From af749cad0fa84d532d6647381cae69a957b9d8b9 Mon Sep 17 00:00:00 2001 From: anorth <445306+anorth@users.noreply.github.com> Date: Wed, 6 Apr 2022 13:43:15 +1000 Subject: [PATCH 01/10] Use new ExitCode type and values. --- Cargo.lock | 44 ++- Cargo.toml | 16 +- actors/account/Cargo.toml | 2 +- actors/account/src/lib.rs | 2 +- actors/account/tests/account_actor_test.rs | 8 +- actors/cron/Cargo.toml | 2 +- actors/cron/src/lib.rs | 2 +- actors/cron/tests/cron_actor_test.rs | 8 +- actors/init/Cargo.toml | 2 +- actors/init/src/lib.rs | 6 +- actors/init/tests/init_actor_test.rs | 10 +- actors/market/Cargo.toml | 2 +- actors/market/src/lib.rs | 98 +++---- actors/market/src/state.rs | 34 +-- actors/market/tests/market_actor_test.rs | 10 +- actors/miner/Cargo.toml | 2 +- actors/miner/src/deadline_state.rs | 40 +-- actors/miner/src/lib.rs | 254 ++++++++---------- actors/miner/src/partition_state.rs | 2 +- actors/miner/src/sectors.rs | 2 +- actors/miner/src/state.rs | 20 +- .../tests/miner_actor_test_construction.rs | 16 +- actors/miner/tests/miner_actor_test_wpost.rs | 30 +-- actors/miner/tests/util.rs | 50 ++-- actors/multisig/Cargo.toml | 2 +- actors/multisig/src/lib.rs | 52 ++-- actors/multisig/tests/multisig_actor_test.rs | 16 +- actors/multisig/tests/util.rs | 2 +- actors/paych/Cargo.toml | 2 +- actors/paych/src/lib.rs | 30 +-- actors/paych/tests/paych_actor_test.rs | 30 +-- actors/power/Cargo.toml | 2 +- actors/power/src/lib.rs | 61 +++-- actors/power/src/state.rs | 8 +- actors/power/tests/harness/mod.rs | 2 +- actors/reward/Cargo.toml | 2 +- actors/reward/src/lib.rs | 2 +- actors/reward/tests/reward_actor_test.rs | 14 +- actors/runtime/Cargo.toml | 2 +- actors/runtime/src/actor_error.rs | 79 +++--- actors/runtime/src/runtime/fvm.rs | 53 ++-- actors/runtime/src/runtime/mod.rs | 3 +- actors/runtime/src/test_utils.rs | 20 +- actors/runtime/src/util/cbor.rs | 10 +- actors/runtime/src/util/chaos/mod.rs | 6 +- actors/runtime/src/util/downcast.rs | 10 +- actors/system/Cargo.toml | 2 +- actors/system/src/lib.rs | 4 +- actors/verifreg/Cargo.toml | 2 +- actors/verifreg/src/lib.rs | 90 +++---- actors/verifreg/tests/verifreg_actor_test.rs | 42 +-- test_vm/Cargo.toml | 2 +- 52 files changed, 601 insertions(+), 611 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 66e532e56..64fadc877 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -550,7 +550,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "num-derive", "num-traits", "serde", @@ -581,7 +581,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "log", "num-derive", "num-traits", @@ -598,7 +598,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "log", "num-derive", "num-traits", @@ -618,7 +618,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "libipld-core", "log", "num-derive", @@ -643,7 +643,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "itertools", "lazy_static", "log", @@ -664,7 +664,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "indexmap", "integer-encoding", "num-derive", @@ -683,7 +683,7 @@ dependencies = [ "fvm_ipld_amt", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "num-derive", "num-traits", "serde", @@ -699,7 +699,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "indexmap", "integer-encoding", "lazy_static", @@ -716,7 +716,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "lazy_static", "log", "num-derive", @@ -732,7 +732,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "num-derive", "num-traits", "serde", @@ -748,7 +748,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "lazy_static", "num-derive", "num-traits", @@ -770,7 +770,7 @@ dependencies = [ "fvm_ipld_encoding", "fvm_ipld_hamt", "fvm_sdk", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "getrandom", "hex", "indexmap", @@ -927,8 +927,6 @@ dependencies = [ [[package]] name = "fvm_ipld_amt" version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3394e5f9c2adb4d586519bc24bbfd659366e01e7ffa6cda676be94a62bab474" dependencies = [ "ahash", "anyhow", @@ -944,8 +942,6 @@ dependencies = [ [[package]] name = "fvm_ipld_bitfield" version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9011349297962982b8ab2663c220034525ec0f95f408c2b561d3d98867f1a803" dependencies = [ "cs_serde_bytes", "fvm_ipld_encoding", @@ -957,8 +953,6 @@ dependencies = [ [[package]] name = "fvm_ipld_blockstore" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1985eae58ec2fbf54535ce115c72a2141459fb7fb4ff7379e17bffae0e302578" dependencies = [ "anyhow", "cid", @@ -981,8 +975,6 @@ dependencies = [ [[package]] name = "fvm_ipld_encoding" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43bd635987aac46a753ec81767713af35cb50f182c7cc49d3a429643ede0e709" dependencies = [ "anyhow", "cid", @@ -998,8 +990,6 @@ dependencies = [ [[package]] name = "fvm_ipld_hamt" version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a03c6ae361a882360bc0c0f47265b294429f096baa8d9467247bbd62c6a6683c" dependencies = [ "anyhow", "byteorder", @@ -1019,12 +1009,10 @@ dependencies = [ [[package]] name = "fvm_sdk" version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee9d472c4f0ad63f91a23b2ef72d9015935a3be040fa3a0ee3a0d6c4549e394" dependencies = [ "cid", "fvm_ipld_encoding", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "lazy_static", "log", "num-traits", @@ -1063,9 +1051,7 @@ dependencies = [ [[package]] name = "fvm_shared" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d1f6ca4fb268d06287c26bc96d7f9e6ac161557b7d70cf557550a186d0714b5" +version = "0.4.1" dependencies = [ "anyhow", "bimap", @@ -1690,7 +1676,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.0", + "fvm_shared 0.4.1", "indexmap", "log", "num-derive", diff --git a/Cargo.toml b/Cargo.toml index d8098f2c6..552230c38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,14 +54,14 @@ members = [ ## Uncomment entries below when working locally on ref-fvm and this repo simultaneously. ## Assumes the ref-fvm checkout is in a sibling directory with the same name. ## (Valid once FVM modules are published to crates.io) -#[patch.crates-io] -#fvm_shared = { path = "../ref-fvm/shared" } -#fvm_sdk = { path = "../ref-fvm/sdk" } -#fvm_ipld_hamt = { path = "../ref-fvm/ipld/hamt" } -#fvm_ipld_amt = { path = "../ref-fvm/ipld/amt" } -#fvm_ipld_bitfield = { path = "../ref-fvm/ipld/bitfield"} -#fvm_ipld_encoding = { path = "../ref-fvm/ipld/encoding"} -#fvm_ipld_blockstore = { path = "../ref-fvm/ipld/blockstore"} +[patch.crates-io] +fvm_shared = { path = "../ref-fvm/shared" } +fvm_sdk = { path = "../ref-fvm/sdk" } +fvm_ipld_hamt = { path = "../ref-fvm/ipld/hamt" } +fvm_ipld_amt = { path = "../ref-fvm/ipld/amt" } +fvm_ipld_bitfield = { path = "../ref-fvm/ipld/bitfield"} +fvm_ipld_encoding = { path = "../ref-fvm/ipld/encoding"} +fvm_ipld_blockstore = { path = "../ref-fvm/ipld/blockstore"} [profile.wasm] inherits = "release" diff --git a/actors/account/Cargo.toml b/actors/account/Cargo.toml index f412e59a8..efd0bee10 100644 --- a/actors/account/Cargo.toml +++ b/actors/account/Cargo.toml @@ -14,7 +14,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/account/src/lib.rs b/actors/account/src/lib.rs index b1e17864e..e4a7953ce 100644 --- a/actors/account/src/lib.rs +++ b/actors/account/src/lib.rs @@ -82,7 +82,7 @@ impl ActorCode for Actor { let addr = Self::pubkey_address(rt)?; Ok(RawBytes::serialize(addr)?) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/account/tests/account_actor_test.rs b/actors/account/tests/account_actor_test.rs index b63652de9..53679e72e 100644 --- a/actors/account/tests/account_actor_test.rs +++ b/actors/account/tests/account_actor_test.rs @@ -51,18 +51,18 @@ macro_rules! account_tests { account_tests! { happy_construct_secp256k1_address: ( Address::new_secp256k1(&[2; fvm_shared::address::SECP_PUB_LEN]).unwrap(), - ExitCode::Ok + ExitCode::OK ), happy_construct_bls_address: ( Address::new_bls(&[1; fvm_shared::address::BLS_PUB_LEN]).unwrap(), - ExitCode::Ok + ExitCode::OK ), fail_construct_id_address: ( Address::new_id(1), - ExitCode::ErrIllegalArgument + ExitCode::USR_ILLEGAL_ARGUMENT ), fail_construct_actor_address: ( Address::new_actor(&[1, 2, 3]), - ExitCode::ErrIllegalArgument + ExitCode::USR_ILLEGAL_ARGUMENT ), } diff --git a/actors/cron/Cargo.toml b/actors/cron/Cargo.toml index 552837d31..3df75a4f4 100644 --- a/actors/cron/Cargo.toml +++ b/actors/cron/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" log = "0.4.14" diff --git a/actors/cron/src/lib.rs b/actors/cron/src/lib.rs index 000ca6126..d33415afe 100644 --- a/actors/cron/src/lib.rs +++ b/actors/cron/src/lib.rs @@ -100,7 +100,7 @@ impl ActorCode for Actor { Self::epoch_tick(rt)?; Ok(RawBytes::default()) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/cron/tests/cron_actor_test.rs b/actors/cron/tests/cron_actor_test.rs index 66773a432..acc350627 100644 --- a/actors/cron/tests/cron_actor_test.rs +++ b/actors/cron/tests/cron_actor_test.rs @@ -73,7 +73,7 @@ fn epoch_tick_with_entries() { RawBytes::default(), 0u8.into(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); rt.expect_send( entry2.receiver, @@ -81,7 +81,7 @@ fn epoch_tick_with_entries() { RawBytes::default(), 0u8.into(), RawBytes::default(), - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, ); rt.expect_send( entry3.receiver, @@ -89,7 +89,7 @@ fn epoch_tick_with_entries() { RawBytes::default(), 0u8.into(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); rt.expect_send( entry4.receiver, @@ -97,7 +97,7 @@ fn epoch_tick_with_entries() { RawBytes::default(), 0u8.into(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); epoch_tick_and_verify(&mut rt); diff --git a/actors/init/Cargo.toml b/actors/init/Cargo.toml index ec4f88c57..ea6412be2 100644 --- a/actors/init/Cargo.toml +++ b/actors/init/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_hamt = "0.4.0" serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" diff --git a/actors/init/src/lib.rs b/actors/init/src/lib.rs index 118a3376c..18cd9ddfe 100644 --- a/actors/init/src/lib.rs +++ b/actors/init/src/lib.rs @@ -44,7 +44,7 @@ impl Actor { let sys_ref: &Address = &SYSTEM_ACTOR_ADDR; rt.validate_immediate_caller_is(std::iter::once(sys_ref))?; let state = State::new(rt.store(), params.network_name).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct init actor state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct init actor state") })?; rt.create(&state)?; @@ -87,7 +87,7 @@ impl Actor { // Store mapping of pubkey or actor address to actor ID let id_address: ActorID = rt.transaction(|s: &mut State, rt| { s.map_address_to_new_id(rt.store(), &robust_address).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to allocate ID address") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to allocate ID address") }) })?; @@ -126,7 +126,7 @@ impl ActorCode for Actor { let res = Self::exec(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::serialize(res)?) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/init/tests/init_actor_test.rs b/actors/init/tests/init_actor_test.rs index d6c9796f6..18be9d29f 100644 --- a/actors/init/tests/init_actor_test.rs +++ b/actors/init/tests/init_actor_test.rs @@ -72,7 +72,7 @@ fn create_2_payment_channels() { RawBytes::serialize(&fake_params).unwrap(), balance, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let exec_ret = exec_and_verify(&mut rt, *PAYCH_ACTOR_CODE_ID, &fake_params).unwrap(); @@ -113,7 +113,7 @@ fn create_storage_miner() { RawBytes::serialize(&fake_params).unwrap(), 0u8.into(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let exec_ret = exec_and_verify(&mut rt, *MINER_ACTOR_CODE_ID, &fake_params).unwrap(); @@ -163,7 +163,7 @@ fn create_multisig_actor() { RawBytes::serialize(&fake_params).unwrap(), 0u8.into(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); // Return should have been successful. Check the returned addresses @@ -197,7 +197,7 @@ fn sending_constructor_failure() { RawBytes::serialize(&fake_params).unwrap(), 0u8.into(), RawBytes::default(), - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, ); let error = exec_and_verify(&mut rt, *MINER_ACTOR_CODE_ID, &fake_params) @@ -207,7 +207,7 @@ fn sending_constructor_failure() { assert_eq!( error_exit_code, - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "Exit Code that is returned is not ErrIllegalState" ); diff --git a/actors/market/Cargo.toml b/actors/market/Cargo.toml index bd95afb0e..f355c2c51 100644 --- a/actors/market/Cargo.toml +++ b/actors/market/Cargo.toml @@ -16,7 +16,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } fvm_ipld_hamt = "0.4.0" -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_bitfield = "0.5.0" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/market/src/lib.rs b/actors/market/src/lib.rs index 40cecef41..e29d3869b 100644 --- a/actors/market/src/lib.rs +++ b/actors/market/src/lib.rs @@ -93,7 +93,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&*SYSTEM_ACTOR_ADDR))?; let st = State::new(rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "Failed to create market state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to create market state") })?; rt.create(&st)?; Ok(()) @@ -126,18 +126,18 @@ impl Actor { .with_locked_table(Permission::Write) .build() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load state") })?; msm.escrow_table.as_mut().unwrap().add(&nominal, &msg_value).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to add balance to escrow table", ) })?; msm.commit_state().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush state") })?; Ok(()) @@ -171,14 +171,14 @@ impl Actor { .with_locked_table(Permission::Write) .build() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load state") })?; // The withdrawable amount might be slightly less than nominal // depending on whether or not all relevant entries have been processed // by cron let min_balance = msm.locked_table.as_ref().unwrap().get(&nominal).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get locked balance") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get locked balance") })?; let ex = msm @@ -188,13 +188,13 @@ impl Actor { .subtract_with_minimum(&nominal, ¶ms.amount, &min_balance) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to subtract from escrow table", ) })?; msm.commit_state().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush state") })?; Ok(ex) @@ -275,7 +275,7 @@ impl Actor { .with_escrow_table(Permission::ReadOnly) .with_locked_table(Permission::ReadOnly) .build() - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to load msm"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load msm"))?; for (di, mut deal) in params.deals.into_iter().enumerate() { // drop malformed deals @@ -309,7 +309,7 @@ impl Actor { let client_balance_ok = msm.balance_covered(client, lockup).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to check client balance coverage", ) })?; @@ -322,7 +322,7 @@ impl Actor { let provider_balance_ok = msm.balance_covered(provider, &total_provider_lockup).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to check provider balance coverage", ) })?; @@ -347,7 +347,7 @@ impl Actor { let duplicate_in_state = msm.pending_deals.as_ref().unwrap().has(&pcid.to_bytes()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to check for existence of deal proposal", ) })?; @@ -411,7 +411,7 @@ impl Actor { .with_locked_table(Permission::Write) .build() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load state") })?; // All storage dealProposals will be added in an atomic transaction; this operation will be unrolled if any of them fails. // This should only fail on programmer error because all expected invalid conditions should be filtered in the first set of checks. @@ -423,10 +423,10 @@ impl Actor { let pcid = valid_proposal_cids[vid]; msm.pending_deals.as_mut().unwrap().put(pcid.to_bytes().into()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to set pending deal") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to set pending deal") })?; msm.deal_proposals.as_mut().unwrap().set(id, valid_deal.proposal.clone()).map_err( - |e| e.downcast_default(ExitCode::ErrIllegalState, "failed to set deal"), + |e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to set deal"), )?; // We randomize the first epoch for when the deal will be processed so an attacker isn't able to @@ -434,14 +434,14 @@ impl Actor { let process_epoch = gen_rand_next_epoch(valid_deal.proposal.start_epoch, id); msm.deals_by_epoch.as_mut().unwrap().put(process_epoch, id).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to set deal ops by epoch") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to set deal ops by epoch") })?; new_deal_ids.push(id); } msm.commit_state().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush state") })?; Ok(()) })?; @@ -467,7 +467,7 @@ impl Actor { let st: State = rt.state()?; let proposals = DealArray::load(&st.proposals, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load deal proposals") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deal proposals") })?; let mut weights = Vec::with_capacity(params.sectors.len()); @@ -481,7 +481,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to validate deal proposals for activation", ) })?; @@ -514,7 +514,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to validate deal proposals for activation", ) })?; @@ -525,7 +525,7 @@ impl Actor { .with_deal_proposals(Permission::ReadOnly) .build() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load state") })?; for deal_id in params.deal_ids { @@ -533,7 +533,7 @@ impl Actor { // state method, possibly batched over all deal ids at once. let s = msm.deal_states.as_ref().unwrap().get(deal_id).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get state for deal_id ({})", deal_id), ) })?; @@ -552,7 +552,7 @@ impl Actor { .get(deal_id) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get deal_id ({})", deal_id), ) })? @@ -565,7 +565,7 @@ impl Actor { let has = msm.pending_deals.as_ref().unwrap().has(&propc.to_bytes()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get pending proposal ({})", propc), ) })?; @@ -591,14 +591,14 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to set deal state {}", deal_id), ) })?; } msm.commit_state().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush state") })?; Ok(()) })?; @@ -626,12 +626,12 @@ impl Actor { .with_deal_proposals(Permission::ReadOnly) .build() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load state") })?; for id in params.deal_ids { let deal = msm.deal_proposals.as_ref().unwrap().get(id).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get deal proposal") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get deal proposal") })?; // The deal may have expired and been deleted before the sector is terminated. // Nothing to do, but continue execution for the other deals. @@ -663,7 +663,7 @@ impl Actor { .unwrap() .get(id) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get deal state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get deal state") })? // A deal with a proposal but no state is not activated, but then it should not be // part of a sector that is terminating. @@ -681,14 +681,14 @@ impl Actor { msm.deal_states.as_mut().unwrap().set(id, state).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to set deal state ({})", id), ) })?; } msm.commit_state().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush state") })?; Ok(()) })?; @@ -708,7 +708,7 @@ impl Actor { let st: State = rt.state()?; let proposals = DealArray::load(&st.proposals, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load deal proposals") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deal proposals") })?; let mut commds = Vec::with_capacity(params.inputs.len()); for comm_input in params.inputs.iter() { @@ -718,7 +718,7 @@ impl Actor { .get(*deal_id) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get deal_id ({})", deal_id), ) })? @@ -730,7 +730,7 @@ impl Actor { let commd = rt.compute_unsealed_sector_cid(comm_input.sector_type, &pieces).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "failed to compute unsealed sector CID", ) })?; @@ -763,7 +763,7 @@ impl Actor { .with_pending_proposals(Permission::Write) .build() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load state") })?; for i in (last_cron + 1)..=rt.curr_epoch() { @@ -781,7 +781,7 @@ impl Actor { Ok(()) }) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to set deal state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to set deal state") })?; for deal_id in deal_ids { @@ -792,7 +792,7 @@ impl Actor { .get(deal_id) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get deal_id ({})", deal_id), ) })? @@ -813,7 +813,7 @@ impl Actor { .get(deal_id) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to get deal state", ) })? @@ -844,7 +844,7 @@ impl Actor { let deleted = msm.deal_proposals.as_mut().unwrap().delete(deal_id).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to delete deal proposal {}", deal_id), ) })?; @@ -863,7 +863,7 @@ impl Actor { .delete(&dcid.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to delete pending proposal {}", deal_id), ) })? @@ -885,7 +885,7 @@ impl Actor { .delete(&dcid.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to delete pending proposal {}", dcid), ) })? @@ -926,7 +926,7 @@ impl Actor { let deleted = msm.deal_states.as_mut().unwrap().delete(deal_id).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to delete deal state", ) })?; @@ -940,7 +940,7 @@ impl Actor { let deleted = msm.deal_proposals.as_mut().unwrap().delete(deal_id).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to delete deal proposal", ) })?; @@ -970,7 +970,7 @@ impl Actor { state.last_updated_epoch = curr_epoch; msm.deal_states.as_mut().unwrap().set(deal_id, state).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to set deal state", ) })?; @@ -984,7 +984,7 @@ impl Actor { } msm.deals_by_epoch.as_mut().unwrap().remove_all(i).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to delete deal ops for epoch {}", i), ) })?; @@ -994,7 +994,7 @@ impl Actor { for (epoch, deals) in updates_needed { msm.deals_by_epoch.as_mut().unwrap().put_many(epoch, &deals).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to reinsert deal IDs for epoch {}", epoch), ) })?; @@ -1003,7 +1003,7 @@ impl Actor { msm.st.last_cron = rt.curr_epoch(); msm.commit_state().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush state") })?; Ok(()) })?; @@ -1235,7 +1235,7 @@ where // Generate unsigned bytes let sv_bz = serialize_vec(&proposal.proposal, "deal proposal")?; rt.verify_signature(&proposal.client_signature, &proposal.proposal.client, &sv_bz).map_err( - |e| e.downcast_default(ExitCode::ErrIllegalArgument, "signature proposal invalid"), + |e| e.downcast_default(ExitCode::USR_ILLEGAL_ARGUMENT, "signature proposal invalid"), )?; Ok(()) @@ -1351,7 +1351,7 @@ impl ActorCode for Actor { Self::cron_tick(rt)?; Ok(RawBytes::default()) } - None => Err(actor_error!(SysErrInvalidMethod, "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), } } } diff --git a/actors/market/src/state.rs b/actors/market/src/state.rs index 6ae2aff2b..9a8317d04 100644 --- a/actors/market/src/state.rs +++ b/actors/market/src/state.rs @@ -408,7 +408,7 @@ where self.unlock_balance(&deal.client, &payment_remaining, Reason::ClientStorageFee) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to unlock remaining client storage fee", ) })?; @@ -417,7 +417,7 @@ where self.unlock_balance(&deal.client, &deal.client_collateral, Reason::ClientCollateral) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to unlock client collateral", ) })?; @@ -425,7 +425,7 @@ where // slash provider collateral let slashed = deal.provider_collateral.clone(); self.slash_balance(&deal.provider, &slashed, Reason::ProviderCollateral) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "slashing balance"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "slashing balance"))?; return Ok((slashed, EPOCH_UNDEFINED, true)); } @@ -453,14 +453,14 @@ where self.unlock_balance(&deal.client, &deal.total_storage_fee(), Reason::ClientStorageFee) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failure unlocking client storage fee", ) })?; self.unlock_balance(&deal.client, &deal.client_collateral, Reason::ClientCollateral) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failure unlocking client collateral") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failure unlocking client collateral") })?; let amount_slashed = @@ -468,13 +468,13 @@ where let amount_remaining = deal.provider_balance_requirement() - &amount_slashed; self.slash_balance(&deal.provider, &amount_slashed, Reason::ProviderCollateral).map_err( - |e| e.downcast_default(ExitCode::ErrIllegalState, "failed to slash balance"), + |e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to slash balance"), )?; self.unlock_balance(&deal.provider, &amount_remaining, Reason::ProviderCollateral) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to unlock deal provider balance", ) })?; @@ -498,7 +498,7 @@ where self.unlock_balance(&deal.provider, &deal.provider_collateral, Reason::ProviderCollateral) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed unlocking deal provider balance", ) })?; @@ -506,7 +506,7 @@ where self.unlock_balance(&deal.client, &deal.client_collateral, Reason::ClientCollateral) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed unlocking deal client balance", ) })?; @@ -527,10 +527,10 @@ where amount_to_lock: &TokenAmount, ) -> anyhow::Result { let prev_locked = self.locked_table.as_ref().unwrap().get(&addr).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get locked balance") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get locked balance") })?; let escrow_balance = self.escrow_table.as_ref().unwrap().get(&addr).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get escrow balance") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get escrow balance") })?; Ok((prev_locked + amount_to_lock) <= escrow_balance) } @@ -545,11 +545,11 @@ where } let prev_locked = self.locked_table.as_ref().unwrap().get(addr).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get locked balance") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get locked balance") })?; let escrow_balance = self.escrow_table.as_ref().unwrap().get(addr).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get escrow balance") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get escrow balance") })?; if &prev_locked + amount > escrow_balance { @@ -560,7 +560,7 @@ where } self.locked_table.as_mut().unwrap().add(addr, amount).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to add locked balance") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to add locked balance") })?; Ok(()) } @@ -629,17 +629,17 @@ where .as_mut() .unwrap() .must_subtract(from_addr, amount) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "subtract from escrow"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "subtract from escrow"))?; self.unlock_balance(from_addr, amount, Reason::ClientStorageFee) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "subtract from locked"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "subtract from locked"))?; // Add subtracted amount to the recipient self.escrow_table .as_mut() .unwrap() .add(to_addr, amount) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "add to escrow"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "add to escrow"))?; Ok(()) } diff --git a/actors/market/tests/market_actor_test.rs b/actors/market/tests/market_actor_test.rs index 2ff810cbe..c32c10a5e 100644 --- a/actors/market/tests/market_actor_test.rs +++ b/actors/market/tests/market_actor_test.rs @@ -298,7 +298,7 @@ fn withdraw_provider_to_owner() { RawBytes::default(), withdraw_amount.clone(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let params = @@ -337,7 +337,7 @@ fn withdraw_non_provider() { RawBytes::default(), withdraw_amount.clone(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let params = WithdrawBalanceParams { provider_or_client: client_addr, amount: withdraw_amount }; @@ -372,7 +372,7 @@ fn client_withdraw_more_than_available() { RawBytes::default(), amount, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let params = WithdrawBalanceParams { provider_or_client: client_addr, amount: withdraw_amount }; @@ -411,7 +411,7 @@ fn worker_withdraw_more_than_available() { RawBytes::default(), amount, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let params = @@ -446,7 +446,7 @@ fn expect_provider_control_address( RawBytes::default(), TokenAmount::from(0u8), RawBytes::serialize(return_value).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); } diff --git a/actors/miner/Cargo.toml b/actors/miner/Cargo.toml index 6452468ce..af6546ce0 100644 --- a/actors/miner/Cargo.toml +++ b/actors/miner/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_bitfield = "0.5.0" fvm_ipld_amt = { version = "0.4.0", features = ["go-interop"] } fvm_ipld_hamt = "0.4.0" diff --git a/actors/miner/src/deadline_state.rs b/actors/miner/src/deadline_state.rs index 5f1bfab99..8ef2ca93a 100644 --- a/actors/miner/src/deadline_state.rs +++ b/actors/miner/src/deadline_state.rs @@ -253,7 +253,7 @@ impl Deadline { .get(partition_idx) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to lookup partition {}", partition_idx), ) })? @@ -273,7 +273,7 @@ impl Deadline { .get(partition_idx) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to lookup partition snapshot {}", partition_idx), ) })? @@ -760,7 +760,7 @@ impl Deadline { .get(partition_idx) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load partition {}", partition_idx), ) })? @@ -791,14 +791,14 @@ impl Deadline { partitions.set(partition_idx, partition).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to store partition {}", partition_idx), ) })?; } self.partitions = partitions.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to store partitions root") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to store partitions root") })?; self.add_expiration_partitions( @@ -809,7 +809,7 @@ impl Deadline { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to update expirations for partitions with faults", ) })?; @@ -831,7 +831,7 @@ impl Deadline { .get(partition_idx) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load partition {}", partition_idx), ) })? @@ -844,7 +844,7 @@ impl Deadline { partitions.set(partition_idx, partition).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update partition {}", partition_idx), ) })?; @@ -853,7 +853,7 @@ impl Deadline { // Power is not regained until the deadline end, when the recovery is confirmed. self.partitions = partitions.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to store partitions root") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to store partitions root") })?; Ok(()) @@ -870,7 +870,7 @@ impl Deadline { sectors: Cid, ) -> Result<(PowerPair, PowerPair), ActorError> { let mut partitions = self.partitions_amt(store).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load partitions") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load partitions") })?; let mut detected_any = false; @@ -888,7 +888,7 @@ impl Deadline { .get(partition_idx) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load partition {}", partition_idx), ) })? @@ -910,7 +910,7 @@ impl Deadline { .record_missed_post(store, fault_expiration_epoch, quant) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to record missed PoSt for partition {}", partition_idx), ) })?; @@ -925,7 +925,7 @@ impl Deadline { // Save new partition state. partitions.set(partition_idx, partition).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update partition {}", partition_idx), ) })?; @@ -939,7 +939,7 @@ impl Deadline { // Save modified deadline state. if detected_any { self.partitions = partitions.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to store partitions") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to store partitions") })?; } @@ -951,7 +951,7 @@ impl Deadline { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to update deadline expiration queue", ) })?; @@ -966,7 +966,7 @@ impl Deadline { ) .flush() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to clear pending proofs array") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to clear pending proofs array") })?; // only snapshot sectors if there's a proof that might be disputed (this is equivalent to asking if the OptimisticPoStSubmissionsSnapshot is empty) @@ -977,7 +977,7 @@ impl Deadline { Array::<(), BS>::new_with_bit_width(store, SECTORS_AMT_BITWIDTH).flush().map_err( |e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to clear sectors snapshot array", ) }, @@ -1201,7 +1201,7 @@ impl Deadline { // This will be rolled back if the method aborts with a failed proof. partitions.set(post.index, partition).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update partition {}", post.index), ) })?; @@ -1219,7 +1219,7 @@ impl Deadline { self.add_expiration_partitions(store, fault_expiration, &rescheduled_partitions, quant) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to update expirations for partitions with faults", ) })?; @@ -1229,7 +1229,7 @@ impl Deadline { self.faulty_power += &new_faulty_power_total; self.partitions = partitions.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to persist partitions") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to persist partitions") })?; // Collect all sectors, faults, and recoveries for proof verification. diff --git a/actors/miner/src/lib.rs b/actors/miner/src/lib.rs index 7814a158e..f38276896 100644 --- a/actors/miner/src/lib.rs +++ b/actors/miner/src/lib.rs @@ -6,7 +6,7 @@ use std::collections::BTreeMap; use std::iter; use std::ops::Neg; -use anyhow::anyhow; +use anyhow::{anyhow, Error}; pub use bitfield_queue::*; use byteorder::{BigEndian, ByteOrder, WriteBytesExt}; use cid::multihash::Code; @@ -37,7 +37,6 @@ use fvm_shared::econ::TokenAmount; // diagnose the problem. use fil_actors_runtime::cbor::{deserialize, serialize, serialize_vec}; use fvm_shared::actor::builtin::{Type, CALLER_TYPES_SIGNABLE}; -use fvm_shared::error::ExitCode::ErrPlaceholder as ErrBalanceInvariantBroken; use fvm_shared::error::*; use fvm_shared::randomness::*; use fvm_shared::reward::ThisEpochRewardReturn; @@ -118,6 +117,8 @@ pub enum Method { ProveReplicaUpdates = 27, } +pub const ERR_BALANCE_INVARIANTS_BROKEN: ExitCode = ExitCode::new(1000); + /// Miner Actor /// here in order to update the Power Actor to v3. pub struct Actor; @@ -152,7 +153,7 @@ impl Actor { assign_proving_period_offset(policy, rt.message().receiver(), current_epoch, blake2b) .map_err(|e| { e.downcast_default( - ExitCode::ErrSerialization, + ExitCode::USR_SERIALIZATION, "failed to assign proving period offset", ) })?; @@ -185,12 +186,12 @@ impl Actor { params.window_post_proof_type, )?; let info_cid = rt.store().put_cbor(&info, Blake2b256).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct illegal state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state") })?; let st = State::new(policy, rt.store(), info_cid, period_start, deadline_idx).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct state") })?; rt.create(&st)?; @@ -250,7 +251,7 @@ impl Actor { } state.save_info(rt.store(), &info).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "could not save miner info") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "could not save miner info") })?; Ok(()) @@ -321,7 +322,7 @@ impl Actor { } state.save_info(rt.store(), &info).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save miner info") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save miner info") })?; Ok(()) @@ -345,7 +346,7 @@ impl Actor { info.peer_id = params.new_id; state.save_info(rt.store(), &info).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "could not save miner info") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "could not save miner info") })?; Ok(()) @@ -373,7 +374,7 @@ impl Actor { info.multi_address = params.new_multi_addrs; state.save_info(rt.store(), &info).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "could not save miner info") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "could not save miner info") })?; Ok(()) @@ -542,7 +543,7 @@ impl Actor { } let sectors = Sectors::load(rt.store(), &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors") })?; let mut deadlines = @@ -551,7 +552,7 @@ impl Actor { let mut deadline = deadlines.load_deadline(rt.policy(), rt.store(), params.deadline).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", params.deadline), ) })?; @@ -578,7 +579,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!( "failed to process post submission for deadline {}", params.deadline @@ -605,7 +606,7 @@ impl Actor { .record_post_proofs(rt.store(), &post_result.partitions, ¶ms.proofs) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to record proof for optimistic verification", ) })? @@ -617,7 +618,7 @@ impl Actor { .load_for_proof(&post_result.sectors, &post_result.ignored_sectors) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load sectors for post verification", ) })?; @@ -629,14 +630,14 @@ impl Actor { deadlines.update_deadline(policy, rt.store(), params.deadline, &deadline).map_err( |e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update deadline {}", deadline_idx), ) }, )?; state.save_deadlines(rt.store(), deadlines).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; Ok(post_result) @@ -649,9 +650,7 @@ impl Actor { request_update_power(rt, post_result.power_delta)?; let state: State = rt.state()?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } @@ -710,7 +709,7 @@ impl Actor { let store = rt.store(); let precommits = state.get_all_precommitted_sectors(store, sector_numbers).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get precommits") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get precommits") })?; // compute data commitments and validate each precommit @@ -814,7 +813,7 @@ impl Actor { infos: svis, }) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalArgument, "aggregate seal verify failed") + e.downcast_default(ExitCode::USR_ILLEGAL_ARGUMENT, "aggregate seal verify failed") })?; let rew = request_current_epoch_block_reward(rt)?; @@ -844,9 +843,7 @@ impl Actor { )); } burn_funds(rt, aggregate_fee)?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } @@ -880,7 +877,7 @@ impl Actor { let sector_store = rt.store().clone(); let mut sectors = Sectors::load(§or_store, &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors array") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array") })?; let mut power_delta = PowerPair::zero(); @@ -1085,7 +1082,7 @@ impl Actor { .load_deadline(rt.policy(),rt.store(), dl_idx) .map_err(|e| e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", dl_idx), ) )?; @@ -1094,7 +1091,7 @@ impl Actor { .partitions_amt(rt.store()) .map_err(|e| e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load partitions for deadline {}", dl_idx), ) )?; @@ -1128,7 +1125,7 @@ impl Actor { ) .map_err(|e| e.downcast_default( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, format!("failed to verify replica proof for sector {}", with_details.sector_info.sector_number), ) )?; @@ -1214,7 +1211,7 @@ impl Actor { .get(with_details.update.partition) .map_err(|e| e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {} partition {}", with_details.update.deadline, with_details.update.partition), ) )? @@ -1230,7 +1227,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to replace sector at deadline {} partition {}", with_details.update.deadline, with_details.update.partition), ) })?; @@ -1242,7 +1239,7 @@ impl Actor { .set(with_details.update.partition, partition) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save deadline {} partition {}", with_details.update.deadline, with_details.update.partition), ) })?; @@ -1253,7 +1250,7 @@ impl Actor { deadline.partitions = partitions.flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save partitions for deadline {}", dl_idx), ) })?; @@ -1262,7 +1259,7 @@ impl Actor { .update_deadline(rt.policy(), rt.store(), dl_idx, &deadline) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save deadline {}", dl_idx), ) })?; @@ -1289,16 +1286,16 @@ impl Actor { // Overwrite sector infos. sectors.store(new_sectors).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to update sector infos", ) })?; state.sectors = sectors.amt.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save sectors") })?; state.save_deadlines(rt.store(), deadlines).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; BitField::try_from_bits(succeeded).map_err(|_|{ @@ -1381,7 +1378,7 @@ impl Actor { let mut dl_current = deadlines_current .load_deadline(policy, rt.store(), params.deadline) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load deadline") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deadline") })?; // Take the post from the snapshot for dispute. @@ -1391,7 +1388,7 @@ impl Actor { let (partitions, proofs) = dl_current.take_post_proofs(rt.store(), params.post_index).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load proof for dispute", ) })?; @@ -1401,7 +1398,7 @@ impl Actor { .load_partitions_for_dispute(rt.store(), partitions) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load partition for dispute", ) })?; @@ -1414,7 +1411,7 @@ impl Actor { let sectors = Sectors::load(rt.store(), &dl_current.sectors_snapshot).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array", ) })?; @@ -1422,7 +1419,7 @@ impl Actor { .load_for_proof(&dispute_info.all_sector_nos, &dispute_info.ignored_sector_nos) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load sectors to dispute window post", ) })?; @@ -1451,20 +1448,20 @@ impl Actor { &mut dispute_info.disputed_sectors, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to declare faults") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to declare faults") })?; deadlines_current .update_deadline(policy, rt.store(), params.deadline, &dl_current) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update deadline {}", params.deadline), ) })?; st.save_deadlines(rt.store(), deadlines_current).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; // --- penalties --- @@ -1495,7 +1492,7 @@ impl Actor { &rt.current_balance(), ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to pay debt") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to pay debt") })?; let to_burn = &penalty_from_vesting + &penalty_from_balance; @@ -1521,9 +1518,7 @@ impl Actor { notify_pledge_changed(rt, &pledge_delta)?; let st: State = rt.state()?; - st.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + st.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } @@ -1630,7 +1625,7 @@ impl Actor { if precommit.replace_capacity { return Err(actor_error!( - SysErrForbidden, + ErrForbidden, "cc upgrade through precommit discontinued, use ProveReplicaUpdate" )); } @@ -1766,11 +1761,11 @@ impl Actor { )?; state.put_precommitted_sectors(store, chain_infos) .map_err(|e| - e.downcast_default(ExitCode::ErrIllegalState, "failed to write pre-committed sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to write pre-committed sectors") )?; state.add_pre_commit_clean_ups(rt.policy(), store, clean_up_events) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to add pre-commit expiry to queue") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to add pre-commit expiry to queue") })?; // Activate miner cron needs_cron = !state.deadline_cron_active; @@ -1779,9 +1774,7 @@ impl Actor { })?; burn_funds(rt, fee_to_burn)?; let state: State = rt.state()?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariant broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; if needs_cron { let new_dl_info = state.deadline_info(rt.policy(), curr_epoch); enroll_cron_event( @@ -1817,7 +1810,7 @@ impl Actor { .get_precommitted_sector(rt.store(), sector_number) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load pre-committed sector {}", sector_number), ) })? @@ -1908,7 +1901,7 @@ impl Actor { let precommited_sectors = st.find_precommitted_sectors(store, ¶ms.sectors).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load pre-committed sectors", ) })?; @@ -2055,7 +2048,7 @@ impl Actor { } let mut sectors = Sectors::load(rt.store(), &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors array") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array") })?; let mut power_delta = PowerPair::zero(); @@ -2066,14 +2059,14 @@ impl Actor { let mut deadline = deadlines.load_deadline(policy, store, deadline_idx).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", deadline_idx), ) })?; let mut partitions = deadline.partitions_amt(store).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load partitions for deadline {}", deadline_idx), ) })?; @@ -2091,7 +2084,7 @@ impl Actor { .get(decl.partition) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load partition {:?}", key), ) })? @@ -2165,7 +2158,7 @@ impl Actor { // Overwrite sector infos. sectors.store(new_sectors.clone()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update sectors {:?}", decl.sectors), ) })?; @@ -2175,7 +2168,7 @@ impl Actor { .replace_sectors(store, &old_sectors, &new_sectors, info.sector_size, quant) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to replace sector expirations at {:?}", key), ) })?; @@ -2185,7 +2178,7 @@ impl Actor { partitions.set(decl.partition, partition).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save partition {:?}", key), ) })?; @@ -2205,7 +2198,7 @@ impl Actor { deadline.partitions = partitions.flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save partitions for deadline {}", deadline_idx), ) })?; @@ -2216,7 +2209,7 @@ impl Actor { deadline.add_expiration_partitions(store, epoch, p_idxs, quant).map_err( |e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!( "failed to add expiration partitions to \ deadline {} epoch {}", @@ -2229,17 +2222,17 @@ impl Actor { deadlines.update_deadline(policy, store, deadline_idx, &deadline).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save deadline {}", deadline_idx), ) })?; } state.sectors = sectors.amt.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save sectors") })?; state.save_deadlines(store, deadlines).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; Ok((power_delta, pledge_delta)) @@ -2338,7 +2331,7 @@ impl Actor { // We're only reading the sectors, so there's no need to save this back. // However, we still want to avoid re-loading this array per-partition. let sectors = Sectors::load(store, &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors") })?; for (deadline_idx, partition_sectors) in to_process.iter() { @@ -2361,7 +2354,7 @@ impl Actor { let mut deadline = deadlines.load_deadline(rt.policy(), store, deadline_idx).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", deadline_idx), ) })?; @@ -2378,7 +2371,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to terminate sectors in deadline {}", deadline_idx), ) })?; @@ -2389,7 +2382,7 @@ impl Actor { deadlines.update_deadline(rt.policy(), store, deadline_idx, &deadline).map_err( |e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update deadline {}", deadline_idx), ) }, @@ -2397,7 +2390,7 @@ impl Actor { } state.save_deadlines(store, deadlines).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; Ok((had_early_terminations, power_delta)) @@ -2421,9 +2414,7 @@ impl Actor { schedule_early_termination_work(rt)?; } let state: State = rt.state()?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariant broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; request_update_power(rt, power_delta)?; Ok(TerminateSectorsReturn { done: !more }) @@ -2485,7 +2476,7 @@ impl Actor { state.load_deadlines(store).map_err(|e| e.wrap("failed to load deadlines"))?; let sectors = Sectors::load(store, &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors array") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array") })?; let mut new_fault_power_total = PowerPair::zero(); @@ -2519,7 +2510,7 @@ impl Actor { let mut deadline = deadlines.load_deadline(policy, store, deadline_idx).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", deadline_idx), ) })?; @@ -2537,14 +2528,14 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to declare faults for deadline {}", deadline_idx), ) })?; deadlines.update_deadline(policy, store, deadline_idx, &deadline).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to store deadline {} partitions", deadline_idx), ) })?; @@ -2553,7 +2544,7 @@ impl Actor { } state.save_deadlines(store, deadlines).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; Ok(new_fault_power_total) @@ -2639,7 +2630,7 @@ impl Actor { state.load_deadlines(store).map_err(|e| e.wrap("failed to load deadlines"))?; let sectors = Sectors::load(store, &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors array") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array") })?; let curr_epoch = rt.curr_epoch(); for (deadline_idx, partition_map) in to_process.iter() { @@ -2671,7 +2662,7 @@ impl Actor { let mut deadline = deadlines.load_deadline(policy, store, deadline_idx).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", deadline_idx), ) })?; @@ -2680,21 +2671,21 @@ impl Actor { .declare_faults_recovered(store, §ors, info.sector_size, partition_map) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to declare recoveries for deadline {}", deadline_idx), ) })?; deadlines.update_deadline(policy, store, deadline_idx, &deadline).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to store deadline {}", deadline_idx), ) })?; } state.save_deadlines(store, deadlines).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save deadlines") })?; Ok(fee_to_burn) @@ -2702,9 +2693,7 @@ impl Actor { burn_funds(rt, fee_to_burn)?; let state: State = rt.state()?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; // Power is not restored yet, but when the recovered sectors are successfully PoSted. Ok(()) @@ -2786,7 +2775,7 @@ impl Actor { let mut deadline = deadlines.load_deadline(policy, store, params_deadline).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load deadline {}", params_deadline), ) })?; @@ -2794,17 +2783,17 @@ impl Actor { let (live, dead, removed_power) = deadline.remove_partitions(store, partitions, quant).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to remove partitions from deadline {}", params_deadline), ) })?; state.delete_sectors(store, &dead).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to delete dead sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to delete dead sectors") })?; let sectors = state.load_sector_infos(store, &live).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load moved sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load moved sectors") })?; let proven = true; let added_power = deadline @@ -2818,7 +2807,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to add back moved sectors", ) })?; @@ -2834,14 +2823,14 @@ impl Actor { deadlines.update_deadline(policy, store, params_deadline, &deadline).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update deadline {}", params_deadline), ) })?; state.save_deadlines(store, deadlines).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to save deadline {}", params_deadline), ) })?; @@ -2972,7 +2961,7 @@ impl Actor { &rt.current_balance(), ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to repay penalty") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to repay penalty") })?; pledge_delta_total -= &penalty_from_vesting; let to_burn = penalty_from_vesting + penalty_from_balance; @@ -2982,9 +2971,7 @@ impl Actor { notify_pledge_changed(rt, &pledge_delta_total)?; burn_funds(rt, to_burn)?; let st: State = rt.state()?; - st.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + st.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } @@ -3004,7 +2991,7 @@ impl Actor { let fault = rt .verify_consensus_fault(¶ms.header1, ¶ms.header2, ¶ms.header_extra) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalArgument, "fault not verified"))? + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_ARGUMENT, "fault not verified"))? .ok_or_else(|| actor_error!(ErrIllegalArgument, "No consensus fault found"))?; if fault.target != rt.message().receiver() { return Err(actor_error!( @@ -3061,7 +3048,7 @@ impl Actor { rt.curr_epoch(), &rt.current_balance(), ) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to pay fees"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to pay fees"))?; let mut burn_amount = &penalty_from_vesting + &penalty_from_balance; pledge_delta -= penalty_from_vesting; @@ -3074,7 +3061,7 @@ impl Actor { rt.curr_epoch() + rt.policy().consensus_fault_ineligibility_duration; st.save_info(rt.store(), &info).map_err(|e| { - e.downcast_default(ExitCode::ErrSerialization, "failed to save miner info") + e.downcast_default(ExitCode::USR_SERIALIZATION, "failed to save miner info") })?; Ok((burn_amount, reward_amount)) @@ -3088,9 +3075,7 @@ impl Actor { notify_pledge_changed(rt, &pledge_delta)?; let state: State = rt.state()?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } @@ -3131,7 +3116,7 @@ impl Actor { // Unlock vested funds so we can spend them. let newly_vested = state.unlock_vested_funds(rt.store(), rt.curr_epoch()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "Failed to vest fund") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to vest fund") })?; // available balance already accounts for fee debt so it is correct to call @@ -3176,9 +3161,7 @@ impl Actor { burn_funds(rt, fee_to_burn)?; notify_pledge_changed(rt, &newly_vested.neg())?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(WithdrawBalanceReturn { amount_withdrawn: amount_withdrawn.clone() }) } @@ -3201,7 +3184,7 @@ impl Actor { &rt.current_balance(), ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to unlock fee debt") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to unlock fee debt") })?; Ok((from_vesting, from_balance, state.clone())) @@ -3211,9 +3194,7 @@ impl Actor { notify_pledge_changed(rt, &from_vesting.neg())?; burn_funds(rt, burn_amount)?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } @@ -3254,9 +3235,7 @@ impl Actor { } }; let state: State = rt.state()?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariants broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok(()) } } @@ -3287,7 +3266,7 @@ where ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to pop early terminations", ) })?; @@ -3302,7 +3281,7 @@ where let info = get_miner_info(rt.store(), state)?; let sectors = Sectors::load(store, &state.sectors).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors array") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array") })?; let mut total_initial_pledge = TokenAmount::zero(); @@ -3360,7 +3339,7 @@ where &rt.current_balance(), ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to repay penalty") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to repay penalty") })?; penalty = &penalty_from_vesting + penalty_from_balance; @@ -3421,7 +3400,7 @@ where // from locked vesting funds before funds free this epoch. let newly_vested = state .unlock_vested_funds(rt.store(), rt.curr_epoch()) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to vest funds"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to vest funds"))?; pledge_delta_total -= newly_vested; @@ -3433,7 +3412,7 @@ where .cleanup_expired_pre_commits(policy, rt.store(), rt.curr_epoch()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to expire pre-committed sectors", ) })?; @@ -3453,7 +3432,7 @@ where had_early_terminations = have_pending_early_terminations(state); let result = state.advance_deadline(policy, rt.store(), rt.curr_epoch()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to advance deadline") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to advance deadline") })?; // Faults detected by this missed PoSt pay no penalty, but sectors that were already faulty @@ -3484,7 +3463,7 @@ where &rt.current_balance(), ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to unlock penalty") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to unlock penalty") })?; penalty_total = &penalty_from_vesting + penalty_from_balance; @@ -3612,7 +3591,7 @@ where .get_sector(store, params.replace_sector_number) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load sector {}", params.replace_sector_number), ) })? @@ -3679,7 +3658,7 @@ where ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to replace sector {}", params.replace_sector_number), ) })?; @@ -4233,7 +4212,7 @@ where { state .get_info(store) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "could not read miner info")) + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "could not read miner info")) } fn process_pending_worker( @@ -4260,7 +4239,7 @@ where state .save_info(rt.store(), info) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to save miner info")) + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save miner info")) } /// Repays all fee debt and then verifies that the miner has amount needed to cover @@ -4276,7 +4255,7 @@ where RT: Runtime, { let res = state.repay_debts(&rt.current_balance()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "unlocked balance can not repay fee debt") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "unlocked balance can not repay fee debt") })?; info!("RepayDebtsOrAbort was called and succeeded"); Ok(res) @@ -4475,11 +4454,11 @@ where } state.put_sectors(store, new_sectors.clone()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to put new sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to put new sectors") })?; state.delete_precommitted_sectors(store, &new_sector_numbers).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to delete precommited sectors") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to delete precommited sectors") })?; state @@ -4493,7 +4472,7 @@ where ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to assign new sectors to deadlines", ) })?; @@ -4521,9 +4500,7 @@ where .add_initial_pledge(&total_pledge) .map_err(|e| actor_error!(ErrIllegalState, "failed to add initial pledge: {}", e))?; - state.check_balance_invariants(&rt.current_balance()).map_err(|e| { - ActorError::new(ErrBalanceInvariantBroken, format!("balance invariant broken: {}", e)) - })?; + state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; Ok((total_pledge, newly_vested)) })?; @@ -4534,6 +4511,11 @@ where Ok(()) } +// XXX: probably better to push this one level down into state +fn balance_invariants_broken(e: Error) -> ActorError { + ActorError::new_unchecked(ERR_BALANCE_INVARIANTS_BROKEN, format!("balance invariants broken: {}", e)) +} + impl ActorCode for Actor { fn invoke_method( rt: &mut RT, @@ -4653,7 +4635,7 @@ impl ActorCode for Actor { let res = Self::prove_replica_updates(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::serialize(res)?) } - None => Err(actor_error!(SysErrInvalidMethod, "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), } } } diff --git a/actors/miner/src/partition_state.rs b/actors/miner/src/partition_state.rs index cd41fbd85..9c7280737 100644 --- a/actors/miner/src/partition_state.rs +++ b/actors/miner/src/partition_state.rs @@ -761,7 +761,7 @@ impl Partition { quant, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to add skipped faults") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to add skipped faults") })?; // Remove faulty recoveries diff --git a/actors/miner/src/sectors.rs b/actors/miner/src/sectors.rs index 6da3836c6..a0db03587 100644 --- a/actors/miner/src/sectors.rs +++ b/actors/miner/src/sectors.rs @@ -41,7 +41,7 @@ impl<'db, BS: Blockstore> Sectors<'db, BS> { .get(sector_number) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load sector {}", sector_number), ) })? diff --git a/actors/miner/src/state.rs b/actors/miner/src/state.rs index 62215c0c7..6a57ab153 100644 --- a/actors/miner/src/state.rs +++ b/actors/miner/src/state.rs @@ -132,7 +132,7 @@ impl State { let empty_precommit_map = make_empty_map::<_, ()>(store, HAMT_BIT_WIDTH).flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to construct empty precommit map", ) })?; @@ -141,7 +141,7 @@ impl State { .flush() .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to construct empty precommits array", ) })?; @@ -150,27 +150,27 @@ impl State { .flush() .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to construct sectors array", ) })?; let empty_bitfield = store.put_cbor(&BitField::new(), Code::Blake2b256).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct empty bitfield") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct empty bitfield") })?; let deadline = Deadline::new(store)?; let empty_deadline = store.put_cbor(&deadline, Code::Blake2b256).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct illegal state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state") })?; let empty_deadlines = store .put_cbor(&Deadlines::new(policy, empty_deadline), Code::Blake2b256) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct illegal state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state") })?; let empty_vesting_funds_cid = store.put_cbor(&VestingFunds::new(), Code::Blake2b256).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct illegal state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state") })?; Ok(Self { @@ -255,7 +255,7 @@ impl State { .get_cbor(&self.allocated_sectors) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load allocated sectors bitfield", ) })? @@ -277,7 +277,7 @@ impl State { self.allocated_sectors = store.put_cbor(&new_allocation, Code::Blake2b256).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, format!( "failed to store allocated sectors bitfield after adding {:?}", sector_numbers, @@ -723,7 +723,7 @@ impl State { pub fn load_deadlines(&self, store: &BS) -> Result { store .get_cbor::(&self.deadlines) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to load deadlines"))? + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deadlines"))? .ok_or_else( || actor_error!(ErrIllegalState; "failed to load deadlines {}", self.deadlines), ) diff --git a/actors/miner/tests/miner_actor_test_construction.rs b/actors/miner/tests/miner_actor_test_construction.rs index 0afc1d0bf..c55dfe8b8 100644 --- a/actors/miner/tests/miner_actor_test_construction.rs +++ b/actors/miner/tests/miner_actor_test_construction.rs @@ -74,7 +74,7 @@ fn simple_construction() { RawBytes::default(), TokenAmount::from(0), RawBytes::serialize(env.worker_key).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); let result = env @@ -147,7 +147,7 @@ fn control_addresses_are_resolved_during_construction() { RawBytes::default(), TokenAmount::from(0), RawBytes::serialize(env.worker_key).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); let result = env @@ -181,14 +181,14 @@ fn fails_if_control_address_is_not_an_account_actor() { RawBytes::default(), TokenAmount::from(0), RawBytes::serialize(env.worker_key).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); let result = env .rt .call::(Method::Constructor as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); env.rt.verify(); } @@ -204,7 +204,7 @@ fn test_construct_with_invalid_peer_id() { .rt .call::(Method::Constructor as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); env.rt.verify(); } @@ -223,7 +223,7 @@ fn fails_if_control_addresses_exceeds_maximum_length() { .rt .call::(Method::Constructor as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); env.rt.verify(); } @@ -242,7 +242,7 @@ fn test_construct_with_large_multiaddr() { .rt .call::(Method::Constructor as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); env.rt.verify(); } @@ -260,6 +260,6 @@ fn test_construct_with_empty_multiaddr() { .rt .call::(Method::Constructor as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); env.rt.verify(); } diff --git a/actors/miner/tests/miner_actor_test_wpost.rs b/actors/miner/tests/miner_actor_test_wpost.rs index e9ca44311..897bf8fea 100644 --- a/actors/miner/tests/miner_actor_test_wpost.rs +++ b/actors/miner/tests/miner_actor_test_wpost.rs @@ -131,7 +131,7 @@ fn invalid_submissions() { params, PoStConfig::empty(), ); - expect_abort_contains_message(ExitCode::ErrIllegalArgument, "invalid deadline", result); + expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "invalid deadline", result); rt.reset(); } @@ -153,7 +153,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "expected proof to be smaller", result, ); @@ -180,7 +180,7 @@ fn invalid_submissions() { params, PoStConfig::empty(), ); - expect_abort_contains_message(ExitCode::ErrIllegalArgument, "too many partitions", result); + expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "too many partitions", result); rt.reset(); } @@ -223,7 +223,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "skipped faults contains sectors outside partition", result, ); @@ -248,7 +248,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "expected exactly one proof", result, ); @@ -273,7 +273,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "proof type StackedDRGWindow8MiBV1 not allowed", result, ); @@ -298,7 +298,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "expected proof of type", result, ); @@ -325,7 +325,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "expected proof to be smaller", result, ); @@ -349,7 +349,7 @@ fn invalid_submissions() { params, PoStConfig::empty(), ); - expect_abort_contains_message(ExitCode::ErrIllegalArgument, "bytes of randomness", result); + expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "bytes of randomness", result); rt.reset(); } @@ -377,7 +377,7 @@ fn invalid_submissions() { // giving a starting deadline of 20. Because committing a sector takes 2 deadlines the // specs-actors test does sector assignment in an immutable deadline 0 forcing assignment to // deadline 2. - expect_abort_contains_message(ExitCode::ErrIllegalArgument, "invalid deadline", result); + expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "invalid deadline", result); rt.epoch = dlinfo.current_epoch; rt.reset(); } @@ -400,7 +400,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "expected chain commit epoch", result, ); @@ -425,7 +425,7 @@ fn invalid_submissions() { PoStConfig::empty(), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "must be less than the current epoch", result, ); @@ -450,7 +450,7 @@ fn invalid_submissions() { PoStConfig::with_randomness(Randomness(b"far".to_vec())), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "randomness mismatched", result, ); @@ -549,7 +549,7 @@ fn duplicate_proof_rejected() { miner::Method::SubmitWindowedPoSt as u64, &RawBytes::serialize(params).unwrap(), ); - expect_abort_contains_message(ExitCode::ErrIllegalArgument, "partition already proven", result); + expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "partition already proven", result); rt.reset(); // Advance to end-of-deadline cron to verify no penalties. @@ -632,7 +632,7 @@ fn duplicate_proof_rejected_with_many_partitions() { PoStConfig::with_expected_power_delta(&pwr), ); expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "partition already proven", result, ); diff --git a/actors/miner/tests/util.rs b/actors/miner/tests/util.rs index 5b85336f0..b2bd5021c 100644 --- a/actors/miner/tests/util.rs +++ b/actors/miner/tests/util.rs @@ -177,7 +177,7 @@ impl ActorHarness { RawBytes::default(), TokenAmount::from(0), RawBytes::serialize(self.worker_key).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); let result = rt @@ -217,7 +217,7 @@ impl ActorHarness { let result = rt .call::(Method::ChangePeerID as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); rt.verify(); } @@ -247,7 +247,7 @@ impl ActorHarness { let result = rt .call::(Method::ChangeMultiaddrs as u64, &RawBytes::serialize(params).unwrap()) .unwrap_err(); - assert_eq!(result.exit_code(), ExitCode::ErrIllegalArgument); + assert_eq!(result.exit_code(), ExitCode::USR_ILLEGAL_ARGUMENT); rt.verify(); } @@ -376,7 +376,7 @@ impl ActorHarness { RawBytes::serialize(vdparams).unwrap(), TokenAmount::from(0), RawBytes::serialize(vdreturn).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); } // in the original test the else branch does some redundant checks which we can omit. @@ -389,7 +389,7 @@ impl ActorHarness { RawBytes::default(), state.fee_debt.clone(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -406,7 +406,7 @@ impl ActorHarness { RawBytes::serialize(cron_params).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -448,7 +448,7 @@ impl ActorHarness { RawBytes::default(), TokenAmount::from(0), RawBytes::serialize(current_reward).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); rt.expect_send( *STORAGE_POWER_ACTOR_ADDR, @@ -456,7 +456,7 @@ impl ActorHarness { RawBytes::default(), TokenAmount::from(0), RawBytes::serialize(current_power).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -496,7 +496,7 @@ impl ActorHarness { RawBytes::serialize(cdc_params).unwrap(), TokenAmount::from(0), RawBytes::serialize(cdc_ret).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); let entropy = RawBytes::serialize(self.receiver).unwrap(); @@ -530,7 +530,7 @@ impl ActorHarness { RawBytes::serialize(seal).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); rt.expect_validate_caller_any(); let result = rt @@ -584,7 +584,7 @@ impl ActorHarness { sector_expiry: pc.info.expiration, }; - let mut exit = ExitCode::Ok; + let mut exit = ExitCode::OK; match cfg.verify_deals_exit.get(&pc.info.sector_number) { Some(exit_code) => { exit = *exit_code; @@ -654,7 +654,7 @@ impl ActorHarness { RawBytes::serialize(BigIntSer(&expected_pledge)).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } } @@ -726,7 +726,7 @@ impl ActorHarness { RawBytes::serialize(params).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -744,7 +744,7 @@ impl ActorHarness { RawBytes::default(), penalty_total.clone(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let mut penalty_from_vesting = penalty_total.clone(); @@ -768,7 +768,7 @@ impl ActorHarness { RawBytes::serialize(BigIntSer(&pledge_delta)).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -781,7 +781,7 @@ impl ActorHarness { RawBytes::serialize(params).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -881,7 +881,7 @@ impl ActorHarness { ); let exit_code = match cfg.verification_exit { Some(exit_code) => exit_code, - None => ExitCode::Ok, + None => ExitCode::OK, }; rt.expect_verify_post(vi, exit_code); } @@ -899,7 +899,7 @@ impl ActorHarness { RawBytes::serialize(claim).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -986,8 +986,8 @@ impl ActorHarness { post.proofs, ); let verify_result = match expect_success { - Some(_) => ExitCode::ErrIllegalArgument, - None => ExitCode::Ok, + Some(_) => ExitCode::USR_ILLEGAL_ARGUMENT, + None => ExitCode::OK, }; rt.expect_verify_post(vi, verify_result); @@ -1006,7 +1006,7 @@ impl ActorHarness { RawBytes::serialize(claim).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -1018,7 +1018,7 @@ impl ActorHarness { RawBytes::default(), expected_reward, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -1030,7 +1030,7 @@ impl ActorHarness { RawBytes::default(), expected_penalty, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } @@ -1042,7 +1042,7 @@ impl ActorHarness { RawBytes::serialize(BigIntSer(&expected_pledge_delta)).unwrap(), TokenAmount::from(0), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } } @@ -1058,7 +1058,7 @@ impl ActorHarness { result.unwrap(); } else { expect_abort_contains_message( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, "failed to dispute valid post", result, ); diff --git a/actors/multisig/Cargo.toml b/actors/multisig/Cargo.toml index c87e28e63..d32cdbda7 100644 --- a/actors/multisig/Cargo.toml +++ b/actors/multisig/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_hamt = "0.4.0" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/multisig/src/lib.rs b/actors/multisig/src/lib.rs index 1caf352ff..c6d3c134d 100644 --- a/actors/multisig/src/lib.rs +++ b/actors/multisig/src/lib.rs @@ -75,7 +75,7 @@ impl Actor { for signer in ¶ms.signers { let resolved = resolve_to_id_addr(rt, signer).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve addr {} to ID addr", signer), ) })?; @@ -103,7 +103,7 @@ impl Actor { let empty_root = make_empty_map::<_, ()>(rt.store(), HAMT_BIT_WIDTH).flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "Failed to create empty map") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to create empty map") })?; let mut st: State = State { @@ -151,7 +151,7 @@ impl Actor { } let mut ptx = make_map_with_root(&st.pending_txs, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load pending transactions") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions") })?; let t_id = st.next_tx_id; @@ -167,14 +167,14 @@ impl Actor { ptx.set(t_id.key(), txn.clone()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to put transaction for propose", ) })?; st.pending_txs = ptx.flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to flush pending transactions", ) })?; @@ -203,7 +203,7 @@ impl Actor { } let ptx = make_map_with_root(&st.pending_txs, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load pending transactions") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions") })?; let txn = get_transaction(rt, &ptx, params.id, params.proposal_hash)?; @@ -241,7 +241,7 @@ impl Actor { let mut ptx = make_map_with_root::<_, Transaction>(&st.pending_txs, rt.store()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions", ) })?; @@ -250,7 +250,7 @@ impl Actor { .delete(¶ms.id.key()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to pop transaction {:?} for cancel", params.id), ) })? @@ -267,7 +267,7 @@ impl Actor { let calculated_hash = compute_proposal_hash(&tx, rt).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to compute proposal hash for (tx: {:?})", params.id), ) })?; @@ -278,7 +278,7 @@ impl Actor { st.pending_txs = ptx.flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to flush pending transactions", ) })?; @@ -297,7 +297,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&receiver))?; let resolved_new_signer = resolve_to_id_addr(rt, ¶ms.signer).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve address {}", params.signer), ) })?; @@ -338,7 +338,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&receiver))?; let resolved_old_signer = resolve_to_id_addr(rt, ¶ms.signer).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve address {}", params.signer), ) })?; @@ -376,7 +376,7 @@ impl Actor { // Remove approvals from removed signer st.purge_approvals(rt.store(), &resolved_old_signer).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to purge approvals of removed signer", ) })?; @@ -398,13 +398,13 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&receiver))?; let from_resolved = resolve_to_id_addr(rt, ¶ms.from).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve address {}", params.from), ) })?; let to_resolved = resolve_to_id_addr(rt, ¶ms.to).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve address {}", params.to), ) })?; @@ -428,7 +428,7 @@ impl Actor { st.purge_approvals(rt.store(), &from_resolved).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to purge approvals of removed signer", ) })?; @@ -513,7 +513,7 @@ impl Actor { let st = rt.transaction(|st: &mut State, rt| { let mut ptx = make_map_with_root(&st.pending_txs, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load pending transactions") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions") })?; // update approved on the transaction @@ -521,14 +521,14 @@ impl Actor { ptx.set(tx_id.key(), txn.clone()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to put transaction {} for approval", tx_id.0), ) })?; st.pending_txs = ptx.flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to flush pending transactions", ) })?; @@ -553,7 +553,7 @@ where RT: Runtime, { let mut out = RawBytes::default(); - let mut code = ExitCode::Ok; + let mut code = ExitCode::OK; let mut applied = false; let threshold_met = txn.approved.len() as u64 >= st.num_approvals_threshold; if threshold_met { @@ -575,21 +575,21 @@ where let mut ptx = make_map_with_root::<_, Transaction>(&st.pending_txs, rt.store()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions", ) })?; ptx.delete(&txn_id.key()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to delete transaction for cleanup", ) })?; st.pending_txs = ptx.flush().map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to flush pending transactions", ) })?; @@ -614,7 +614,7 @@ where .get(&txn_id.key()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load transaction {:?} for approval", txn_id), ) })? @@ -625,7 +625,7 @@ where if !proposal_hash.is_empty() { let calculated_hash = compute_proposal_hash(txn, rt).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to compute proposal hash for (tx: {:?})", txn_id), ) })?; @@ -702,7 +702,7 @@ impl ActorCode for Actor { Self::lock_balance(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::default()) } - None => Err(actor_error!(SysErrInvalidMethod, "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), } } } diff --git a/actors/multisig/tests/multisig_actor_test.rs b/actors/multisig/tests/multisig_actor_test.rs index db8dd506a..c61a40972 100644 --- a/actors/multisig/tests/multisig_actor_test.rs +++ b/actors/multisig/tests/multisig_actor_test.rs @@ -36,7 +36,7 @@ fn test_construction_fail_to_construct_multisig_actor_with_0_signers() { rt.set_caller(*INIT_ACTOR_CODE_ID, *INIT_ACTOR_ADDR); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, rt.call::( Method::Constructor as u64, &RawBytes::serialize(&zero_signer_params).unwrap(), @@ -64,7 +64,7 @@ fn test_construction_fail_to_construct_multisig_with_more_than_max_signers() { rt.expect_validate_caller_addr(vec![*INIT_ACTOR_ADDR]); rt.set_caller(*INIT_ACTOR_CODE_ID, *INIT_ACTOR_ADDR); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, rt.call::( Method::Constructor as u64, &RawBytes::serialize(&over_max_signers_params).unwrap(), @@ -138,7 +138,7 @@ fn test_add_signer() { increase: false, expect_signers: vec![anne, bob, chuck], expect_approvals: 2, - code: ExitCode::Ok, + code: ExitCode::OK, }, TestCase{ desc: "add signer and increase threshold", @@ -149,7 +149,7 @@ fn test_add_signer() { increase: true, expect_signers: vec![anne, bob, chuck], expect_approvals: 3, - code: ExitCode::Ok, + code: ExitCode::OK, }, TestCase{ desc: "fail to add signer that already exists", @@ -197,7 +197,7 @@ fn test_add_signer() { rt.set_caller(*MULTISIG_ACTOR_CODE_ID, msig); match tc.code { - ExitCode::Ok => { + ExitCode::OK => { let ret = h.add_signer(&mut rt, tc.add_signer, tc.increase).unwrap(); assert_eq!(RawBytes::default(), ret); let st = rt.get_state::().unwrap(); @@ -302,7 +302,7 @@ fn test_approve_simple_propose_and_approval() { // approval rt.set_balance(send_value.clone()); rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, bob); - rt.expect_send(chuck, fake_method, fake_params, send_value, fake_ret, ExitCode::Ok); + rt.expect_send(chuck, fake_method, fake_params, send_value, fake_ret, ExitCode::OK); h.approve_ok(&mut rt, TxnID(0), proposal_hash); h.assert_transactions(&rt, vec![]); } @@ -354,13 +354,13 @@ fn test_lock_balance_checks_preconditions() { // Disallow negative duration but allow negative start epoch rt.set_caller(*MULTISIG_ACTOR_CODE_ID, msig); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.lock_balance(&mut rt, vest_start, -1_i64, lock_amount), ); // Disallow negative amount expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.lock_balance(&mut rt, vest_start, vest_duration, TokenAmount::from(-1i32)), ); } diff --git a/actors/multisig/tests/util.rs b/actors/multisig/tests/util.rs index 1bc324abf..b5b5307e0 100644 --- a/actors/multisig/tests/util.rs +++ b/actors/multisig/tests/util.rs @@ -116,7 +116,7 @@ impl ActorHarness { ) -> RawBytes { let ret = self.approve(rt, txn_id, proposal_hash).unwrap(); let approve_ret = ret.deserialize::().unwrap(); - assert_eq!(ExitCode::Ok, approve_ret.code); + assert_eq!(ExitCode::OK, approve_ret.code); approve_ret.ret } diff --git a/actors/paych/Cargo.toml b/actors/paych/Cargo.toml index 6dfff9f49..c017a922e 100644 --- a/actors/paych/Cargo.toml +++ b/actors/paych/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" serde = { version = "1.0.136", features = ["derive"] } diff --git a/actors/paych/src/lib.rs b/actors/paych/src/lib.rs index 9cb54423c..aa0130416 100644 --- a/actors/paych/src/lib.rs +++ b/actors/paych/src/lib.rs @@ -10,7 +10,6 @@ use fvm_shared::address::Address; use fvm_shared::bigint::{BigInt, Sign}; use fvm_shared::econ::TokenAmount; use fvm_shared::error::ExitCode; -use fvm_shared::error::ExitCode::ErrTooManyProveCommits as ErrChannelStateUpdateAfterSettled; use fvm_shared::{MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND}; use num_derive::FromPrimitive; use num_traits::FromPrimitive; @@ -36,6 +35,8 @@ pub enum Method { Collect = 4, } +pub const ERR_CHANNEL_STATE_UPDATE_AFTER_SETTLED: ExitCode = ExitCode::new(32); + /// Payment Channel actor pub struct Actor; impl Actor { @@ -58,7 +59,7 @@ impl Actor { Array::<(), _>::new_with_bit_width(rt.store(), LANE_STATES_AMT_BITWIDTH) .flush() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to create empty AMT") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to create empty AMT") })?; rt.create(&State::new(from, to, empty_arr_cid))?; @@ -73,7 +74,7 @@ impl Actor { { let resolved = resolve_to_id_addr(rt, raw).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve address {}", raw), ) })?; @@ -118,8 +119,8 @@ impl Actor { .ok_or_else(|| actor_error!(ErrIllegalArgument, "voucher has no signature"))?; if st.settling_at != 0 && rt.curr_epoch() >= st.settling_at { - return Err(ActorError::new( - ErrChannelStateUpdateAfterSettled, + return Err(ActorError::new_unchecked( + ERR_CHANNEL_STATE_UPDATE_AFTER_SETTLED, "no vouchers can be processed after settling at epoch".to_string(), )); } @@ -130,15 +131,12 @@ impl Actor { // Generate unsigned bytes let sv_bz = sv.signing_bytes().map_err(|e| { - ActorError::new( - ExitCode::ErrSerialization, - format!("failed to serialized SignedVoucher: {}", e), - ) + ActorError::ErrSerialization(format!("failed to serialized SignedVoucher: {}", e)) })?; // Validate signature rt.verify_signature(sig, &signer, &sv_bz).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalArgument, "voucher signature invalid") + e.downcast_default(ExitCode::USR_ILLEGAL_ARGUMENT, "voucher signature invalid") })?; let pch_addr = rt.message().receiver(); @@ -187,7 +185,7 @@ impl Actor { rt.transaction(|st: &mut State, rt| { let mut l_states = Array::load(&st.lane_states, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load lane states") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load lane states") })?; // Find the voucher lane, create and insert it in sorted order if necessary. @@ -230,7 +228,7 @@ impl Actor { other_ls.nonce = merge.nonce; l_states.set(merge.lane, other_ls).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to store lane {}", merge.lane), ) })?; @@ -272,13 +270,13 @@ impl Actor { l_states.set(lane_id, lane_state).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to store lane {}", lane_id), ) })?; st.lane_states = l_states.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to save lanes") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to save lanes") })?; Ok(()) }) @@ -341,7 +339,7 @@ where } ls.get(id).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, format!("failed to load lane {}", id)) + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, format!("failed to load lane {}", id)) }) } @@ -372,7 +370,7 @@ impl ActorCode for Actor { Self::collect(rt)?; Ok(RawBytes::default()) } - _ => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + _ => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/paych/tests/paych_actor_test.rs b/actors/paych/tests/paych_actor_test.rs index 7551fe42b..5d560af23 100644 --- a/actors/paych/tests/paych_actor_test.rs +++ b/actors/paych/tests/paych_actor_test.rs @@ -105,7 +105,7 @@ mod paych_constructor { &mut rt, METHOD_CONSTRUCTOR, &RawBytes::serialize(params).unwrap(), - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, ); } @@ -198,7 +198,7 @@ mod create_lane_tests { sig: Option, #[builder(default = "true")] verify_sig: bool, - #[builder(default = "ExitCode::ErrIllegalArgument")] + #[builder(default = "ExitCode::USR_ILLEGAL_ARGUMENT")] exp_exit_code: ExitCode, } impl TestCase { @@ -220,7 +220,7 @@ mod create_lane_tests { TestCase::builder() .desc("succeeds".to_string()) .sig(sig.clone()) - .exp_exit_code(ExitCode::Ok) + .exp_exit_code(ExitCode::OK) .build() .unwrap(), TestCase::builder() @@ -316,7 +316,7 @@ mod create_lane_tests { }); } - if test_case.exp_exit_code == ExitCode::Ok { + if test_case.exp_exit_code == ExitCode::OK { call( &mut rt, Method::UpdateChannelState as u64, @@ -513,28 +513,28 @@ mod merge_tests { voucher: 10, balance: 0, merge: 1, - exit: ExitCode::ErrIllegalArgument, + exit: ExitCode::USR_ILLEGAL_ARGUMENT, }, TestCase { lane: 1, voucher: 0, balance: 0, merge: 10, - exit: ExitCode::ErrIllegalArgument, + exit: ExitCode::USR_ILLEGAL_ARGUMENT, }, TestCase { lane: 1, voucher: 10, balance: 1, merge: 10, - exit: ExitCode::ErrIllegalArgument, + exit: ExitCode::USR_ILLEGAL_ARGUMENT, }, TestCase { lane: 0, voucher: 10, balance: 0, merge: 10, - exit: ExitCode::ErrIllegalArgument, + exit: ExitCode::USR_ILLEGAL_ARGUMENT, }, ]; @@ -569,7 +569,7 @@ mod merge_tests { signer: Address::new_id(PAYEE_ID), result: Ok(()), }); - failure_end(&mut rt, sv, ExitCode::ErrIllegalArgument); + failure_end(&mut rt, sv, ExitCode::USR_ILLEGAL_ARGUMENT); } #[test] @@ -579,7 +579,7 @@ mod merge_tests { sv.lane = MAX_LANE + 1; sv.nonce += 1; sv.amount = BigInt::from(100); - failure_end(&mut rt, sv, ExitCode::ErrIllegalArgument); + failure_end(&mut rt, sv, ExitCode::USR_ILLEGAL_ARGUMENT); } } @@ -625,7 +625,7 @@ mod update_channel_state_extra { #[test] #[ignore = "old functionality -- test framework needs to be updated"] fn extra_call_succeed() { - let (mut rt, sv) = construct_runtime(ExitCode::Ok); + let (mut rt, sv) = construct_runtime(ExitCode::OK); call( &mut rt, Method::UpdateChannelState as u64, @@ -745,7 +745,7 @@ mod secret_preimage { &mut rt, Method::UpdateChannelState as u64, &RawBytes::serialize(ucp).unwrap(), - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, ); rt.verify(); @@ -786,7 +786,7 @@ mod actor_settle { &mut rt, Method::Settle as u64, &RawBytes::default(), - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, ); } @@ -852,7 +852,7 @@ mod actor_collect { Default::default(), st.to_send.clone(), Default::default(), - ExitCode::Ok, + ExitCode::OK, ); // Collect. @@ -875,7 +875,7 @@ mod actor_collect { // fails if not settling with: payment channel not settling or settled TestCase { dont_settle: true, - exp_send_to: ExitCode::Ok, + exp_send_to: ExitCode::OK, exp_collect_exit: ExitCode::ErrForbidden, }, // fails if Failed to send funds to `To` diff --git a/actors/power/Cargo.toml b/actors/power/Cargo.toml index de97200b0..6cf29ee3e 100644 --- a/actors/power/Cargo.toml +++ b/actors/power/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_hamt = "0.4.0" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/power/src/lib.rs b/actors/power/src/lib.rs index f8291c797..7b3e340a7 100644 --- a/actors/power/src/lib.rs +++ b/actors/power/src/lib.rs @@ -61,6 +61,8 @@ pub enum Method { CurrentTotalPower = 9, } +pub const ERR_TOO_MANY_PROVE_COMMITS: ExitCode = ExitCode::new(32); + /// Storage Power Actor pub struct Actor; impl Actor { @@ -73,7 +75,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&*SYSTEM_ACTOR_ADDR))?; let st = State::new(rt.store()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "Failed to create power actor state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to create power actor state") })?; rt.create(&st)?; Ok(()) @@ -117,7 +119,7 @@ impl Actor { rt.transaction(|st: &mut State, rt| { let mut claims = make_map_with_root_and_bitwidth(&st.claims, rt.store(), HAMT_BIT_WIDTH).map_err( - |e| e.downcast_default(ExitCode::ErrIllegalState, "failed to load claims"), + |e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims"), )?; set_claim( &mut claims, @@ -130,7 +132,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to put power in claimed table while creating miner", ) })?; @@ -146,7 +148,7 @@ impl Actor { })?; st.claims = claims.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush claims") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush claims") })?; Ok(()) })?; @@ -169,7 +171,7 @@ impl Actor { rt.transaction(|st: &mut State, rt| { let mut claims = make_map_with_root_and_bitwidth(&st.claims, rt.store(), HAMT_BIT_WIDTH).map_err( - |e| e.downcast_default(ExitCode::ErrIllegalState, "failed to load claims"), + |e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims"), )?; st.add_to_claim( @@ -180,7 +182,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!( "failed to update power raw {}, qa {}", params.raw_byte_delta, params.quality_adjusted_delta, @@ -189,7 +191,7 @@ impl Actor { })?; st.claims = claims.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush claims") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush claims") })?; Ok(()) }) @@ -224,15 +226,15 @@ impl Actor { CRON_QUEUE_AMT_BITWIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load cron events") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load cron events") })?; st.append_cron_event(&mut events, params.event_epoch, miner_event).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to enroll cron event") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to enroll cron event") })?; st.cron_event_queue = events.root().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush cron events") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush cron events") })?; Ok(()) })?; @@ -326,7 +328,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load proof batching set", ) })? @@ -337,24 +339,28 @@ impl Actor { let miner_addr = rt.message().caller(); let arr = mmap.get::(&miner_addr.to_bytes()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get seal verify infos at addr {}", miner_addr), ) })?; if let Some(arr) = arr { if arr.count() >= MAX_MINER_PROVE_COMMITS_PER_EPOCH { - return Err(actor_error!(ErrTooManyProveCommits; - "miner {} attempting to prove commit over {} sectors in epoch", - miner_addr, MAX_MINER_PROVE_COMMITS_PER_EPOCH)); + return Err(ActorError::new_unchecked( + ERR_TOO_MANY_PROVE_COMMITS, + format!( + "miner {} attempting to prove commit over {} sectors in epoch", + miner_addr, MAX_MINER_PROVE_COMMITS_PER_EPOCH + ), + )); } } mmap.add(miner_addr.to_bytes().into(), seal_info).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to insert proof into set") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to insert proof into set") })?; let mmrc = mmap.root().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush proofs batch map") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush proofs batch map") })?; rt.charge_gas("OnSubmitVerifySeal", GAS_ON_SUBMIT_VERIFY_SEAL); @@ -540,18 +546,18 @@ impl Actor { CRON_QUEUE_AMT_BITWIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load cron events") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load cron events") })?; let claims = make_map_with_root_and_bitwidth::<_, Claim>(&st.claims, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load claims") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims") })?; for epoch in st.first_cron_epoch..=rt_epoch { let epoch_events = load_cron_events(&events, epoch).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to load cron events at {}", epoch), ) })?; @@ -563,7 +569,10 @@ impl Actor { for evt in epoch_events.into_iter() { let miner_has_claim = claims.contains_key(&evt.miner_addr.to_bytes()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to look up claim") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to look up claim", + ) })?; if !miner_has_claim { debug!("skipping cron event for unknown miner: {}", evt.miner_addr); @@ -574,7 +583,7 @@ impl Actor { events.remove_all(&epoch_key(epoch)).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to clear cron events at {}", epoch), ) })?; @@ -582,7 +591,7 @@ impl Actor { st.first_cron_epoch = rt_epoch + 1; st.cron_event_queue = events.root().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush events") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush events") })?; Ok(()) @@ -616,7 +625,7 @@ impl Actor { let mut claims = make_map_with_root_and_bitwidth(&st.claims, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load claims") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims") })?; // Remove power and leave miner frozen @@ -633,7 +642,7 @@ impl Actor { } st.claims = claims.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush claims") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush claims") })?; Ok(()) })?; @@ -686,7 +695,7 @@ impl ActorCode for Actor { let res = Self::current_total_power(rt)?; Ok(RawBytes::serialize(res)?) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/power/src/state.rs b/actors/power/src/state.rs index 537f8d32a..455c5ce88 100644 --- a/actors/power/src/state.rs +++ b/actors/power/src/state.rs @@ -82,7 +82,7 @@ impl State { let empty_mmap = Multimap::new(store, CRON_QUEUE_HAMT_BITWIDTH, CRON_QUEUE_AMT_BITWIDTH) .root() .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "Failed to get empty multimap cid") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to get empty multimap cid") })?; Ok(State { cron_event_queue: empty_mmap, @@ -267,11 +267,11 @@ impl State { BS: Blockstore, { let claims = make_map_with_root::<_, Claim>(&self.claims, store) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to load claims"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims"))?; if !claims .contains_key(&miner_addr.to_bytes()) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to look up claim"))? + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to look up claim"))? { return Err(actor_error!( ErrForbidden, @@ -290,7 +290,7 @@ impl State { let claims = make_map_with_root_and_bitwidth::<_, Claim>(&self.claims, store, HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load claims") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims") })?; let claim = get_claim(&claims, miner)?; diff --git a/actors/power/tests/harness/mod.rs b/actors/power/tests/harness/mod.rs index 437d51ea8..2d9732a04 100644 --- a/actors/power/tests/harness/mod.rs +++ b/actors/power/tests/harness/mod.rs @@ -137,7 +137,7 @@ impl Harness { RawBytes::serialize(expected_init_params).unwrap(), value.clone(), RawBytes::serialize(create_miner_ret).unwrap(), - ExitCode::Ok, + ExitCode::OK, ); let params = CreateMinerParams { owner: *owner, diff --git a/actors/reward/Cargo.toml b/actors/reward/Cargo.toml index 75e520018..61b7ef2e3 100644 --- a/actors/reward/Cargo.toml +++ b/actors/reward/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" log = "0.4.14" diff --git a/actors/reward/src/lib.rs b/actors/reward/src/lib.rs index 82e0bf489..a5c1e46e2 100644 --- a/actors/reward/src/lib.rs +++ b/actors/reward/src/lib.rs @@ -258,7 +258,7 @@ impl ActorCode for Actor { Self::update_network_kpi(rt, param.map(|v| v.0))?; Ok(RawBytes::default()) } - None => Err(actor_error!(SysErrInvalidMethod, "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), } } } diff --git a/actors/reward/tests/reward_actor_test.rs b/actors/reward/tests/reward_actor_test.rs index 31d3ec168..161dfe4ac 100644 --- a/actors/reward/tests/reward_actor_test.rs +++ b/actors/reward/tests/reward_actor_test.rs @@ -87,7 +87,7 @@ mod test_award_block_reward { rt.set_balance(TokenAmount::from(9)); rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); assert_eq!( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, award_block_reward( &mut rt, *WINNER, @@ -111,7 +111,7 @@ mod test_award_block_reward { for (reward, penalty) in &reward_penalty_pairs { assert_eq!( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, award_block_reward( &mut rt, *WINNER, @@ -179,7 +179,7 @@ mod test_award_block_reward { RawBytes::serialize(BigIntSer(&expected_reward)).unwrap(), expected_reward, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, @@ -187,7 +187,7 @@ mod test_award_block_reward { RawBytes::default(), penalty.clone(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let params = AwardBlockRewardParams { @@ -262,7 +262,7 @@ mod test_award_block_reward { RawBytes::default(), expected_reward, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); let params = AwardBlockRewardParams { @@ -350,7 +350,7 @@ fn award_block_reward( .unwrap(), expected_payment.clone(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); if penalty > TokenAmount::from(0) { @@ -360,7 +360,7 @@ fn award_block_reward( RawBytes::default(), expected_payment, RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); } diff --git a/actors/runtime/Cargo.toml b/actors/runtime/Cargo.toml index af05b8652..03f1b722a 100644 --- a/actors/runtime/Cargo.toml +++ b/actors/runtime/Cargo.toml @@ -10,7 +10,7 @@ repository = "https://github.com/filecoin-project/builtin-actors" [dependencies] fvm_ipld_hamt = "0.4.0" fvm_ipld_amt = { version = "0.4.0", features = ["go-interop"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" serde = { version = "1.0.136", features = ["derive"] } diff --git a/actors/runtime/src/actor_error.rs b/actors/runtime/src/actor_error.rs index 1a6e41be4..23dc656c7 100644 --- a/actors/runtime/src/actor_error.rs +++ b/actors/runtime/src/actor_error.rs @@ -1,20 +1,50 @@ use fvm_shared::error::ExitCode; use thiserror::Error; -/// TODO fix error system; actor errors should be transparent to the VM. -/// The error type that gets returned by actor method calls. +/// The error type returned by actor method calls. #[derive(Error, Debug, Clone, PartialEq)] #[error("ActorError(exit_code: {exit_code:?}, msg: {msg})")] pub struct ActorError { - /// The exit code for this invocation, must not be `0`. + /// The exit code for this invocation. + /// Codes less than `FIRST_ACTOR_EXIT_CODE` are prohibited and will be overwritten by the VM. exit_code: ExitCode, /// Message for debugging purposes, msg: String, } impl ActorError { - pub fn new(exit_code: ExitCode, msg: String) -> Self { - Self { exit_code, msg } + /// Creates a new ActorError. This method does not check that the code is in the + /// range of valid actor abort codes. + pub fn new_unchecked(code: ExitCode, msg: String) -> Self { + Self { exit_code: code, msg } + } + + pub fn ErrIllegalArgument(msg: String) -> Self { + Self { exit_code: ExitCode::USR_ILLEGAL_ARGUMENT, msg } + } + pub fn ErrNotFound(msg: String) -> Self { + Self { exit_code: ExitCode::USR_NOT_FOUND, msg } + } + pub fn ErrForbidden(msg: String) -> Self { + Self { exit_code: ExitCode::USR_FORBIDDEN, msg } + } + pub fn ErrInsufficientFunds(msg: String) -> Self { + Self { exit_code: ExitCode::USR_INSUFFICIENT_FUNDS, msg } + } + pub fn ErrIllegalState(msg: String) -> Self { + Self { exit_code: ExitCode::USR_ILLEGAL_STATE, msg } + } + pub fn ErrSerialization(msg: String) -> Self { + Self { exit_code: ExitCode::USR_SERIALIZATION, msg } + } + pub fn ErrUnhandledMessage(msg: String) -> Self { + Self { exit_code: ExitCode::USR_UNHANDLED_MESSAGE, msg } + } + pub fn ErrUnspecified(msg: String) -> Self { + Self { exit_code: ExitCode::USR_UNSPECIFIED, msg } + } + pub fn ErrInternalSendAborted(msg: String) -> Self { + Self { exit_code: ExitCode::from(24), msg } // TODO use symbolic constant when it's defined. } /// Returns the exit code of the error. @@ -22,11 +52,6 @@ impl ActorError { self.exit_code } - /// Returns true when the exit code is `Ok`. - pub fn is_ok(&self) -> bool { - self.exit_code == ExitCode::Ok - } - /// Error message of the actor error. pub fn msg(&self) -> &str { &self.msg @@ -42,7 +67,7 @@ impl ActorError { /// Converts a raw encoding error into an ErrSerialization. impl From for ActorError { fn from(e: fvm_ipld_encoding::Error) -> Self { - Self { exit_code: ExitCode::ErrSerialization, msg: e.to_string() } + Self { exit_code: ExitCode::USR_SERIALIZATION, msg: e.to_string() } } } @@ -51,16 +76,7 @@ impl From for ActorError { #[cfg(feature = "fil-actor")] impl From for ActorError { fn from(e: fvm_sdk::error::ActorDeleteError) -> Self { - use fvm_sdk::error::ActorDeleteError::*; - Self { - // FIXME: These shouldn't be "system" errors, but we're trying to match existing - // behavior here. - exit_code: match e { - BeneficiaryIsSelf => ExitCode::SysErrIllegalActor, - BeneficiaryDoesNotExist => ExitCode::SysErrIllegalArgument, - }, - msg: e.to_string(), - } + Self { exit_code: ExitCode::USR_ILLEGAL_ARGUMENT, msg: e.to_string() } } } @@ -69,32 +85,27 @@ impl From for ActorError { #[cfg(feature = "fil-actor")] impl From for ActorError { fn from(e: fvm_sdk::error::NoStateError) -> Self { - Self { - // FIXME: These shouldn't be "system" errors, but we're trying to match existing - // behavior here. - exit_code: ExitCode::SysErrIllegalActor, - msg: e.to_string(), - } + Self { exit_code: ExitCode::USR_ILLEGAL_STATE, msg: e.to_string() } } } /// Performs conversions from SyscallResult, whose error type is ExitCode, /// to ActorErrors. This facilitates propagation. -impl From for ActorError { - fn from(e: ExitCode) -> Self { - ActorError { exit_code: e, msg: "".to_string() } - } -} +// impl From for ActorError { +// fn from(e: ExitCode) -> Self { +// ActorError { exit_code: e, msg: "".to_string() } +// } +// } /// Convenience macro for generating Actor Errors #[macro_export] macro_rules! actor_error { // Error with only one stringable expression - ( $code:ident; $msg:expr ) => { $crate::ActorError::new(fvm_shared::error::ExitCode::$code, $msg.to_string()) }; + ( $code:ident; $msg:expr ) => { $crate::ActorError::$code($msg.to_string()) }; // String with positional arguments ( $code:ident; $msg:literal $(, $ex:expr)+ ) => { - $crate::ActorError::new(fvm_shared::error::ExitCode::$code, format!($msg, $($ex,)*)) + $crate::ActorError::$code(format!($msg, $($ex,)*)) }; // Error with only one stringable expression, with comma separator diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index dee547c26..93667fd43 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -60,7 +60,7 @@ impl FvmRuntime { fn assert_not_validated(&mut self) -> Result<(), ActorError> { if self.caller_validated { return Err(actor_error!( - SysErrIllegalActor, + ErrUnspecified, // FIXME is this the right one? "Method must validate caller identity exactly once" )); } @@ -121,7 +121,7 @@ where if addresses.into_iter().any(|a| *a == caller_addr) { Ok(()) } else { - return Err(actor_error!(SysErrForbidden; + return Err(actor_error!(ErrForbidden; "caller {} is not one of supported", caller_addr )); } @@ -140,7 +140,7 @@ where match self.resolve_builtin_actor_type(&caller_cid) { Some(typ) if types.into_iter().any(|t| *t == typ) => Ok(()), - _ => Err(actor_error!(SysErrForbidden; + _ => Err(actor_error!(ErrForbidden; "caller cid type {} not one of supported", caller_cid)), } } @@ -263,28 +263,40 @@ where value: TokenAmount, ) -> Result { if self.in_transaction { - return Err(actor_error!(SysErrIllegalActor; "runtime.send() is not allowed")); + return Err(actor_error!(ErrUnspecified; "runtime.send() is not allowed")); } - // TODO: distinguish between "syscall" errors and actor exit codes. match fvm::send::send(&to, method, params, value) { Ok(ret) => { if ret.exit_code.is_success() { Ok(ret.return_data) } else { - Err(ActorError::from(ret.exit_code)) + // The returned code can't be simply propagated as it may be a system exit code. + Err(ActorError::ErrInternalSendAborted(format!( + "send to {} method {} aborted with code {}", + to, method, ret.exit_code + ))) } } Err(err) => Err(match err { + // Some of these errors are from operations in the Runtime or SDK layer + // before or after the underlying VM send syscall. ErrorNumber::NotFound => { - actor_error!(SysErrInvalidReceiver; "receiver not found") + // How do we know the receiver is what triggered this? + // An error number doesn't carry enough information at this level + // above the raw syscall (and even then). + actor_error!(ErrNotFound; "receiver not found") } ErrorNumber::InsufficientFunds => { - actor_error!(SysErrInsufficientFunds; "not enough funds") + // Actually this is more like an illegal argument where the caller attempted + // to transfer an amount larger than that representable by the VM's + // token amount type. Yes, the caller doesn't have that amount, but if they'd + // attempted to transfer a representable amount it would fail with + // SYS_INSUFFICIENT_FUNDS instead, so this difference is wierd. + actor_error!(ErrInsufficientFunds; "not enough funds") } - ErrorNumber::LimitExceeded => { - actor_error!(SysErrForbidden; "recursion limit exceeded") + err => { + actor_error!(ErrUnspecified; "unexpected error: {}", err) } - err => panic!("unexpected error: {}", err), }), } } @@ -294,14 +306,11 @@ where } fn create_actor(&mut self, code_id: Cid, actor_id: ActorID) -> Result<(), ActorError> { - fvm::actor::create_actor(actor_id, &code_id).map_err(|e| { - ActorError::new( - match e { - ErrorNumber::IllegalArgument => ExitCode::SysErrIllegalArgument, - _ => panic!("create failed with unknown error: {}", e), - }, - "failed to create actor".into(), - ) + fvm::actor::create_actor(actor_id, &code_id).map_err(|e| match e { + ErrorNumber::IllegalArgument => { + ActorError::ErrIllegalArgument("failed to create actor".into()) + } + _ => panic!("create failed with unknown error: {}", e), }) } @@ -431,13 +440,13 @@ pub fn trampoline(params: u32) -> u32 { let mut rt = FvmRuntime::default(); // Invoke the method, aborting if the actor returns an errored exit code. let ret = C::invoke_method(&mut rt, method, ¶ms) - .unwrap_or_else(|err| fvm::vm::abort(err.exit_code() as u32, Some(err.msg()))); + .unwrap_or_else(|err| fvm::vm::abort(err.exit_code().value(), Some(err.msg()))); - // Abort with "illegal actor" if the actor failed to validate the caller somewhere. + // Abort with "unspecified" if the actor failed to validate the caller somewhere. // We do this after handling the error, because the actor may have encountered an error before // it even could validate the caller. if !rt.caller_validated { - fvm::vm::abort(ExitCode::SysErrIllegalActor as u32, Some("failed to validate caller")) + fvm::vm::abort(ExitCode::USR_UNSPECIFIED.value(), Some("failed to validate caller")) } // Then handle the return value. diff --git a/actors/runtime/src/runtime/mod.rs b/actors/runtime/src/runtime/mod.rs index bb84b66a7..eb38b229b 100644 --- a/actors/runtime/src/runtime/mod.rs +++ b/actors/runtime/src/runtime/mod.rs @@ -20,9 +20,8 @@ use fvm_shared::sector::{ use fvm_shared::version::NetworkVersion; use fvm_shared::{ActorID, MethodNum}; -use crate::ActorError; - pub use self::actor_code::*; +use crate::{ActorError}; pub use self::policy::*; mod actor_code; diff --git a/actors/runtime/src/test_utils.rs b/actors/runtime/src/test_utils.rs index 0dc0735e1..047762c6e 100644 --- a/actors/runtime/src/test_utils.rs +++ b/actors/runtime/src/test_utils.rs @@ -840,8 +840,8 @@ impl Runtime for MockRuntime { } match expected_msg.exit_code { - ExitCode::Ok => Ok(expected_msg.send_return), - x => Err(ActorError::new(x, "Expected message Fail".to_string())), + ExitCode::OK => Ok(expected_msg.send_return), + x => Err(ActorError::new_unchecked(x, "Expected message Fail".to_string())), } } @@ -980,8 +980,8 @@ impl Syscalls for MockRuntime { ))); } - if exp.exit_code != ExitCode::Ok { - return Err(anyhow!(ActorError::new(exp.exit_code, "Expected Failure".to_string(),))); + if exp.exit_code != ExitCode::OK { + return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); } Ok(exp.cid) } @@ -994,8 +994,8 @@ impl Syscalls for MockRuntime { if exp.seal != *seal { return Err(anyhow!(actor_error!(ErrIllegalState; "Unexpected seal verification"),)); } - if exp.exit_code != ExitCode::Ok { - return Err(anyhow!(ActorError::new(exp.exit_code, "Expected Failure".to_string(),))); + if exp.exit_code != ExitCode::OK { + return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); } Ok(()) } @@ -1008,8 +1008,8 @@ impl Syscalls for MockRuntime { if exp.post != *post { return Err(anyhow!(actor_error!(ErrIllegalState; "Unexpected PoSt verification"),)); } - if exp.exit_code != ExitCode::Ok { - return Err(anyhow!(ActorError::new(exp.exit_code, "Expected Failure".to_string(),))); + if exp.exit_code != ExitCode::OK { + return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); } Ok(()) } @@ -1033,8 +1033,8 @@ impl Syscalls for MockRuntime { return Err(anyhow!(actor_error!(ErrIllegalState; "Header extra mismatch"),)); } } - if exp.exit_code != ExitCode::Ok { - return Err(anyhow!(ActorError::new(exp.exit_code, "Expected Failure".to_string(),))); + if exp.exit_code != ExitCode::OK { + return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); } Ok(exp.fault) } diff --git a/actors/runtime/src/util/cbor.rs b/actors/runtime/src/util/cbor.rs index 6ec6f0ef7..a2f38e8d3 100644 --- a/actors/runtime/src/util/cbor.rs +++ b/actors/runtime/src/util/cbor.rs @@ -1,8 +1,7 @@ use fvm_ipld_encoding::{to_vec, RawBytes}; -use fvm_shared::error::ExitCode; use serde::{de, ser}; -use crate::ActorError; +use crate::{ActorError}; /// Serializes a structure as a CBOR vector of bytes, returning a serialization error on failure. /// `desc` is a noun phrase for the object being serialized, included in any error message. @@ -11,7 +10,7 @@ where T: ser::Serialize + ?Sized, { to_vec(value).map_err(|e| { - ActorError::new(ExitCode::ErrSerialization, format!("failed to serialize {}: {}", desc, e)) + ActorError::ErrSerialization(format!("failed to serialize {}: {}", desc, e)) }) } @@ -28,10 +27,7 @@ where /// `desc` is a noun phrase for the object being deserialized, included in any error message. pub fn deserialize(v: &RawBytes, desc: &str) -> Result { v.deserialize().map_err(|e| { - ActorError::new( - ExitCode::ErrSerialization, - format!("failed to deserialize {}: {}", desc, e), - ) + ActorError::ErrSerialization(format!("failed to deserialize {}: {}", desc, e)) }) } diff --git a/actors/runtime/src/util/chaos/mod.rs b/actors/runtime/src/util/chaos/mod.rs index 2f274fb66..b6cab6dca 100644 --- a/actors/runtime/src/util/chaos/mod.rs +++ b/actors/runtime/src/util/chaos/mod.rs @@ -60,7 +60,7 @@ impl Actor { if let Err(e) = result { Ok(SendReturn { return_value: RawBytes::default(), code: e.exit_code() }) } else { - Ok(SendReturn { return_value: result.unwrap(), code: ExitCode::Ok }) + Ok(SendReturn { return_value: result.unwrap(), code: ExitCode::OK }) } } @@ -172,7 +172,7 @@ impl Actor { if arg.uncontrolled { panic!("Uncontrolled abort/error"); } - Err(ActorError::new(arg.code, arg.message)) + Err(ActorError::new_unchecked(arg.code, arg.message)) } pub fn inspect_runtime(rt: &mut RT) -> Result @@ -246,7 +246,7 @@ impl ActorCode for Actor { Ok(RawBytes::serialize(inspect)?) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/runtime/src/util/downcast.rs b/actors/runtime/src/util/downcast.rs index e86bf05a1..7e0652fa9 100644 --- a/actors/runtime/src/util/downcast.rs +++ b/actors/runtime/src/util/downcast.rs @@ -7,7 +7,7 @@ use fvm_ipld_encoding::Error as EncodingError; use fvm_ipld_hamt::Error as HamtError; use fvm_shared::error::ExitCode; -use crate::ActorError; +use crate::{ActorError}; /// Trait to allow multiple error types to be able to be downcasted into an `ActorError`. pub trait ActorDowncast { @@ -24,7 +24,7 @@ impl ActorDowncast for anyhow::Error { match downcast_util(self) { Ok(actor_error) => actor_error.wrap(msg), Err(other) => { - ActorError::new(default_exit_code, format!("{}: {}", msg.as_ref(), other)) + ActorError::new_unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)) } } } @@ -40,7 +40,7 @@ impl ActorDowncast for AmtError { fn downcast_default(self, default_exit_code: ExitCode, msg: impl AsRef) -> ActorError { match self { AmtError::Dynamic(e) => e.downcast_default(default_exit_code, msg), - other => ActorError::new(default_exit_code, format!("{}: {}", msg.as_ref(), other)), + other => ActorError::new_unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)), } } fn downcast_wrap(self, msg: impl AsRef) -> anyhow::Error { @@ -55,7 +55,7 @@ impl ActorDowncast for HamtError { fn downcast_default(self, default_exit_code: ExitCode, msg: impl AsRef) -> ActorError { match self { HamtError::Dynamic(e) => e.downcast_default(default_exit_code, msg), - other => ActorError::new(default_exit_code, format!("{}: {}", msg.as_ref(), other)), + other => ActorError::new_unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)), } } fn downcast_wrap(self, msg: impl AsRef) -> anyhow::Error { @@ -79,7 +79,7 @@ fn downcast_util(error: anyhow::Error) -> anyhow::Result { // Check if error is Encoding error, if so return `ErrSerialization` let error = match error.downcast::() { Ok(enc_error) => { - return Ok(ActorError::new(ExitCode::ErrSerialization, enc_error.to_string())) + return Ok(ActorError::new_unchecked(ExitCode::USR_SERIALIZATION, enc_error.to_string())) } Err(other) => other, }; diff --git a/actors/system/Cargo.toml b/actors/system/Cargo.toml index 2bdb112d9..f7d0346aa 100644 --- a/actors/system/Cargo.toml +++ b/actors/system/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_encoding = "0.1.0" fvm_ipld_blockstore = { version = "0.1.0" } num-traits = "0.2.14" diff --git a/actors/system/src/lib.rs b/actors/system/src/lib.rs index 0b00c9444..490a182f0 100644 --- a/actors/system/src/lib.rs +++ b/actors/system/src/lib.rs @@ -61,7 +61,7 @@ impl Actor { .store() .put_cbor(&Vec::<(String, Cid)>::new(), multihash::Code::Blake2b256) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to construct state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct state") })?; rt.create(&State { builtin_actors: c })?; @@ -84,7 +84,7 @@ impl ActorCode for Actor { Self::constructor(rt)?; Ok(RawBytes::default()) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/verifreg/Cargo.toml b/actors/verifreg/Cargo.toml index 467b049e6..8bea62878 100644 --- a/actors/verifreg/Cargo.toml +++ b/actors/verifreg/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/verifreg/src/lib.rs b/actors/verifreg/src/lib.rs index 52fc7058a..976003a44 100644 --- a/actors/verifreg/src/lib.rs +++ b/actors/verifreg/src/lib.rs @@ -56,7 +56,7 @@ impl Actor { .ok_or_else(|| actor_error!(ErrIllegalArgument, "root should be an ID address"))?; let st = State::new(rt.store(), id_addr).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "Failed to create verifreg state") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to create verifreg state") })?; rt.create(&st)?; @@ -79,7 +79,7 @@ impl Actor { let verifier = resolve_to_id_addr(rt, ¶ms.address).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve addr {} to ID addr", params.address), ) })?; @@ -96,7 +96,7 @@ impl Actor { make_map_with_root_and_bitwidth(&st.verifiers, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients", ) })?; @@ -106,12 +106,12 @@ impl Actor { HAMT_BIT_WIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; let found = verified_clients.contains_key(&verifier.to_bytes()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get client state for {}", verifier), ) })?; @@ -124,10 +124,10 @@ impl Actor { } verifiers.set(verifier.to_bytes().into(), BigIntDe(params.allowance.clone())).map_err( - |e| e.downcast_default(ExitCode::ErrIllegalState, "failed to add verifier"), + |e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to add verifier"), )?; st.verifiers = verifiers.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush verifiers") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush verifiers") })?; Ok(()) @@ -143,7 +143,7 @@ impl Actor { { let verifier = resolve_to_id_addr(rt, &verifier_addr).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve addr {} to ID addr", verifier_addr), ) })?; @@ -158,19 +158,19 @@ impl Actor { HAMT_BIT_WIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; verifiers .delete(&verifier.to_bytes()) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to remove verifier") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to remove verifier") })? .ok_or_else(|| { actor_error!(ErrIllegalArgument, "failed to remove verifier: not found") })?; st.verifiers = verifiers.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush verifiers") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush verifiers") })?; Ok(()) })?; @@ -200,7 +200,7 @@ impl Actor { let client = resolve_to_id_addr(rt, ¶ms.address).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve addr {} to ID addr", params.address), ) })?; @@ -215,14 +215,14 @@ impl Actor { make_map_with_root_and_bitwidth(&st.verifiers, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients", ) })?; let mut verified_clients = make_map_with_root_and_bitwidth(&st.verified_clients, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; // Validate caller is one of the verifiers. @@ -231,7 +231,7 @@ impl Actor { .get(&verifier.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get Verifier {}", verifier), ) })? @@ -241,7 +241,7 @@ impl Actor { // Validate client to be added isn't a verifier let found = verifiers.contains_key(&client.to_bytes()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get verifier") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get verifier") })?; if found { return Err(actor_error!( @@ -264,14 +264,14 @@ impl Actor { verifiers.set(verifier.to_bytes().into(), BigIntDe(new_verifier_cap)).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("Failed to update new verifier cap for {}", verifier), ) })?; let client_cap = verified_clients.get(&client.to_bytes()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("Failed to get verified client {}", client), ) })?; @@ -286,7 +286,7 @@ impl Actor { verified_clients.set(client.to_bytes().into(), BigIntDe(client_cap.clone())).map_err( |e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!( "Failed to add verified client {} with cap {}", client, client_cap, @@ -296,10 +296,10 @@ impl Actor { )?; st.verifiers = verifiers.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush verifiers") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush verifiers") })?; st.verified_clients = verified_clients.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush verified clients") })?; Ok(()) @@ -320,7 +320,7 @@ impl Actor { let client = resolve_to_id_addr(rt, ¶ms.address).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve addr {} to ID addr", params.address), ) })?; @@ -337,14 +337,14 @@ impl Actor { let mut verified_clients = make_map_with_root_and_bitwidth(&st.verified_clients, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; let BigIntDe(vc_cap) = verified_clients .get(&client.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get verified client {}", &client), ) })? @@ -376,7 +376,7 @@ impl Actor { .delete(&client.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("Failed to delete verified client {}", client), ) })? @@ -391,7 +391,7 @@ impl Actor { verified_clients.set(client.to_bytes().into(), BigIntDe(new_vc_cap)).map_err( |e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("Failed to update verified client {}", client), ) }, @@ -399,7 +399,7 @@ impl Actor { } st.verified_clients = verified_clients.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush verified clients") })?; Ok(()) })?; @@ -425,7 +425,7 @@ impl Actor { let client = resolve_to_id_addr(rt, ¶ms.address).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to resolve addr {} to ID addr", params.address), ) })?; @@ -439,7 +439,7 @@ impl Actor { let mut verified_clients = make_map_with_root_and_bitwidth(&st.verified_clients, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; let verifiers = make_map_with_root_and_bitwidth::<_, BigIntDe>( &st.verifiers, @@ -447,12 +447,12 @@ impl Actor { HAMT_BIT_WIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verifiers") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verifiers") })?; // validate we are NOT attempting to do this for a verifier let found = verifiers.contains_key(&client.to_bytes()).map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to get verifier") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get verifier") })?; if found { return Err(actor_error!( @@ -467,7 +467,7 @@ impl Actor { .get(&client.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get verified client {}", &client), ) })? @@ -478,13 +478,13 @@ impl Actor { let new_vc_cap = vc_cap + ¶ms.deal_size; verified_clients.set(client.to_bytes().into(), BigIntDe(new_vc_cap)).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("Failed to put verified client {}", client), ) })?; st.verified_clients = verified_clients.flush().map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to flush verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to flush verified clients") })?; Ok(()) })?; @@ -503,7 +503,7 @@ impl Actor { { let client = resolve_to_id_addr(rt, ¶ms.verified_client_to_remove).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, format!( "failed to resolve client addr {} to ID addr", params.verified_client_to_remove @@ -514,7 +514,7 @@ impl Actor { let verifier_1 = resolve_to_id_addr(rt, ¶ms.verifier_request_1.verifier).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, format!( "failed to resolve verifier addr {} to ID addr", params.verifier_request_1.verifier @@ -525,7 +525,7 @@ impl Actor { let verifier_2 = resolve_to_id_addr(rt, ¶ms.verifier_request_2.verifier).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, format!( "failed to resolve verifier addr {} to ID addr", params.verifier_request_2.verifier @@ -551,7 +551,7 @@ impl Actor { HAMT_BIT_WIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; // check that `client` is currently a verified client @@ -564,7 +564,7 @@ impl Actor { .get(&client.to_bytes()) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to get verified client {}", &client), ) })? @@ -589,7 +589,7 @@ impl Actor { ) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, "failed to load datacap removal proposal ids", ) })?; @@ -617,7 +617,7 @@ impl Actor { // no DataCap remaining, delete verified client verified_clients.delete(&client.to_bytes()).map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to delete verified client {}", &client), ) })?; @@ -628,7 +628,7 @@ impl Actor { .set(BytesKey::from(client.to_bytes()), BigIntDe(new_data_cap)) .map_err(|e| { e.downcast_default( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, format!("failed to update datacap for verified client {}", &client), ) })?; @@ -670,13 +670,13 @@ where HAMT_BIT_WIDTH, ) .map_err(|e| { - e.downcast_default(ExitCode::ErrIllegalState, "failed to load verified clients") + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") })?; // check that the `address` is currently a verified client let found = verified_clients .contains_key(&address.to_bytes()) - .map_err(|e| e.downcast_default(ExitCode::ErrIllegalState, "failed to get verifier"))?; + .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to get verifier"))?; Ok(found) } @@ -788,7 +788,7 @@ impl ActorCode for Actor { Self::remove_verified_client_data_cap(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::default()) } - None => Err(actor_error!(SysErrInvalidMethod; "Invalid method")), + None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), } } } diff --git a/actors/verifreg/tests/verifreg_actor_test.rs b/actors/verifreg/tests/verifreg_actor_test.rs index 71c5dd653..cd37116ae 100644 --- a/actors/verifreg/tests/verifreg_actor_test.rs +++ b/actors/verifreg/tests/verifreg_actor_test.rs @@ -54,7 +54,7 @@ mod construction { rt.expect_validate_caller_addr(vec![*SYSTEM_ACTOR_ADDR]); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, rt.call::( Method::Constructor as MethodNum, &RawBytes::serialize(root_pubkey).unwrap(), @@ -101,7 +101,7 @@ mod verifiers { fn add_verifier_enforces_min_size() { let (h, mut rt) = new_harness(); let allowance = MINIMUM_VERIFIED_DEAL_SIZE.clone() - 1; - expect_abort(ExitCode::ErrIllegalArgument, h.add_verifier(&mut rt, &VERIFIER, &allowance)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.add_verifier(&mut rt, &VERIFIER, &allowance)); h.check_state(); } @@ -109,7 +109,7 @@ mod verifiers { fn add_verifier_rejects_root() { let (h, mut rt) = new_harness(); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_verifier(&mut rt, &ROOT_ADDR, &VERIFIER_ALLOWANCE), ); h.check_state(); @@ -126,7 +126,7 @@ mod verifiers { &VERIFIER_ALLOWANCE, ); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_verifier(&mut rt, &CLIENT, &VERIFIER_ALLOWANCE), ); h.check_state(); @@ -144,10 +144,10 @@ mod verifiers { RawBytes::default(), TokenAmount::default(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); expect_abort( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, h.add_verifier(&mut rt, &verifier_key_address, &VERIFIER_ALLOWANCE), ); h.check_state(); @@ -192,7 +192,7 @@ mod verifiers { #[test] fn remove_requires_verifier_exists() { let (h, mut rt) = new_harness(); - expect_abort(ExitCode::ErrIllegalArgument, h.remove_verifier(&mut rt, &VERIFIER)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.remove_verifier(&mut rt, &VERIFIER)); h.check_state(); } @@ -265,7 +265,7 @@ mod clients { h.add_client(&mut rt, &VERIFIER, &CLIENT, &CLIENT_ALLOWANCE, &CLIENT_ALLOWANCE).unwrap(); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_client(&mut rt, &VERIFIER, &CLIENT2, &CLIENT_ALLOWANCE, &CLIENT_ALLOWANCE), ); @@ -318,11 +318,11 @@ mod clients { RawBytes::default(), TokenAmount::default(), RawBytes::default(), - ExitCode::Ok, + ExitCode::OK, ); expect_abort( - ExitCode::ErrIllegalState, + ExitCode::USR_ILLEGAL_STATE, h.add_client(&mut rt, &VERIFIER, &client, &CLIENT_ALLOWANCE, &CLIENT_ALLOWANCE), ); h.check_state(); @@ -335,7 +335,7 @@ mod clients { let allowance = MINIMUM_VERIFIED_DEAL_SIZE.clone() - 1; expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_client(&mut rt, &VERIFIER, &CLIENT, &allowance, &allowance), ); h.check_state(); @@ -368,7 +368,7 @@ mod clients { let allowance = VERIFIER_ALLOWANCE.clone() + 1; expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_client(&mut rt, &VERIFIER, &h.root, &allowance, &allowance), ); h.check_state(); @@ -379,7 +379,7 @@ mod clients { let (h, mut rt) = new_harness(); h.add_verifier(&mut rt, &VERIFIER, &VERIFIER_ALLOWANCE).unwrap(); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_client(&mut rt, &VERIFIER, &h.root, &CLIENT_ALLOWANCE, &CLIENT_ALLOWANCE), ); h.check_state(); @@ -390,13 +390,13 @@ mod clients { let (h, mut rt) = new_harness(); h.add_verifier(&mut rt, &VERIFIER, &VERIFIER_ALLOWANCE).unwrap(); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_client(&mut rt, &VERIFIER, &VERIFIER, &CLIENT_ALLOWANCE, &CLIENT_ALLOWANCE), ); h.add_verifier(&mut rt, &VERIFIER2, &VERIFIER_ALLOWANCE).unwrap(); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.add_client(&mut rt, &VERIFIER, &VERIFIER2, &CLIENT_ALLOWANCE, &CLIENT_ALLOWANCE), ); @@ -466,7 +466,7 @@ mod datacap { // Attempt to use more than remaining. let deal_size = MINIMUM_VERIFIED_DEAL_SIZE.clone() + 2; - expect_abort(ExitCode::ErrIllegalArgument, h.use_bytes(&mut rt, &CLIENT, &deal_size)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.use_bytes(&mut rt, &CLIENT, &deal_size)); h.check_state() } @@ -525,7 +525,7 @@ mod datacap { ); let deal_size = MINIMUM_VERIFIED_DEAL_SIZE.clone() - 1; - expect_abort(ExitCode::ErrIllegalArgument, h.use_bytes(&mut rt, &CLIENT, &deal_size)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.use_bytes(&mut rt, &CLIENT, &deal_size)); h.check_state() } @@ -551,7 +551,7 @@ mod datacap { ); let deal_size = CLIENT_ALLOWANCE.clone() + 1; - expect_abort(ExitCode::ErrIllegalArgument, h.use_bytes(&mut rt, &CLIENT, &deal_size)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.use_bytes(&mut rt, &CLIENT, &deal_size)); h.check_state() } @@ -679,7 +679,7 @@ mod datacap { ); let deal_size = MINIMUM_VERIFIED_DEAL_SIZE.clone() - 1; - expect_abort(ExitCode::ErrIllegalArgument, h.restore_bytes(&mut rt, &CLIENT, &deal_size)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.restore_bytes(&mut rt, &CLIENT, &deal_size)); h.check_state() } @@ -688,7 +688,7 @@ mod datacap { let (h, mut rt) = new_harness(); let deal_size = MINIMUM_VERIFIED_DEAL_SIZE.clone(); expect_abort( - ExitCode::ErrIllegalArgument, + ExitCode::USR_ILLEGAL_ARGUMENT, h.restore_bytes(&mut rt, &ROOT_ADDR, &deal_size), ); h.check_state() @@ -699,7 +699,7 @@ mod datacap { let (h, mut rt) = new_harness(); h.add_verifier(&mut rt, &VERIFIER, &VERIFIER_ALLOWANCE).unwrap(); let deal_size = MINIMUM_VERIFIED_DEAL_SIZE.clone(); - expect_abort(ExitCode::ErrIllegalArgument, h.restore_bytes(&mut rt, &VERIFIER, &deal_size)); + expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.restore_bytes(&mut rt, &VERIFIER, &deal_size)); h.check_state() } } diff --git a/test_vm/Cargo.toml b/test_vm/Cargo.toml index d6b181856..23962500d 100644 --- a/test_vm/Cargo.toml +++ b/test_vm/Cargo.toml @@ -11,7 +11,7 @@ keywords = ["filecoin", "web3", "wasm"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../actors/runtime" } -fvm_shared = { version = "0.4.0", default-features = false } +fvm_shared = { version = "0.4.1", default-features = false } fvm_ipld_encoding = { version = "0.1.0", default-features = false } fvm_ipld_blockstore = { version = "0.1.0", default-features = false } fvm_ipld_hamt = "0.4.0" From c923b9fb005cd0e11542dc2bf88b71eb73b530f2 Mon Sep 17 00:00:00 2001 From: anorth <445306+anorth@users.noreply.github.com> Date: Wed, 6 Apr 2022 21:29:02 +1000 Subject: [PATCH 02/10] rename methods to snake case --- actors/account/src/lib.rs | 4 +- actors/cron/src/lib.rs | 2 +- actors/init/src/lib.rs | 6 +- actors/market/src/lib.rs | 103 ++--- actors/market/src/state.rs | 29 +- actors/miner/src/deadline_state.rs | 40 +- actors/miner/src/lib.rs | 357 +++++++++--------- actors/miner/src/partition_state.rs | 14 +- actors/miner/src/sectors.rs | 6 +- actors/miner/src/state.rs | 38 +- actors/miner/tests/miner_actor_test_wpost.rs | 18 +- actors/multisig/src/lib.rs | 88 +++-- actors/paych/src/lib.rs | 44 +-- actors/power/src/lib.rs | 10 +- actors/power/src/state.rs | 26 +- actors/reward/src/lib.rs | 20 +- actors/runtime/src/actor_error.rs | 31 +- .../runtime/src/runtime/actor_blockstore.rs | 9 +- actors/runtime/src/runtime/fvm.rs | 36 +- actors/runtime/src/runtime/mod.rs | 2 +- actors/runtime/src/test_utils.rs | 60 +-- actors/runtime/src/util/cbor.rs | 12 +- actors/runtime/src/util/chaos/mod.rs | 6 +- actors/runtime/src/util/downcast.rs | 14 +- actors/system/src/lib.rs | 2 +- actors/verifreg/src/lib.rs | 79 ++-- actors/verifreg/tests/verifreg_actor_test.rs | 10 +- 27 files changed, 541 insertions(+), 525 deletions(-) diff --git a/actors/account/src/lib.rs b/actors/account/src/lib.rs index e4a7953ce..f2838ba74 100644 --- a/actors/account/src/lib.rs +++ b/actors/account/src/lib.rs @@ -43,7 +43,7 @@ impl Actor { match address.protocol() { Protocol::Secp256k1 | Protocol::BLS => {} protocol => { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "address must use BLS or SECP protocol, got {}", protocol)); } } @@ -82,7 +82,7 @@ impl ActorCode for Actor { let addr = Self::pubkey_address(rt)?; Ok(RawBytes::serialize(addr)?) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/cron/src/lib.rs b/actors/cron/src/lib.rs index d33415afe..b92add812 100644 --- a/actors/cron/src/lib.rs +++ b/actors/cron/src/lib.rs @@ -100,7 +100,7 @@ impl ActorCode for Actor { Self::epoch_tick(rt)?; Ok(RawBytes::default()) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/init/src/lib.rs b/actors/init/src/lib.rs index 18cd9ddfe..d602368b4 100644 --- a/actors/init/src/lib.rs +++ b/actors/init/src/lib.rs @@ -63,13 +63,13 @@ impl Actor { log::trace!("called exec; params.code_cid: {:?}", ¶ms.code_cid); let caller_code = rt.get_actor_code_cid(&rt.message().caller()).ok_or_else(|| { - actor_error!(ErrIllegalState, "no code for caller as {}", rt.message().caller()) + actor_error!(illegal_state, "no code for caller as {}", rt.message().caller()) })?; log::trace!("caller code CID: {:?}", &caller_code); if !can_exec(rt, &caller_code, ¶ms.code_cid) { - return Err(actor_error!(ErrForbidden; + return Err(actor_error!(forbidden; "called type {} cannot exec actor type {}", &caller_code, ¶ms.code_cid )); @@ -126,7 +126,7 @@ impl ActorCode for Actor { let res = Self::exec(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::serialize(res)?) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/market/src/lib.rs b/actors/market/src/lib.rs index e29d3869b..0025d9f04 100644 --- a/actors/market/src/lib.rs +++ b/actors/market/src/lib.rs @@ -109,7 +109,7 @@ impl Actor { if msg_value <= TokenAmount::from(0) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "balance to add must be greater than zero was: {}", msg_value )); @@ -157,7 +157,7 @@ impl Actor { RT: Runtime, { if params.amount < TokenAmount::from(0) { - return Err(actor_error!(ErrIllegalArgument, "negative amount: {}", params.amount)); + return Err(actor_error!(illegal_argument, "negative amount: {}", params.amount)); } let (nominal, recipient, approved) = escrow_address(rt, ¶ms.provider_or_client)?; @@ -218,22 +218,22 @@ impl Actor { // This allows us to retain and verify only the client's signature in each deal proposal itself. rt.validate_immediate_caller_type(CALLER_TYPES_SIGNABLE.iter())?; if params.deals.is_empty() { - return Err(actor_error!(ErrIllegalArgument, "Empty deals parameter")); + return Err(actor_error!(illegal_argument, "Empty deals parameter")); } // All deals should have the same provider so get worker once let provider_raw = params.deals[0].proposal.provider; let provider = rt.resolve_address(&provider_raw).ok_or_else(|| { - actor_error!(ErrNotFound, "failed to resolve provider address {}", provider_raw) + actor_error!(not_found, "failed to resolve provider address {}", provider_raw) })?; - let code_id = rt.get_actor_code_cid(&provider).ok_or_else(|| { - actor_error!(ErrIllegalArgument, "no code ID for address {}", provider) - })?; + let code_id = rt + .get_actor_code_cid(&provider) + .ok_or_else(|| actor_error!(illegal_argument, "no code ID for address {}", provider))?; if rt.resolve_builtin_actor_type(&code_id) != Some(Type::Miner) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "deal provider is not a storage miner actor" )); } @@ -249,7 +249,7 @@ impl Actor { } if !caller_ok { return Err(actor_error!( - ErrForbidden, + forbidden, "caller {} is not worker or control address of provider {}", caller, provider @@ -338,9 +338,9 @@ impl Actor { deal.proposal.provider = provider; deal.proposal.client = client; - let pcid = deal.proposal.cid().map_err(|e| { - actor_error!(ErrIllegalArgument; "failed to take cid of proposal {}: {}", di, e) - })?; + let pcid = deal.proposal.cid().map_err( + |e| actor_error!(illegal_argument; "failed to take cid of proposal {}: {}", di, e), + )?; // check proposalCids for duplication within message batch // check state PendingProposals for duplication across messages @@ -383,7 +383,7 @@ impl Actor { let valid_deal_count = valid_input_bf.len(); if valid_deals.len() != valid_proposal_cids.len() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "{} valid deals but {} valid proposal cids", valid_deals.len(), valid_proposal_cids.len() @@ -391,14 +391,14 @@ impl Actor { } if valid_deal_count != valid_deals.len() as u64 { return Err(actor_error!( - ErrIllegalState, + illegal_state, "{} valid deals but valid_deal_count {}", valid_deals.len(), valid_deal_count )); } if valid_deal_count == 0 { - return Err(actor_error!(ErrIllegalArgument, "All deal proposals invalid")); + return Err(actor_error!(illegal_argument, "All deal proposals invalid")); } let mut new_deal_ids = Vec::with_capacity(valid_deals.len()); @@ -434,7 +434,10 @@ impl Actor { let process_epoch = gen_rand_next_epoch(valid_deal.proposal.start_epoch, id); msm.deals_by_epoch.as_mut().unwrap().put(process_epoch, id).map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to set deal ops by epoch") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to set deal ops by epoch", + ) })?; new_deal_ids.push(id); @@ -539,7 +542,7 @@ impl Actor { })?; if s.is_some() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "deal {} already included in another sector", deal_id )); @@ -556,7 +559,7 @@ impl Actor { format!("failed to get deal_id ({})", deal_id), ) })? - .ok_or_else(|| actor_error!(ErrNotFound, "no such deal_id: {}", deal_id))?; + .ok_or_else(|| actor_error!(not_found, "no such deal_id: {}", deal_id))?; let propc = proposal .cid() @@ -572,7 +575,7 @@ impl Actor { if !has { return Err(actor_error!( - ErrIllegalState, + illegal_state, "tried to activate deal that was not in the pending set ({})", propc )); @@ -643,7 +646,7 @@ impl Actor { if deal.provider != miner_addr { return Err(actor_error!( - ErrIllegalState, + illegal_state, "caller {} is not the provider {} of deal {}", miner_addr, deal.provider, @@ -667,7 +670,7 @@ impl Actor { })? // A deal with a proposal but no state is not activated, but then it should not be // part of a sector that is terminating. - .ok_or_else(|| actor_error!(ErrIllegalArgument, "no state for deal {}", id))?; + .ok_or_else(|| actor_error!(illegal_argument, "no state for deal {}", id))?; // If a deal is already slashed, don't need to do anything if state.slash_epoch != EPOCH_UNDEFINED { @@ -723,7 +726,7 @@ impl Actor { ) })? .ok_or_else(|| { - actor_error!(ErrNotFound, "proposal doesn't exist ({})", deal_id) + actor_error!(not_found, "proposal doesn't exist ({})", deal_id) })?; pieces.push(PieceInfo { cid: deal.piece_cid, size: deal.piece_size }); } @@ -797,7 +800,7 @@ impl Actor { ) })? .ok_or_else(|| { - actor_error!(ErrNotFound, "proposal doesn't exist ({})", deal_id) + actor_error!(not_found, "proposal doesn't exist ({})", deal_id) })? .clone(); @@ -825,7 +828,7 @@ impl Actor { // Not yet appeared in proven sector; check for timeout. if curr_epoch < deal.start_epoch { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal {} processed before start epoch {}", deal_id, deal.start_epoch @@ -850,7 +853,7 @@ impl Actor { })?; if deleted.is_none() { return Err(actor_error!( - ErrIllegalState, + illegal_state, format!( "failed to delete deal {} proposal {}: does not exist", deal_id, dcid @@ -869,7 +872,7 @@ impl Actor { })? .ok_or_else(|| { actor_error!( - ErrIllegalState, + illegal_state, "failed to delete pending proposal: does not exist" ) })?; @@ -891,7 +894,7 @@ impl Actor { })? .ok_or_else(|| { actor_error!( - ErrIllegalState, + illegal_state, "failed to delete pending proposal: does not exist" ) })?; @@ -901,7 +904,7 @@ impl Actor { msm.update_pending_deal_state(&state, &deal, curr_epoch)?; if slash_amount.is_negative() { return Err(actor_error!( - ErrIllegalState, + illegal_state, format!( "computed negative slash amount {} for deal {}", slash_amount, deal_id @@ -912,7 +915,7 @@ impl Actor { if remove_deal { if next_epoch != EPOCH_UNDEFINED { return Err(actor_error!( - ErrIllegalState, + illegal_state, format!( "removed deal {} should have no scheduled epoch (got {})", deal_id, next_epoch @@ -932,7 +935,7 @@ impl Actor { })?; if deleted.is_none() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "failed to delete deal state: does not exist" )); } @@ -946,14 +949,14 @@ impl Actor { })?; if deleted.is_none() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "failed to delete deal proposal: does not exist" )); } } else { if next_epoch <= rt.curr_epoch() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "continuing deal {} next epoch {} should be in the future", deal_id, next_epoch @@ -961,7 +964,7 @@ impl Actor { } if !slash_amount.is_zero() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "continuing deal {} should not be slashed", deal_id )); @@ -1073,7 +1076,7 @@ where for deal_id in deal_ids { if !seen_deal_ids.insert(deal_id) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "deal id {} present multiple times", deal_id ) @@ -1081,7 +1084,7 @@ where } let proposal = proposals .get(*deal_id)? - .ok_or_else(|| actor_error!(ErrNotFound, "no such deal {}", deal_id))?; + .ok_or_else(|| actor_error!(not_found, "no such deal {}", deal_id))?; validate_deal_can_activate(proposal, miner_addr, sector_expiry, sector_activation) .map_err(|e| e.wrap(&format!("cannot activate deal {}", deal_id)))?; @@ -1119,7 +1122,7 @@ fn validate_deal_can_activate( ) -> Result<(), ActorError> { if &proposal.provider != miner_addr { return Err(actor_error!( - ErrForbidden, + forbidden, "proposal has provider {}, must be {}", proposal.provider, miner_addr @@ -1128,7 +1131,7 @@ fn validate_deal_can_activate( if curr_epoch > proposal.start_epoch { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "proposal start epoch {} has already elapsed at {}", proposal.start_epoch, curr_epoch @@ -1137,7 +1140,7 @@ fn validate_deal_can_activate( if proposal.end_epoch > sector_expiration { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "proposal expiration {} exceeds sector expiration {}", proposal.end_epoch, sector_expiration @@ -1163,7 +1166,7 @@ where if proposal.label.len() > DEAL_MAX_LABEL_SIZE { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "deal label can be at most {} bytes, is {}", DEAL_MAX_LABEL_SIZE, proposal.label.len() @@ -1173,32 +1176,32 @@ where proposal .piece_size .validate() - .map_err(|e| actor_error!(ErrIllegalArgument, "proposal piece size is invalid: {}", e))?; + .map_err(|e| actor_error!(illegal_argument, "proposal piece size is invalid: {}", e))?; // * we are skipping the check for if Cid is defined, but this shouldn't be possible if !is_piece_cid(&proposal.piece_cid) { - return Err(actor_error!(ErrIllegalArgument, "proposal PieceCID undefined")); + return Err(actor_error!(illegal_argument, "proposal PieceCID undefined")); } if proposal.end_epoch <= proposal.start_epoch { - return Err(actor_error!(ErrIllegalArgument, "proposal end before proposal start")); + return Err(actor_error!(illegal_argument, "proposal end before proposal start")); } if rt.curr_epoch() > proposal.start_epoch { - return Err(actor_error!(ErrIllegalArgument, "Deal start epoch has already elapsed.")); + return Err(actor_error!(illegal_argument, "Deal start epoch has already elapsed.")); }; let (min_dur, max_dur) = deal_duration_bounds(proposal.piece_size); if proposal.duration() < min_dur || proposal.duration() > max_dur { - return Err(actor_error!(ErrIllegalArgument, "Deal duration out of bounds.")); + return Err(actor_error!(illegal_argument, "Deal duration out of bounds.")); }; let (min_price, max_price) = deal_price_per_epoch_bounds(proposal.piece_size, proposal.duration()); if proposal.storage_price_per_epoch < min_price || &proposal.storage_price_per_epoch > max_price { - return Err(actor_error!(ErrIllegalArgument, "Storage price out of bounds.")); + return Err(actor_error!(illegal_argument, "Storage price out of bounds.")); }; let (min_provider_collateral, max_provider_collateral) = deal_provider_collateral_bounds( @@ -1210,7 +1213,7 @@ where if proposal.provider_collateral < min_provider_collateral || proposal.provider_collateral > max_provider_collateral { - return Err(actor_error!(ErrIllegalArgument, "Provider collateral out of bounds.")); + return Err(actor_error!(illegal_argument, "Provider collateral out of bounds.")); }; let (min_client_collateral, max_client_collateral) = @@ -1218,7 +1221,7 @@ where if proposal.client_collateral < min_client_collateral || proposal.client_collateral > max_client_collateral { - return Err(actor_error!(ErrIllegalArgument, "Client collateral out of bounds.")); + return Err(actor_error!(illegal_argument, "Client collateral out of bounds.")); }; Ok(()) @@ -1254,11 +1257,11 @@ where // Resolve the provided address to the canonical form against which the balance is held. let nominal = rt .resolve_address(addr) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "failed to resolve address {}", addr))?; + .ok_or_else(|| actor_error!(illegal_argument, "failed to resolve address {}", addr))?; let code_id = rt .get_actor_code_cid(&nominal) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "no code for address {}", nominal))?; + .ok_or_else(|| actor_error!(illegal_argument, "no code for address {}", nominal))?; if rt.resolve_builtin_actor_type(&code_id) == Some(Type::Miner) { // Storage miner actor entry; implied funds recipient is the associated owner address. @@ -1351,7 +1354,7 @@ impl ActorCode for Actor { Self::cron_tick(rt)?; Ok(RawBytes::default()) } - None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), + None => Err(actor_error!(unhandled_message, "Invalid method")), } } } diff --git a/actors/market/src/state.rs b/actors/market/src/state.rs index 9a8317d04..d12ce8359 100644 --- a/actors/market/src/state.rs +++ b/actors/market/src/state.rs @@ -123,7 +123,7 @@ fn deal_get_payment_remaining( ) -> Result { if slash_epoch > deal.end_epoch { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal slash epoch {} after end epoch {}", slash_epoch, deal.end_epoch @@ -136,7 +136,7 @@ fn deal_get_payment_remaining( let duration_remaining = deal.end_epoch - slash_epoch; if duration_remaining < 0 { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal remaining duration negative: {}", duration_remaining )); @@ -354,7 +354,7 @@ where // if the deal was ever updated, make sure it didn't happen in the future if ever_updated && state.last_updated_epoch > epoch { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal updated at future epoch {}", state.last_updated_epoch )); @@ -369,14 +369,14 @@ where let payment_end_epoch = if ever_slashed { if epoch < state.slash_epoch { return Err(actor_error!( - ErrIllegalState, + illegal_state, "current epoch less than deal slash epoch {}", state.slash_epoch )); } if state.slash_epoch > deal.end_epoch { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal slash epoch {} after deal end {}", state.slash_epoch, deal.end_epoch @@ -460,7 +460,10 @@ where self.unlock_balance(&deal.client, &deal.client_collateral, Reason::ClientCollateral) .map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failure unlocking client collateral") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failure unlocking client collateral", + ) })?; let amount_slashed = @@ -492,7 +495,7 @@ where BS: Blockstore, { if state.sector_start_epoch == EPOCH_UNDEFINED { - return Err(actor_error!(ErrIllegalState, "start sector epoch undefined")); + return Err(actor_error!(illegal_state, "start sector epoch undefined")); } self.unlock_balance(&deal.provider, &deal.provider_collateral, Reason::ProviderCollateral) @@ -541,7 +544,7 @@ where amount: &TokenAmount, ) -> Result<(), ActorError> { if amount.is_negative() { - return Err(actor_error!(ErrIllegalState, "cannot lock negative amount {}", amount)); + return Err(actor_error!(illegal_state, "cannot lock negative amount {}", amount)); } let prev_locked = self.locked_table.as_ref().unwrap().get(addr).map_err(|e| { @@ -553,7 +556,7 @@ where })?; if &prev_locked + amount > escrow_balance { - return Err(actor_error!(ErrInsufficientFunds; + return Err(actor_error!(insufficient_funds; "not enough balance to lock for addr{}: \ escrow balance {} < prev locked {} + amount {}", addr, escrow_balance, prev_locked, amount)); @@ -594,7 +597,7 @@ where lock_reason: Reason, ) -> anyhow::Result<()> { if amount.is_negative() { - return Err(actor_error!(ErrIllegalState, "unlock negative amount: {}", amount).into()); + return Err(actor_error!(illegal_state, "unlock negative amount: {}", amount).into()); } self.locked_table.as_mut().unwrap().must_subtract(addr, amount)?; @@ -621,7 +624,7 @@ where amount: &TokenAmount, ) -> Result<(), ActorError> { if amount.is_negative() { - return Err(actor_error!(ErrIllegalState, "transfer negative amount: {}", amount)); + return Err(actor_error!(illegal_state, "transfer negative amount: {}", amount)); } // Subtract from locked and escrow tables @@ -651,9 +654,7 @@ where lock_reason: Reason, ) -> anyhow::Result<()> { if amount.is_negative() { - return Err( - actor_error!(ErrIllegalState, "negative amount to slash: {}", amount).into() - ); + return Err(actor_error!(illegal_state, "negative amount to slash: {}", amount).into()); } // Subtract from locked and escrow tables diff --git a/actors/miner/src/deadline_state.rs b/actors/miner/src/deadline_state.rs index 8ef2ca93a..40816d52f 100644 --- a/actors/miner/src/deadline_state.rs +++ b/actors/miner/src/deadline_state.rs @@ -58,14 +58,14 @@ impl Deadlines { ) -> anyhow::Result { if deadline_idx >= policy.wpost_period_deadlines { return Err(anyhow!(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid deadline {}", deadline_idx ))); } store.get_cbor(&self.due[deadline_idx as usize])?.ok_or_else(|| { - anyhow!(actor_error!(ErrIllegalState, "failed to lookup deadline {}", deadline_idx)) + anyhow!(actor_error!(illegal_state, "failed to lookup deadline {}", deadline_idx)) }) } @@ -257,7 +257,7 @@ impl Deadline { format!("failed to lookup partition {}", partition_idx), ) })? - .ok_or_else(|| actor_error!(ErrNotFound, "no partition {}", partition_idx))?; + .ok_or_else(|| actor_error!(not_found, "no partition {}", partition_idx))?; Ok(partition.clone()) } @@ -277,7 +277,7 @@ impl Deadline { format!("failed to lookup partition snapshot {}", partition_idx), ) })? - .ok_or_else(|| actor_error!(ErrNotFound, "no partition snapshot {}", partition_idx))?; + .ok_or_else(|| actor_error!(not_found, "no partition snapshot {}", partition_idx))?; Ok(partition.clone()) } @@ -363,7 +363,7 @@ impl Deadline { // Update early expiration bitmap. let new_early_terminations = BitField::try_from_bits(partitions_with_early_terminations) - .map_err(|_| actor_error!(ErrIllegalState; "partition index out of bitfield range"))?; + .map_err(|_| actor_error!(illegal_state; "partition index out of bitfield range"))?; self.early_terminations |= &new_early_terminations; let all_on_time_sectors = BitField::union(&on_time_sectors); @@ -566,7 +566,7 @@ impl Deadline { e.downcast_wrap(format!("failed to load partition {}", partition_idx)) })? .ok_or_else( - || actor_error!(ErrNotFound; "failed to find partition {}", partition_idx), + || actor_error!(not_found; "failed to find partition {}", partition_idx), )? .clone(); @@ -636,7 +636,7 @@ impl Deadline { let partition_count = old_partitions.count(); let to_remove_set: BTreeSet<_> = to_remove .bounded_iter(partition_count) - .ok_or_else(|| actor_error!(ErrIllegalArgument; "partitions to remove exceeds total"))? + .ok_or_else(|| actor_error!(illegal_argument; "partitions to remove exceeds total"))? .collect(); if to_remove_set.is_empty() {} @@ -644,7 +644,7 @@ impl Deadline { if let Some(&max_partition) = to_remove_set.iter().max() { if max_partition > partition_count { return Err( - actor_error!(ErrIllegalArgument; "partition index {} out of range [0, {})", max_partition, partition_count).into() + actor_error!(illegal_argument; "partition index {} out of range [0, {})", max_partition, partition_count).into() ); } } else { @@ -655,7 +655,7 @@ impl Deadline { // Should already be checked earlier, but we might as well check again. if !self.early_terminations.is_empty() { return Err( - actor_error!(ErrIllegalArgument; "cannot remove partitions from deadline with early terminations").into(), + actor_error!(illegal_argument; "cannot remove partitions from deadline with early terminations").into(), ); } @@ -680,7 +680,7 @@ impl Deadline { let has_no_faults = partition.faults.is_empty(); if !has_no_faults { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot remove partition {}: has faults", partition_idx ) @@ -691,7 +691,7 @@ impl Deadline { let all_proven = partition.unproven.is_empty(); if !all_proven { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot remove partition {}: has unproven sectors", partition_idx ) @@ -764,7 +764,7 @@ impl Deadline { format!("failed to load partition {}", partition_idx), ) })? - .ok_or_else(|| actor_error!(ErrNotFound; "no such partition {}", partition_idx))? + .ok_or_else(|| actor_error!(not_found; "no such partition {}", partition_idx))? .clone(); let (new_faults, partition_power_delta, partition_new_faulty_power) = partition @@ -835,7 +835,7 @@ impl Deadline { format!("failed to load partition {}", partition_idx), ) })? - .ok_or_else(|| actor_error!(ErrNotFound; "no such partition {}", partition_idx))? + .ok_or_else(|| actor_error!(not_found; "no such partition {}", partition_idx))? .clone(); partition @@ -892,7 +892,7 @@ impl Deadline { format!("failed to load partition {}", partition_idx), ) })? - .ok_or_else(|| actor_error!(ErrIllegalState; "no partition {}", partition_idx))? + .ok_or_else(|| actor_error!(illegal_state; "no partition {}", partition_idx))? .clone(); // If we have no recovering power/sectors, and all power is faulty, skip @@ -1118,13 +1118,11 @@ impl Deadline { post_partitions: &mut [PoStPartition], ) -> anyhow::Result { let partition_indexes = BitField::try_from_bits(post_partitions.iter().map(|p| p.index)) - .map_err( - |_| actor_error!(ErrIllegalArgument; "partition index out of bitfield range"), - )?; + .map_err(|_| actor_error!(illegal_argument; "partition index out of bitfield range"))?; let num_partitions = partition_indexes.len(); if num_partitions != post_partitions.len() as u64 { - return Err(anyhow!(actor_error!(ErrIllegalArgument, "duplicate partitions proven"))); + return Err(anyhow!(actor_error!(illegal_argument, "duplicate partitions proven"))); } // First check to see if we're proving any already proven partitions. @@ -1132,7 +1130,7 @@ impl Deadline { let already_proven = &self.partitions_posted & &partition_indexes; if !already_proven.is_empty() { return Err(anyhow!(actor_error!( - ErrIllegalArgument, + illegal_argument, "partition already proven: {:?}", already_proven ))); @@ -1153,7 +1151,7 @@ impl Deadline { let mut partition = partitions .get(post.index) .map_err(|e| e.downcast_wrap(format!("failed to load partition {}", post.index)))? - .ok_or_else(|| actor_error!(ErrNotFound; "no such partition {}", post.index))? + .ok_or_else(|| actor_error!(not_found; "no such partition {}", post.index))? .clone(); // Process new faults and accumulate new faulty power. @@ -1286,7 +1284,7 @@ impl Deadline { let post = proof_arr .delete(idx) .map_err(|e| e.downcast_wrap(format!("failed to retrieve proof {}", idx)))? - .ok_or_else(|| actor_error!(ErrIllegalArgument, "proof {} not found", idx))?; + .ok_or_else(|| actor_error!(illegal_argument, "proof {} not found", idx))?; let root = proof_arr.flush().map_err(|e| e.downcast_wrap("failed to save proofs"))?; self.optimistic_post_submissions_snapshot = root; diff --git a/actors/miner/src/lib.rs b/actors/miner/src/lib.rs index f38276896..2722108f7 100644 --- a/actors/miner/src/lib.rs +++ b/actors/miner/src/lib.rs @@ -161,7 +161,7 @@ impl Actor { let period_start = current_proving_period_start(policy, current_epoch, offset); if period_start > current_epoch { return Err(actor_error!( - ErrIllegalState, + illegal_state, "computed proving period start {} after current epoch {}", period_start, current_epoch @@ -171,7 +171,7 @@ impl Actor { let deadline_idx = current_deadline_index(policy, current_epoch, period_start); if deadline_idx >= policy.wpost_period_deadlines { return Err(actor_error!( - ErrIllegalState, + illegal_state, "computed proving deadline index {} invalid", deadline_idx )); @@ -291,7 +291,7 @@ impl Actor { // * deserialized over the wire? If so, a workaround will be needed if !matches!(new_address.protocol(), Protocol::ID) { - return Err(actor_error!(ErrIllegalArgument, "owner address must be an ID address")); + return Err(actor_error!(illegal_argument, "owner address must be an ID address")); } rt.transaction(|state: &mut State, rt| { @@ -305,7 +305,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&pending_address))?; if new_address != pending_address { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected confirmation of {} got {}", pending_address, new_address @@ -397,7 +397,7 @@ impl Actor { let policy = rt.policy(); if params.proofs.len() != 1 { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected exactly one proof, got {}", params.proofs.len() )); @@ -405,7 +405,7 @@ impl Actor { if check_valid_post_proof_type(policy, params.proofs[0].post_proof).is_err() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "proof type {:?} not allowed", params.proofs[0].post_proof )); @@ -413,7 +413,7 @@ impl Actor { if params.deadline >= policy.wpost_period_deadlines { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid deadline {} of {}", params.deadline, policy.wpost_period_deadlines @@ -422,7 +422,7 @@ impl Actor { if params.chain_commit_rand.0.len() > RANDOMNESS_LENGTH { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected at most {} bytes of randomness, got {}", RANDOMNESS_LENGTH, params.chain_commit_rand.0.len() @@ -434,11 +434,7 @@ impl Actor { let info = get_miner_info(rt.store(), state)?; let max_proof_size = info.window_post_proof_type.proof_size().map_err(|e| { - actor_error!( - ErrIllegalState, - "failed to determine max window post proof size: {}", - e - ) + actor_error!(illegal_state, "failed to determine max window post proof size: {}", e) })?; rt.validate_immediate_caller_is( @@ -448,7 +444,7 @@ impl Actor { // Verify that the miner has passed exactly 1 proof. if params.proofs.len() != 1 { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected exactly one proof, got {}", params.proofs.len() )); @@ -457,7 +453,7 @@ impl Actor { // Make sure the miner is using the correct proof type. if params.proofs[0].post_proof != info.window_post_proof_type { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected proof of type {:?}, got {:?}", params.proofs[0].post_proof, info.window_post_proof_type @@ -468,7 +464,7 @@ impl Actor { let max_size = max_proof_size * params.partitions.len(); if params.proofs[0].proof_bytes.len() > max_size { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected proof to be smaller than {} bytes", max_size )); @@ -479,7 +475,7 @@ impl Actor { load_partitions_sectors_max(rt.policy(), info.window_post_partition_sectors); if params.partitions.len() as u64 > submission_partition_limit { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many partitions {}, limit {}", params.partitions.len(), submission_partition_limit @@ -494,7 +490,7 @@ impl Actor { // of this deadline haven't been processed yet. if !current_deadline.is_open() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "proving period {} not yet open at {}", current_deadline.period_start, current_epoch @@ -504,7 +500,7 @@ impl Actor { // The miner may only submit a proof for the current deadline. if params.deadline != current_deadline.index { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid deadline {} at epoch {}, expected {}", params.deadline, current_epoch, @@ -516,7 +512,7 @@ impl Actor { // WPoStChallengeLookback+WPoStChallengeWindow in the past. if params.chain_commit_epoch < current_deadline.challenge { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "expected chain commit epoch {} to be after {}", params.chain_commit_epoch, current_deadline.challenge @@ -525,7 +521,7 @@ impl Actor { if params.chain_commit_epoch >= current_epoch { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "chain commit epoch {} must be less than the current epoch {}", params.chain_commit_epoch, current_epoch @@ -539,7 +535,7 @@ impl Actor { &[], )?; if comm_rand != params.chain_commit_rand { - return Err(actor_error!(ErrIllegalArgument, "post commit randomness mismatched")); + return Err(actor_error!(illegal_argument, "post commit randomness mismatched")); } let sectors = Sectors::load(rt.store(), &state.sectors).map_err(|e| { @@ -595,7 +591,7 @@ impl Actor { // since that will just cause them to pay a penalty at deadline end that would otherwise be zero // if they had *not* declared them. return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot prove partitions with no active sectors" )); } @@ -666,11 +662,7 @@ impl Actor { RT: Runtime, { let sector_numbers = params.sector_numbers.validate().map_err(|e| { - actor_error!( - ErrIllegalState, - "Failed to validate bitfield for aggregated sectors: {}", - e - ) + actor_error!(illegal_state, "Failed to validate bitfield for aggregated sectors: {}", e) })?; let agg_sectors_count = sector_numbers.len(); @@ -678,14 +670,14 @@ impl Actor { let policy = rt.policy(); if agg_sectors_count > policy.max_aggregated_sectors { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many sectors addressed, addressed {} want <= {}", agg_sectors_count, policy.max_aggregated_sectors )); } else if agg_sectors_count < policy.min_aggregated_sectors { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too few sectors addressed, addressed {} want >= {}", agg_sectors_count, policy.min_aggregated_sectors @@ -694,7 +686,7 @@ impl Actor { if params.aggregate_proof.len() > policy.max_aggregated_proof_size { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "sector prove-commit proof of size {} exceeds max size of {}", params.aggregate_proof.len(), policy.max_aggregated_proof_size @@ -719,7 +711,7 @@ impl Actor { let msd = max_prove_commit_duration(rt.policy(), precommit.info.seal_proof) .ok_or_else(|| { actor_error!( - ErrIllegalState, + illegal_state, "no max seal duration for proof type: {}", i64::from(precommit.info.seal_proof) ) @@ -740,7 +732,7 @@ impl Actor { let prev_seal_proof = precommits[i - 1].info.seal_proof; if prev_seal_proof != precommit.info.seal_proof { return Err(actor_error!( - ErrIllegalState, + illegal_state, "aggregate contains mismatched seal proofs {} and {}", i64::from(prev_seal_proof), i64::from(precommit.info.seal_proof) @@ -760,7 +752,7 @@ impl Actor { *i } else { return Err(actor_error!( - ErrIllegalState, + illegal_state, "runtime provided non-ID receiver address {}", rt.message().receiver() )); @@ -773,7 +765,7 @@ impl Actor { precommit.pre_commit_epoch + rt.policy().pre_commit_challenge_delay; if rt.curr_epoch() <= interactive_epoch { return Err(actor_error!( - ErrForbidden, + forbidden, "too early to prove sector {}", precommit.info.sector_number )); @@ -801,7 +793,7 @@ impl Actor { let seal_proof = precommits[0].info.seal_proof; if precommits.is_empty() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "bitfield non-empty but zero precommits read from state" )); } @@ -833,10 +825,10 @@ impl Actor { aggregate_prove_commit_network_fee(precommits_to_confirm.len() as i64, &rt.base_fee()); let unlocked_balance = state .get_unlocked_balance(&rt.current_balance()) - .map_err(|_e| actor_error!(ErrIllegalState, "failed to determine unlocked balance"))?; + .map_err(|_e| actor_error!(illegal_state, "failed to determine unlocked balance"))?; if unlocked_balance < aggregate_fee { return Err(actor_error!( - ErrInsufficientFunds, + insufficient_funds, "remaining unlocked funds after prove-commit {} are insufficient to pay aggregation fee of {}", unlocked_balance, aggregate_fee @@ -861,7 +853,7 @@ impl Actor { if params.updates.len() > rt.policy().prove_replica_updates_max_size { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many updates ({} > {})", params.updates.len(), rt.policy().prove_replica_updates_max_size @@ -967,7 +959,7 @@ impl Actor { update.sector_number, true, ) - .map_err(|_| actor_error!(ErrIllegalArgument, "error checking sector health"))? + .map_err(|_| actor_error!(illegal_argument, "error checking sector health"))? { info!("sector isn't healthy, skipping sector {}", update.sector_number); continue; @@ -1019,7 +1011,7 @@ impl Actor { } if validated_updates.is_empty() { - return Err(actor_error!(ErrIllegalArgument, "no valid updates")); + return Err(actor_error!(illegal_argument, "no valid updates")); } // Errors past this point cause the prove_replica_updates call to fail (no more skipping sectors) @@ -1027,7 +1019,7 @@ impl Actor { let deal_weights = request_deal_weights(rt, §ors_deals)?; if deal_weights.sectors.len() != validated_updates.len() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal weight request returned {} records, expected {}", deal_weights.sectors.len(), validated_updates.len() @@ -1037,7 +1029,7 @@ impl Actor { let unsealed_sector_cids = request_unsealed_sector_cids(rt, §ors_data_spec)?; if unsealed_sector_cids.len() != validated_updates.len() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "unsealed sector cid request returned {} records, expected {}", unsealed_sector_cids.len(), validated_updates.len() @@ -1103,13 +1095,13 @@ impl Actor { .registered_update_proof() .map_err(|_| actor_error!( - ErrIllegalState, + illegal_state, "couldn't load update proof type" ) )?; if with_details.update.update_proof_type != update_proof_type { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, format!("unsupported update proof type {}", i64::from(with_details.update.update_proof_type)) )); } @@ -1185,11 +1177,11 @@ impl Actor { let unlocked_balance = state .get_unlocked_balance(&rt.current_balance()) .map_err(|_| - actor_error!(ErrIllegalState, "failed to calculate unlocked balance") + actor_error!(illegal_state, "failed to calculate unlocked balance") )?; if unlocked_balance < deficit { return Err(actor_error!( - ErrInsufficientFunds, + insufficient_funds, "insufficient funds for new initial pledge requirement {}, available: {}, skipping sector {}", deficit, unlocked_balance, @@ -1199,7 +1191,7 @@ impl Actor { state.add_initial_pledge(&deficit).map_err(|_e| actor_error!( - ErrIllegalState, + illegal_state, "failed to add initial pledge" ) )?; @@ -1216,7 +1208,7 @@ impl Actor { ) )? .cloned() - .ok_or_else(|| actor_error!(ErrNotFound, "no such deadline {} partition {}", dl_idx, with_details.update.partition))?; + .ok_or_else(|| actor_error!(not_found, "no such deadline {} partition {}", dl_idx, with_details.update.partition))?; let (partition_power_delta, partition_pledge_delta) = partition .replace_sectors(rt.store(), @@ -1268,7 +1260,7 @@ impl Actor { let success_len = succeeded.len(); if success_len != validated_updates.len() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "unexpected success_len {} != {}", success_len, validated_updates.len() @@ -1276,7 +1268,7 @@ impl Actor { } if new_sectors.len() != validated_updates.len() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "unexpected new_sectors len {} != {}", new_sectors.len(), validated_updates.len() @@ -1299,7 +1291,7 @@ impl Actor { })?; BitField::try_from_bits(succeeded).map_err(|_|{ - actor_error!(ErrIllegalArgument; "invalid sector number") + actor_error!(illegal_argument; "invalid sector number") }) })?; @@ -1324,7 +1316,7 @@ impl Actor { let policy = rt.policy(); if params.deadline >= policy.wpost_period_deadlines { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid deadline {} of {}", params.deadline, policy.wpost_period_deadlines @@ -1353,7 +1345,7 @@ impl Actor { current_epoch, ) { return Err(actor_error!( - ErrForbidden, + forbidden, "can only dispute window posts during the dispute window\ ({} epochs after the challenge window closes)", policy.wpost_dispute_window @@ -1426,7 +1418,7 @@ impl Actor { // Check proof, we fail if validation succeeds. if verify_windowed_post(rt, target_deadline.challenge, §or_infos, proofs)? { - return Err(actor_error!(ErrIllegalArgument, "failed to dispute valid post")); + return Err(actor_error!(illegal_argument, "failed to dispute valid post")); } else { info!("Successfully disputed post- window post was invalid"); } @@ -1484,7 +1476,7 @@ impl Actor { // portion of their fee back as a reward. let penalty_target = &penalty_base + &reward_target; st.apply_penalty(&penalty_target) - .map_err(|e| actor_error!(ErrIllegalState, "failed to apply penalty {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to apply penalty {}", e))?; let (penalty_from_vesting, penalty_from_balance) = st .repay_partial_debt_in_priority_order( rt.store(), @@ -1557,10 +1549,10 @@ impl Actor { { let policy = rt.policy(); if params.sectors.is_empty() { - return Err(actor_error!(ErrIllegalArgument, "batch empty")); + return Err(actor_error!(illegal_argument, "batch empty")); } else if params.sectors.len() > policy.pre_commit_sector_batch_max_size { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "batch of {} too large, max {}", params.sectors.len(), policy.pre_commit_sector_batch_max_size @@ -1575,14 +1567,14 @@ impl Actor { let set = sector_numbers.get(precommit.sector_number); if set { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "duplicate sector number {}", precommit.sector_number )); } if precommit.sector_number > MAX_SECTOR_NUMBER { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "sector number {} out of range 0..(2^63-1)", precommit.sector_number )); @@ -1590,7 +1582,7 @@ impl Actor { sector_numbers.set(precommit.sector_number); if !can_pre_commit_seal_proof(rt.policy(), precommit.seal_proof) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "unsupported seal proof type {}", i64::from(precommit.seal_proof) )); @@ -1598,11 +1590,11 @@ impl Actor { // Skip checking if CID is defined because it cannot be so in Rust if !is_sealed_sector(&precommit.sealed_cid) { - return Err(actor_error!(ErrIllegalArgument, "sealed CID had wrong prefix")); + return Err(actor_error!(illegal_argument, "sealed CID had wrong prefix")); } if precommit.seal_rand_epoch >= curr_epoch { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "seal challenge epoch {} must be before now {}", precommit.seal_rand_epoch, curr_epoch @@ -1610,7 +1602,7 @@ impl Actor { } if precommit.seal_rand_epoch < challenge_earliest { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "seal challenge epoch {} too old, must be after {}", precommit.seal_rand_epoch, challenge_earliest @@ -1625,7 +1617,7 @@ impl Actor { if precommit.replace_capacity { return Err(actor_error!( - ErrForbidden, + forbidden, "cc upgrade through precommit discontinued, use ProveReplicaUpdate" )); } @@ -1641,7 +1633,7 @@ impl Actor { let deal_weights = request_deal_weights(rt, §ors_deals)?; if deal_weights.sectors.len() != params.sectors.len() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "deal weight request returned {} records, expected {}", deal_weights.sectors.len(), params.sectors.len() @@ -1657,7 +1649,7 @@ impl Actor { state.apply_penalty(&aggregate_fee) .map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to apply penalty: {}", e ) @@ -1670,7 +1662,7 @@ impl Actor { .get_available_balance(&rt.current_balance()) .map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to calculate available balance: {}", e ) @@ -1686,7 +1678,7 @@ impl Actor { )?; let store = rt.store(); if consensus_fault_active(&info, curr_epoch) { - return Err(actor_error!(ErrForbidden, "pre-commit not allowed during active consensus fault")); + return Err(actor_error!(forbidden, "pre-commit not allowed during active consensus fault")); } let mut chain_infos = Vec::with_capacity(params.sectors.len()); @@ -1700,21 +1692,21 @@ impl Actor { .registered_window_post_proof() .map_err(|_e| actor_error!( - ErrIllegalArgument, + illegal_argument, "failed to lookup Window PoSt proof type for sector seal proof {}", i64::from(precommit.seal_proof) ))?; if sector_wpost_proof != info.window_post_proof_type { - return Err(actor_error!(ErrIllegalArgument, "sector Window PoSt proof type %d must match miner Window PoSt proof type {} (seal proof type {})", i64::from(sector_wpost_proof), i64::from(info.window_post_proof_type))); + return Err(actor_error!(illegal_argument, "sector Window PoSt proof type %d must match miner Window PoSt proof type {} (seal proof type {})", i64::from(sector_wpost_proof), i64::from(info.window_post_proof_type))); } if precommit.deal_ids.len() as u64 > deal_count_max { - return Err(actor_error!(ErrIllegalArgument, "too many deals for sector {} > {}", precommit.deal_ids.len(), deal_count_max)); + return Err(actor_error!(illegal_argument, "too many deals for sector {} > {}", precommit.deal_ids.len(), deal_count_max)); } // Ensure total deal space does not exceed sector size. let deal_weight = &deal_weights.sectors[i]; if deal_weight.deal_space > info.sector_size as u64 { - return Err(actor_error!(ErrIllegalArgument, "deals too large to fit in sector {} > {}", deal_weight.deal_space, info.sector_size)); + return Err(actor_error!(illegal_argument, "deals too large to fit in sector {} > {}", deal_weight.deal_space, info.sector_size)); } if precommit.replace_capacity { validate_replace_sector(rt.policy(), state, store, precommit)? @@ -1737,7 +1729,7 @@ impl Actor { // Calculate pre-commit cleanup let msd = max_prove_commit_duration(rt.policy(), precommit.seal_proof) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "no max seal duration set for proof type: {}", i64::from(precommit.seal_proof)))?; + .ok_or_else(|| actor_error!(illegal_argument, "no max seal duration set for proof type: {}", i64::from(precommit.seal_proof)))?; // PreCommitCleanUpDelay > 0 here is critical for the batch verification of proofs. Without it, if a proof arrived exactly on the // due epoch, ProveCommitSector would accept it, then the expiry event would remove it, and then // ConfirmSectorProofsValid would fail to find it. @@ -1746,12 +1738,12 @@ impl Actor { } // Batch update actor state. if available_balance < total_deposit_required { - return Err(actor_error!(ErrInsufficientFunds, "insufficient funds {} for pre-commit deposit: {}", available_balance, total_deposit_required)); + return Err(actor_error!(insufficient_funds, "insufficient funds {} for pre-commit deposit: {}", available_balance, total_deposit_required)); } state.add_pre_commit_deposit(&total_deposit_required) .map_err(|e| actor_error!( - ErrIllegalState, + illegal_state, "failed to add pre-commit deposit {}: {}", total_deposit_required, e ))?; @@ -1800,7 +1792,7 @@ impl Actor { rt.validate_immediate_caller_accept_any()?; if params.sector_number > MAX_SECTOR_NUMBER { - return Err(actor_error!(ErrIllegalArgument, "sector number greater than maximum")); + return Err(actor_error!(illegal_argument, "sector number greater than maximum")); } let sector_number = params.sector_number; @@ -1814,11 +1806,11 @@ impl Actor { format!("failed to load pre-committed sector {}", sector_number), ) })? - .ok_or_else(|| actor_error!(ErrNotFound, "no pre-commited sector {}", sector_number))?; + .ok_or_else(|| actor_error!(not_found, "no pre-commited sector {}", sector_number))?; let max_proof_size = precommit.info.seal_proof.proof_size().map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to determine max proof size for sector {}: {}", sector_number, e @@ -1826,7 +1818,7 @@ impl Actor { })?; if params.proof.len() > max_proof_size { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "sector prove-commit proof of size {} exceeds max size of {}", params.proof.len(), max_proof_size @@ -1836,7 +1828,7 @@ impl Actor { let msd = max_prove_commit_duration(rt.policy(), precommit.info.seal_proof).ok_or_else(|| { actor_error!( - ErrIllegalState, + illegal_state, "no max seal duration set for proof type: {:?}", precommit.info.seal_proof ) @@ -1844,7 +1836,7 @@ impl Actor { let prove_commit_due = precommit.pre_commit_epoch + msd; if rt.curr_epoch() > prove_commit_due { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "commitment proof for {} too late at {}, due {}", sector_number, rt.curr_epoch(), @@ -1925,21 +1917,19 @@ impl Actor { rt.validate_immediate_caller_accept_any()?; if params.sector_number > MAX_SECTOR_NUMBER { - return Err(actor_error!(ErrIllegalArgument, "sector number out of range")); + return Err(actor_error!(illegal_argument, "sector number out of range")); } let st: State = rt.state()?; match st.get_sector(rt.store(), params.sector_number) { Err(e) => Err(actor_error!( - ErrIllegalState, + illegal_state, "failed to load proven sector {}: {}", params.sector_number, e )), - Ok(None) => { - Err(actor_error!(ErrNotFound, "sector {} not proven", params.sector_number)) - } + Ok(None) => Err(actor_error!(not_found, "sector {} not proven", params.sector_number)), Ok(Some(_sector)) => Ok(()), } } @@ -1959,7 +1949,7 @@ impl Actor { let policy = rt.policy(); if params.extensions.len() as u64 > policy.delcarations_max { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many declarations {}, max {}", params.extensions.len(), policy.delcarations_max @@ -1975,7 +1965,7 @@ impl Actor { let policy = rt.policy(); if decl.deadline >= policy.wpost_period_deadlines { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "deadline {} not in range 0..{}", decl.deadline, policy.wpost_period_deadlines @@ -1986,7 +1976,7 @@ impl Actor { Ok(sectors) => sectors, Err(e) => { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "failed to validate sectors for deadline {}, partition {}: {}", decl.deadline, decl.partition, @@ -1998,10 +1988,7 @@ impl Actor { match sector_count.checked_add(sectors.len()) { Some(sum) => sector_count = sum, None => { - return Err(actor_error!( - ErrIllegalArgument, - "sector bitfield integer overflow" - )); + return Err(actor_error!(illegal_argument, "sector bitfield integer overflow")); } } } @@ -2010,7 +1997,7 @@ impl Actor { let policy = rt.policy(); if sector_count > policy.addressed_sectors_max { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many sectors for declaration {}, max {}", sector_count, policy.addressed_sectors_max @@ -2089,7 +2076,7 @@ impl Actor { ) })? .cloned() - .ok_or_else(|| actor_error!(ErrNotFound, "no such partition {:?}", key))?; + .ok_or_else(|| actor_error!(not_found, "no such partition {:?}", key))?; let old_sectors = sectors .load_sector(&mut decl.sectors) @@ -2100,7 +2087,7 @@ impl Actor { .map(|sector| { if !can_extend_seal_proof_type(sector.seal_proof) { return Err(actor_error!( - ErrForbidden, + forbidden, "cannot extend expiration for sector {} with unsupported \ seal type {:?}", sector.sector_number, @@ -2112,7 +2099,7 @@ impl Actor { // because the end of its deadline hasn't passed yet. if sector.expiration < rt.curr_epoch() { return Err(actor_error!( - ErrForbidden, + forbidden, "cannot extend expiration for expired sector {} at {}", sector.sector_number, sector.expiration @@ -2121,7 +2108,7 @@ impl Actor { if decl.new_expiration < sector.expiration { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot reduce sector {} expiration to {} from {}", sector.sector_number, decl.new_expiration, @@ -2278,7 +2265,7 @@ impl Actor { let policy = rt.policy(); if params.terminations.len() as u64 > policy.delcarations_max { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many declarations when terminating sectors: {} > {}", params.terminations.len(), policy.delcarations_max @@ -2294,7 +2281,7 @@ impl Actor { to_process.add(rt.policy(), deadline, partition, term.sectors).map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "failed to process deadline {}, partition {}: {}", deadline, partition, @@ -2308,7 +2295,7 @@ impl Actor { to_process .check(policy.addressed_partitions_max, policy.addressed_sectors_max) .map_err(|e| { - actor_error!(ErrIllegalArgument, "cannot process requested parameters: {}", e) + actor_error!(illegal_argument, "cannot process requested parameters: {}", e) })?; } @@ -2344,7 +2331,7 @@ impl Actor { curr_epoch, ) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot terminate sectors in immutable deadline {}", deadline_idx )); @@ -2429,7 +2416,7 @@ impl Actor { let policy = rt.policy(); if params.faults.len() as u64 > policy.delcarations_max { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many fault declarations for a single message: {} > {}", params.faults.len(), policy.delcarations_max @@ -2445,7 +2432,7 @@ impl Actor { to_process.add(rt.policy(), deadline, partition, term.sectors).map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "failed to process deadline {}, partition {}: {}", deadline, partition, @@ -2459,7 +2446,7 @@ impl Actor { to_process .check(policy.addressed_partitions_max, policy.addressed_sectors_max) .map_err(|e| { - actor_error!(ErrIllegalArgument, "cannot process requested parameters: {}", e) + actor_error!(illegal_argument, "cannot process requested parameters: {}", e) })?; } @@ -2491,7 +2478,7 @@ impl Actor { ) .map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid fault declaration deadline {}: {}", deadline_idx, e @@ -2500,7 +2487,7 @@ impl Actor { validate_fr_declaration_deadline(&target_deadline).map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "failed fault declaration at deadline {}: {}", deadline_idx, e @@ -2572,7 +2559,7 @@ impl Actor { let policy = rt.policy(); if params.recoveries.len() as u64 > policy.delcarations_max { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many recovery declarations for a single message: {} > {}", params.recoveries.len(), policy.delcarations_max @@ -2588,7 +2575,7 @@ impl Actor { to_process.add(rt.policy(), deadline, partition, term.sectors).map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "failed to process deadline {}, partition {}: {}", deadline, partition, @@ -2602,7 +2589,7 @@ impl Actor { to_process .check(policy.addressed_partitions_max, policy.addressed_sectors_max) .map_err(|e| { - actor_error!(ErrIllegalArgument, "cannot process requested parameters: {}", e) + actor_error!(illegal_argument, "cannot process requested parameters: {}", e) })?; } @@ -2619,7 +2606,7 @@ impl Actor { if consensus_fault_active(&info, rt.curr_epoch()) { return Err(actor_error!( - ErrForbidden, + forbidden, "recovery not allowed during active consensus fault" )); } @@ -2643,7 +2630,7 @@ impl Actor { ) .map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid recovery declaration deadline {}: {}", deadline_idx, e @@ -2652,7 +2639,7 @@ impl Actor { validate_fr_declaration_deadline(&target_deadline).map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "failed recovery declaration at deadline {}: {}", deadline_idx, e @@ -2716,16 +2703,12 @@ impl Actor { { let policy = rt.policy(); if params.deadline >= policy.wpost_period_deadlines { - return Err(actor_error!( - ErrIllegalArgument, - "invalid deadline {}", - params.deadline - )); + return Err(actor_error!(illegal_argument, "invalid deadline {}", params.deadline)); } } let partitions = params.partitions.validate().map_err(|e| { - actor_error!(ErrIllegalArgument, "failed to parse partitions bitfield: {}", e) + actor_error!(illegal_argument, "failed to parse partitions bitfield: {}", e) })?; let partition_count = partitions.len(); @@ -2748,7 +2731,7 @@ impl Actor { rt.curr_epoch(), ) { return Err(actor_error!( - ErrForbidden, + forbidden, "cannot compact deadline {} during its challenge window, \ or the prior challenge window, or before {} epochs have passed since its last challenge window ended", @@ -2761,7 +2744,7 @@ impl Actor { load_partitions_sectors_max(policy, info.window_post_partition_sectors); if partition_count > submission_partition_limit { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "too many partitions {}, limit {}", partition_count, submission_partition_limit @@ -2814,7 +2797,7 @@ impl Actor { if removed_power != added_power { return Err(actor_error!( - ErrIllegalState, + illegal_state, "power changed when compacting partitions: was {:?}, is now {:?}", removed_power, added_power @@ -2861,16 +2844,16 @@ impl Actor { let mask_sector_numbers = params .mask_sector_numbers .validate() - .map_err(|e| actor_error!(ErrIllegalArgument, "invalid mask bitfield: {}", e))?; + .map_err(|e| actor_error!(illegal_argument, "invalid mask bitfield: {}", e))?; let last_sector_number = mask_sector_numbers .last() - .ok_or_else(|| actor_error!(ErrIllegalArgument, "invalid mask bitfield"))? + .ok_or_else(|| actor_error!(illegal_argument, "invalid mask bitfield"))? as SectorNumber; if last_sector_number > MAX_SECTOR_NUMBER { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "masked sector number {} exceeded max sector number", last_sector_number )); @@ -2901,13 +2884,13 @@ impl Actor { { if params.reward.is_negative() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot lock up a negative amount of funds" )); } if params.penalty.is_negative() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot penalize a negative amount of funds" )); } @@ -2923,12 +2906,12 @@ impl Actor { // This ensures the miner has sufficient funds to lock up amountToLock. // This should always be true if reward actor sends reward funds with the message. let unlocked_balance = st.get_unlocked_balance(&rt.current_balance()).map_err(|e| { - actor_error!(ErrIllegalState, "failed to calculate unlocked balance: {}", e) + actor_error!(illegal_state, "failed to calculate unlocked balance: {}", e) })?; if unlocked_balance < reward_to_lock { return Err(actor_error!( - ErrInsufficientFunds, + insufficient_funds, "insufficient funds to lock, available: {}, requested: {}", unlocked_balance, reward_to_lock @@ -2943,13 +2926,13 @@ impl Actor { locked_reward_vesting_spec, ) .map_err(|e| { - actor_error!(ErrIllegalState, "failed to lock funds in vesting table: {}", e) + actor_error!(illegal_state, "failed to lock funds in vesting table: {}", e) })?; pledge_delta_total -= &newly_vested; pledge_delta_total += &reward_to_lock; st.apply_penalty(¶ms.penalty) - .map_err(|e| actor_error!(ErrIllegalState, "failed to apply penalty: {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to apply penalty: {}", e))?; // Attempt to repay all fee debt in this call. In most cases the miner will have enough // funds in the *reward alone* to cover the penalty. In the rare case a miner incurs more @@ -2992,10 +2975,10 @@ impl Actor { let fault = rt .verify_consensus_fault(¶ms.header1, ¶ms.header2, ¶ms.header_extra) .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_ARGUMENT, "fault not verified"))? - .ok_or_else(|| actor_error!(ErrIllegalArgument, "No consensus fault found"))?; + .ok_or_else(|| actor_error!(illegal_argument, "No consensus fault found"))?; if fault.target != rt.message().receiver() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "fault by {} reported to miner {}", fault.target, rt.message().receiver() @@ -3006,7 +2989,7 @@ impl Actor { let fault_age = rt.curr_epoch() - fault.epoch; if fault_age <= 0 { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid fault epoch {} ahead of current {}", fault.epoch, rt.curr_epoch() @@ -3030,7 +3013,7 @@ impl Actor { // Verify miner hasn't already been faulted if fault.epoch < info.consensus_fault_elapsed { return Err(actor_error!( - ErrForbidden, + forbidden, "fault epoch {} is too old, last exclusion period ended at {}", fault.epoch, info.consensus_fault_elapsed @@ -3038,7 +3021,7 @@ impl Actor { } st.apply_penalty(&fault_penalty).map_err(|e| { - actor_error!(ErrIllegalState, format!("failed to apply penalty: {}", e)) + actor_error!(illegal_state, format!("failed to apply penalty: {}", e)) })?; // Pay penalty @@ -3048,7 +3031,9 @@ impl Actor { rt.curr_epoch(), &rt.current_balance(), ) - .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to pay fees"))?; + .map_err(|e| { + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to pay fees") + })?; let mut burn_amount = &penalty_from_vesting + &penalty_from_balance; pledge_delta -= penalty_from_vesting; @@ -3089,7 +3074,7 @@ impl Actor { { if params.amount_requested.is_negative() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "negative fund requested for withdrawal: {}", params.amount_requested )); @@ -3106,7 +3091,7 @@ impl Actor { // Ensure we don't have any pending terminations. if !state.early_terminations.is_empty() { return Err(actor_error!( - ErrForbidden, + forbidden, "cannot withdraw funds while {} deadlines have terminated sectors \ with outstanding fees", state.early_terminations.len() @@ -3125,7 +3110,7 @@ impl Actor { let available_balance = state.get_available_balance(&rt.current_balance()).map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, format!("failed to calculate available balance: {}", e) ) })?; @@ -3140,14 +3125,14 @@ impl Actor { let amount_withdrawn = std::cmp::min(&available_balance, ¶ms.amount_requested); if amount_withdrawn.is_negative() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "negative amount to withdraw: {}", amount_withdrawn )); } if amount_withdrawn > &available_balance { return Err(actor_error!( - ErrIllegalState, + illegal_state, "amount to withdraw {} < available {}", amount_withdrawn, available_balance @@ -3210,7 +3195,7 @@ impl Actor { let payload: CronEventPayload = from_slice(¶ms.event_payload).map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, format!("failed to unmarshal miner cron payload into expected structure: {}", e) ) })?; @@ -3318,17 +3303,12 @@ where // Pay penalty state .apply_penalty(&penalty) - .map_err(|e| actor_error!(ErrIllegalState, "failed to apply penalty: {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to apply penalty: {}", e))?; // Remove pledge requirement. let mut pledge_delta = -total_initial_pledge; state.add_initial_pledge(&pledge_delta).map_err(|e| { - actor_error!( - ErrIllegalState, - "failed to add initial pledge {}: {}", - pledge_delta, - e - ) + actor_error!(illegal_state, "failed to add initial pledge {}: {}", pledge_delta, e) })?; // Use unlocked pledge to pay down outstanding fee debt @@ -3419,7 +3399,7 @@ where state .apply_penalty(&deposit_to_burn) - .map_err(|e| actor_error!(ErrIllegalState, "failed to apply penalty: {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to apply penalty: {}", e))?; log::debug!( "storage provider {} penalized {} for expired pre commits", @@ -3448,7 +3428,7 @@ where state .apply_penalty(&penalty_target) - .map_err(|e| actor_error!(ErrIllegalState, "failed to apply penalty: {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to apply penalty: {}", e))?; log::debug!( "storage provider {} penalized {} for continued fault", @@ -3530,7 +3510,7 @@ where // Expiration must be after activation. Check this explicitly to avoid an underflow below. if expiration <= activation { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "sector expiration {} must be after activation {}", expiration, activation @@ -3540,7 +3520,7 @@ where // expiration cannot be less than minimum after activation if expiration - activation < policy.min_sector_expiration { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid expiration {}, total sector lifetime ({}) must exceed {} after activation {}", expiration, expiration - activation, @@ -3552,7 +3532,7 @@ where // expiration cannot exceed MaxSectorExpirationExtension from now if expiration > rt.curr_epoch() + policy.max_sector_expiration_extension { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid expiration {}, cannot be more than {} past current epoch {}", expiration, policy.max_sector_expiration_extension, @@ -3562,11 +3542,11 @@ where // total sector lifetime cannot exceed SectorMaximumLifetime for the sector's seal proof let max_lifetime = seal_proof_sector_maximum_lifetime(seal_proof).ok_or_else(|| { - actor_error!(ErrIllegalArgument, "unrecognized seal proof type {:?}", seal_proof) + actor_error!(illegal_argument, "unrecognized seal proof type {:?}", seal_proof) })?; if expiration - activation > max_lifetime { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "invalid expiration {}, total sector lifetime ({}) cannot exceed {} after activation {}", expiration, expiration - activation, @@ -3596,12 +3576,12 @@ where ) })? .ok_or_else(|| { - actor_error!(ErrNotFound, "no such sector {} to replace", params.replace_sector_number) + actor_error!(not_found, "no such sector {} to replace", params.replace_sector_number) })?; if !replace_sector.deal_ids.is_empty() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot replace sector {} which has deals", params.replace_sector_number )); @@ -3613,7 +3593,7 @@ where let replace_w_post_proof = replace_sector.seal_proof.registered_window_post_proof().map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to lookup Window PoSt proof type for sector seal proof {:?}: {}", replace_sector.seal_proof, e @@ -3621,7 +3601,7 @@ where })?; let new_w_post_proof = params.seal_proof.registered_window_post_proof().map_err(|e| { actor_error!( - ErrIllegalArgument, + illegal_argument, "failed to lookup Window PoSt proof type for new seal proof {:?}: {}", replace_sector.seal_proof, e @@ -3630,7 +3610,7 @@ where if replace_w_post_proof != new_w_post_proof { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "new sector window PoSt proof type {:?} must match replaced proof type {:?} (seal proof type {:?})", replace_w_post_proof, new_w_post_proof, @@ -3640,7 +3620,7 @@ where if params.expiration < replace_sector.expiration { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot replace sector {} expiration {} with sooner expiration {}", params.replace_sector_number, replace_sector.expiration, @@ -3772,7 +3752,7 @@ where *i } else { return Err(actor_error!( - ErrIllegalState, + illegal_state, "runtime provided bad receiver address {}", rt.message().receiver() )); @@ -3810,7 +3790,7 @@ where RT: Runtime, { if rt.curr_epoch() <= params.interactive_epoch { - return Err(actor_error!(ErrForbidden, "too early to prove sector")); + return Err(actor_error!(forbidden, "too early to prove sector")); } let commds = request_unsealed_sector_cids( @@ -3825,7 +3805,7 @@ where *i } else { return Err(actor_error!( - ErrIllegalState, + illegal_state, "runtime provided non ID receiver address {}", rt.message().receiver() )); @@ -3877,7 +3857,7 @@ where )? .deserialize()?; if data_commitment_inputs.len() != ret.commds.len() { - return Err(actor_error!(ErrIllegalState, + return Err(actor_error!(illegal_state, "number of data commitments computed {} does not match number of data commitment inputs {}", ret.commds.len(), data_commitment_inputs.len() )); @@ -3973,11 +3953,11 @@ where { let resolved = rt .resolve_address(&raw) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "unable to resolve address: {}", raw))?; + .ok_or_else(|| actor_error!(illegal_argument, "unable to resolve address: {}", raw))?; let owner_code = rt .get_actor_code_cid(&resolved) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "no code for address: {}", resolved))?; + .ok_or_else(|| actor_error!(illegal_argument, "no code for address: {}", resolved))?; let is_principal = rt .resolve_builtin_actor_type(&owner_code) @@ -3987,7 +3967,7 @@ where if !is_principal { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "owner actor type must be a principal, was {}", owner_code )); @@ -4005,14 +3985,14 @@ where { let resolved = rt .resolve_address(&raw) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "unable to resolve address: {}", raw))?; + .ok_or_else(|| actor_error!(illegal_argument, "unable to resolve address: {}", raw))?; let worker_code = rt .get_actor_code_cid(&resolved) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "no code for address: {}", resolved))?; + .ok_or_else(|| actor_error!(illegal_argument, "no code for address: {}", resolved))?; if rt.resolve_builtin_actor_type(&worker_code) != Some(Type::Account) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "worker actor type must be an account, was {}", worker_code )); @@ -4028,7 +4008,7 @@ where let pub_key: Address = deserialize(&ret, "address response")?; if pub_key.protocol() != Protocol::BLS { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "worker account {} must have BLS pubkey, was {}", resolved, pub_key.protocol() @@ -4264,7 +4244,7 @@ where fn check_control_addresses(policy: &Policy, control_addrs: &[Address]) -> Result<(), ActorError> { if control_addrs.len() > policy.max_control_addresses { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "control addresses length {} exceeds max control addresses length {}", control_addrs.len(), policy.max_control_addresses @@ -4282,7 +4262,7 @@ fn check_valid_post_proof_type( Ok(()) } else { Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "proof type {:?} not allowed for new miner actors", proof_type )) @@ -4296,7 +4276,7 @@ fn check_peer_info( ) -> Result<(), ActorError> { if peer_id.len() > policy.max_peer_id_length { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "peer ID size of {} exceeds maximum size of {}", peer_id.len(), policy.max_peer_id_length @@ -4306,14 +4286,14 @@ fn check_peer_info( let mut total_size = 0; for ma in multiaddrs { if ma.0.is_empty() { - return Err(actor_error!(ErrIllegalArgument, "invalid empty multiaddr")); + return Err(actor_error!(illegal_argument, "invalid empty multiaddr")); } total_size += ma.0.len(); } if total_size > policy.max_multiaddr_data { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "multiaddr size of {} exceeds maximum of {}", total_size, policy.max_multiaddr_data @@ -4371,7 +4351,7 @@ where // When all prove commits have failed abort early if valid_pre_commits.is_empty() { - return Err(actor_error!(ErrIllegalArgument, "all prove commits failed to validate")); + return Err(actor_error!(illegal_argument, "all prove commits failed to validate")); } let (total_pledge, newly_vested) = rt.transaction(|state: &mut State, rt| { @@ -4482,14 +4462,14 @@ where // Unlock deposit for successful proofs, make it available for lock-up as initial pledge. state .add_pre_commit_deposit(&(-deposit_to_unlock)) - .map_err(|e| actor_error!(ErrIllegalState, "failed to add precommit deposit: {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to add precommit deposit: {}", e))?; let unlocked_balance = state.get_unlocked_balance(&rt.current_balance()).map_err(|e| { - actor_error!(ErrIllegalState, "failed to calculate unlocked balance: {}", e) + actor_error!(illegal_state, "failed to calculate unlocked balance: {}", e) })?; if unlocked_balance < total_pledge { return Err(actor_error!( - ErrInsufficientFunds, + insufficient_funds, "insufficient funds for aggregate initial pledge requirement {}, available: {}", total_pledge, unlocked_balance @@ -4498,7 +4478,7 @@ where state .add_initial_pledge(&total_pledge) - .map_err(|e| actor_error!(ErrIllegalState, "failed to add initial pledge: {}", e))?; + .map_err(|e| actor_error!(illegal_state, "failed to add initial pledge: {}", e))?; state.check_balance_invariants(&rt.current_balance()).map_err(balance_invariants_broken)?; @@ -4513,7 +4493,10 @@ where // XXX: probably better to push this one level down into state fn balance_invariants_broken(e: Error) -> ActorError { - ActorError::new_unchecked(ERR_BALANCE_INVARIANTS_BROKEN, format!("balance invariants broken: {}", e)) + ActorError::unchecked( + ERR_BALANCE_INVARIANTS_BROKEN, + format!("balance invariants broken: {}", e), + ) } impl ActorCode for Actor { @@ -4635,7 +4618,7 @@ impl ActorCode for Actor { let res = Self::prove_replica_updates(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::serialize(res)?) } - None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), + None => Err(actor_error!(unhandled_message, "Invalid method")), } } } diff --git a/actors/miner/src/partition_state.rs b/actors/miner/src/partition_state.rs index 9c7280737..5d5420982 100644 --- a/actors/miner/src/partition_state.rs +++ b/actors/miner/src/partition_state.rs @@ -219,7 +219,7 @@ impl Partition { quant: QuantSpec, ) -> anyhow::Result<(BitField, PowerPair, PowerPair)> { validate_partition_contains_sectors(self, sector_numbers) - .map_err(|e| actor_error!(ErrIllegalArgument; "failed fault declaration: {}", e))?; + .map_err(|e| actor_error!(illegal_argument; "failed fault declaration: {}", e))?; let sector_numbers = sector_numbers .validate() @@ -316,7 +316,7 @@ impl Partition { ) -> anyhow::Result<()> { // Check that the declared sectors are actually assigned to the partition. validate_partition_contains_sectors(self, sector_numbers) - .map_err(|e| actor_error!(ErrIllegalArgument; "failed fault declaration: {}", e))?; + .map_err(|e| actor_error!(illegal_argument; "failed fault declaration: {}", e))?; let sector_numbers = sector_numbers .validate() @@ -377,7 +377,7 @@ impl Partition { quant: QuantSpec, ) -> anyhow::Result> { let sector_numbers = sector_numbers.validate().map_err(|e| { - actor_error!(ErrIllegalArgument, "failed to validate rescheduled sectors: {}", e) + actor_error!(illegal_argument, "failed to validate rescheduled sectors: {}", e) })?; // Ensure these sectors actually belong to this partition. @@ -490,11 +490,11 @@ impl Partition { ) -> anyhow::Result { let live_sectors = self.live_sectors(); let sector_numbers = sector_numbers.validate().map_err(|e| { - actor_error!(ErrIllegalArgument, "failed to validate terminating sectors: {}", e) + actor_error!(illegal_argument, "failed to validate terminating sectors: {}", e) })?; if !live_sectors.contains_all(sector_numbers) { - return Err(actor_error!(ErrIllegalArgument, "can only terminate live sectors").into()); + return Err(actor_error!(illegal_argument, "can only terminate live sectors").into()); } let sector_infos = sectors.load_sector(sector_numbers)?; @@ -722,7 +722,7 @@ impl Partition { skipped: &mut UnvalidatedBitField, ) -> anyhow::Result<(PowerPair, PowerPair, PowerPair, bool)> { let skipped = skipped.validate().map_err(|e| { - actor_error!(ErrIllegalArgument, "failed to validate skipped sectors: {}", e) + actor_error!(illegal_argument, "failed to validate skipped sectors: {}", e) })?; if skipped.is_empty() { @@ -732,7 +732,7 @@ impl Partition { // Check that the declared sectors are actually in the partition. if !self.sectors.contains_all(skipped) { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "skipped faults contains sectors outside partition" ) .into()); diff --git a/actors/miner/src/sectors.rs b/actors/miner/src/sectors.rs index a0db03587..49b0bd959 100644 --- a/actors/miner/src/sectors.rs +++ b/actors/miner/src/sectors.rs @@ -29,9 +29,7 @@ impl<'db, BS: Blockstore> Sectors<'db, BS> { ) -> Result, ActorError> { let sector_numbers = match sector_numbers.validate() { Ok(sector_numbers) => sector_numbers, - Err(e) => { - return Err(actor_error!(ErrIllegalArgument, "failed to load sectors: {}", e)) - } + Err(e) => return Err(actor_error!(illegal_argument, "failed to load sectors: {}", e)), }; let mut sector_infos: Vec = Vec::new(); @@ -46,7 +44,7 @@ impl<'db, BS: Blockstore> Sectors<'db, BS> { ) })? .cloned() - .ok_or_else(|| actor_error!(ErrNotFound; "sector not found: {}", sector_number))?; + .ok_or_else(|| actor_error!(not_found; "sector not found: {}", sector_number))?; sector_infos.push(sector_on_chain); } Ok(sector_infos) diff --git a/actors/miner/src/state.rs b/actors/miner/src/state.rs index 6a57ab153..1e96acc49 100644 --- a/actors/miner/src/state.rs +++ b/actors/miner/src/state.rs @@ -199,7 +199,7 @@ impl State { pub fn get_info(&self, store: &BS) -> anyhow::Result { match store.get_cbor(&self.info) { Ok(Some(info)) => Ok(info), - Ok(None) => Err(actor_error!(ErrNotFound, "failed to get miner info").into()), + Ok(None) => Err(actor_error!(not_found, "failed to get miner info").into()), Err(e) => Err(e.downcast_wrap("failed to get miner info")), } } @@ -259,7 +259,7 @@ impl State { "failed to load allocated sectors bitfield", ) })? - .ok_or_else(|| actor_error!(ErrIllegalState, "allocated sectors bitfield not found"))?; + .ok_or_else(|| actor_error!(illegal_state, "allocated sectors bitfield not found"))?; if policy != CollisionPolicy::AllowCollisions { // NOTE: A fancy merge algorithm could extract this intersection while merging, below, saving @@ -267,7 +267,7 @@ impl State { let collisions = &prior_allocation & sector_numbers; if !collisions.is_empty() { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "sector numbers {:?} already allocated", collisions )); @@ -643,7 +643,7 @@ impl State { let exists = partition.sectors.get(sector_number); if !exists { return Err(actor_error!( - ErrNotFound; + not_found; "sector {} not a member of partition {}, deadline {}", sector_number, partition_idx, deadline_idx ) @@ -683,7 +683,7 @@ impl State { if !partition.sectors.get(sector_number) { return Err(actor_error!( - ErrNotFound; + not_found; "sector {} not a member of partition {}, deadline {}", sector_number, partition_idx, deadline_idx ) @@ -692,7 +692,7 @@ impl State { if partition.faults.get(sector_number) { return Err(actor_error!( - ErrForbidden; + forbidden; "sector {} not a member of partition {}, deadline {}", sector_number, partition_idx, deadline_idx ) @@ -701,7 +701,7 @@ impl State { if partition.terminated.get(sector_number) { return Err(actor_error!( - ErrNotFound; + not_found; "sector {} not of partition {}, deadline {} is terminated", sector_number, partition_idx, deadline_idx ) @@ -723,9 +723,11 @@ impl State { pub fn load_deadlines(&self, store: &BS) -> Result { store .get_cbor::(&self.deadlines) - .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deadlines"))? + .map_err(|e| { + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deadlines") + })? .ok_or_else( - || actor_error!(ErrIllegalState; "failed to load deadlines {}", self.deadlines), + || actor_error!(illegal_state; "failed to load deadlines {}", self.deadlines), ) } @@ -743,11 +745,11 @@ impl State { Ok(store .get_cbor(&self.vesting_funds) .map_err(|e| { - e.downcast_wrap( - format!("failed to load vesting funds {}", self.vesting_funds), - ) + e.downcast_wrap(format!("failed to load vesting funds {}", self.vesting_funds)) })? - .ok_or_else(|| actor_error!(ErrNotFound; "failed to load vesting funds {:?}", self.vesting_funds))?) + .ok_or_else( + || actor_error!(not_found; "failed to load vesting funds {:?}", self.vesting_funds), + )?) } /// Saves the vesting table to the store. @@ -883,7 +885,7 @@ impl State { let unlocked_balance = self.get_unlocked_balance(curr_balance)?; if unlocked_balance < self.fee_debt { return Err(actor_error!( - ErrInsufficientFunds, + insufficient_funds, "unlocked balance can not repay fee debt ({} < {})", unlocked_balance, self.fee_debt @@ -1174,13 +1176,13 @@ impl State { for sector_no in sector_nos.iter() { if sector_no as u64 > MAX_SECTOR_NUMBER { return Err( - actor_error!(ErrIllegalArgument; "sector number greater than maximum").into() + actor_error!(illegal_argument; "sector number greater than maximum").into() ); } let info: &SectorPreCommitOnChainInfo = precommitted .get(&u64_key(sector_no as u64))? - .ok_or_else(|| actor_error!(ErrNotFound, "sector {} not found", sector_no))?; + .ok_or_else(|| actor_error!(not_found, "sector {} not found", sector_no))?; precommits.push(info.clone()); } Ok(precommits) @@ -1257,11 +1259,11 @@ impl MinerInfo { ) -> Result { let sector_size = window_post_proof_type .sector_size() - .map_err(|e| actor_error!(ErrIllegalArgument, "invalid sector size: {}", e))?; + .map_err(|e| actor_error!(illegal_argument, "invalid sector size: {}", e))?; let window_post_partition_sectors = window_post_proof_type .window_post_partitions_sector() - .map_err(|e| actor_error!(ErrIllegalArgument, "invalid partition sectors: {}", e))?; + .map_err(|e| actor_error!(illegal_argument, "invalid partition sectors: {}", e))?; Ok(Self { owner, diff --git a/actors/miner/tests/miner_actor_test_wpost.rs b/actors/miner/tests/miner_actor_test_wpost.rs index 897bf8fea..087b94271 100644 --- a/actors/miner/tests/miner_actor_test_wpost.rs +++ b/actors/miner/tests/miner_actor_test_wpost.rs @@ -180,7 +180,11 @@ fn invalid_submissions() { params, PoStConfig::empty(), ); - expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "too many partitions", result); + expect_abort_contains_message( + ExitCode::USR_ILLEGAL_ARGUMENT, + "too many partitions", + result, + ); rt.reset(); } @@ -349,7 +353,11 @@ fn invalid_submissions() { params, PoStConfig::empty(), ); - expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "bytes of randomness", result); + expect_abort_contains_message( + ExitCode::USR_ILLEGAL_ARGUMENT, + "bytes of randomness", + result, + ); rt.reset(); } @@ -549,7 +557,11 @@ fn duplicate_proof_rejected() { miner::Method::SubmitWindowedPoSt as u64, &RawBytes::serialize(params).unwrap(), ); - expect_abort_contains_message(ExitCode::USR_ILLEGAL_ARGUMENT, "partition already proven", result); + expect_abort_contains_message( + ExitCode::USR_ILLEGAL_ARGUMENT, + "partition already proven", + result, + ); rt.reset(); // Advance to end-of-deadline cron to verify no penalties. diff --git a/actors/multisig/src/lib.rs b/actors/multisig/src/lib.rs index c6d3c134d..ffb88c622 100644 --- a/actors/multisig/src/lib.rs +++ b/actors/multisig/src/lib.rs @@ -58,12 +58,12 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&*INIT_ACTOR_ADDR))?; if params.signers.is_empty() { - return Err(actor_error!(ErrIllegalArgument; "Must have at least one signer")); + return Err(actor_error!(illegal_argument; "Must have at least one signer")); } if params.signers.len() > SIGNERS_MAX { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot add more than {} signers", SIGNERS_MAX )); @@ -81,7 +81,7 @@ impl Actor { })?; if !dedup_signers.insert(resolved.id().expect("address should be resolved")) { return Err( - actor_error!(ErrIllegalArgument; "duplicate signer not allowed: {}", signer), + actor_error!(illegal_argument; "duplicate signer not allowed: {}", signer), ); } resolved_signers.push(resolved); @@ -89,16 +89,16 @@ impl Actor { if params.num_approvals_threshold > params.signers.len() as u64 { return Err( - actor_error!(ErrIllegalArgument; "must not require more approvals than signers"), + actor_error!(illegal_argument; "must not require more approvals than signers"), ); } if params.num_approvals_threshold < 1 { - return Err(actor_error!(ErrIllegalArgument; "must require at least one approval")); + return Err(actor_error!(illegal_argument; "must require at least one approval")); } if params.unlock_duration < 0 { - return Err(actor_error!(ErrIllegalArgument; "negative unlock duration disallowed")); + return Err(actor_error!(illegal_argument; "negative unlock duration disallowed")); } let empty_root = @@ -139,7 +139,7 @@ impl Actor { if params.value.sign() == Sign::Minus { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "proposed value must be non-negative, was {}", params.value )); @@ -147,11 +147,14 @@ impl Actor { let (txn_id, txn) = rt.transaction(|st: &mut State, rt| { if !st.is_signer(&proposer) { - return Err(actor_error!(ErrForbidden, "{} is not a signer", proposer)); + return Err(actor_error!(forbidden, "{} is not a signer", proposer)); } let mut ptx = make_map_with_root(&st.pending_txs, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to load pending transactions", + ) })?; let t_id = st.next_tx_id; @@ -199,11 +202,14 @@ impl Actor { let id = params.id; let (st, txn) = rt.transaction(|st: &mut State, rt| { if !st.is_signer(&approver) { - return Err(actor_error!(ErrForbidden; "{} is not a signer", approver)); + return Err(actor_error!(forbidden; "{} is not a signer", approver)); } let ptx = make_map_with_root(&st.pending_txs, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to load pending transactions", + ) })?; let txn = get_transaction(rt, &ptx, params.id, params.proposal_hash)?; @@ -235,7 +241,7 @@ impl Actor { rt.transaction(|st: &mut State, rt| { if !st.is_signer(&caller_addr) { - return Err(actor_error!(ErrForbidden; "{} is not a signer", caller_addr)); + return Err(actor_error!(forbidden; "{} is not a signer", caller_addr)); } let mut ptx = make_map_with_root::<_, Transaction>(&st.pending_txs, rt.store()) @@ -255,14 +261,12 @@ impl Actor { ) })? .ok_or_else(|| { - actor_error!(ErrNotFound, "no such transaction {:?} to cancel", params.id) + actor_error!(not_found, "no such transaction {:?} to cancel", params.id) })?; // Check to make sure transaction proposer is caller address if tx.approved.get(0) != Some(&caller_addr) { - return Err( - actor_error!(ErrForbidden; "Cannot cancel another signers transaction"), - ); + return Err(actor_error!(forbidden; "Cannot cancel another signers transaction")); } let calculated_hash = compute_proposal_hash(&tx, rt).map_err(|e| { @@ -273,7 +277,7 @@ impl Actor { })?; if !params.proposal_hash.is_empty() && params.proposal_hash != calculated_hash { - return Err(actor_error!(ErrIllegalState, "hash does not match proposal params")); + return Err(actor_error!(illegal_state, "hash does not match proposal params")); } st.pending_txs = ptx.flush().map_err(|e| { @@ -305,17 +309,13 @@ impl Actor { rt.transaction(|st: &mut State, _| { if st.signers.len() >= SIGNERS_MAX { return Err(actor_error!( - ErrForbidden, + forbidden, "cannot add more than {} signers", SIGNERS_MAX )); } if st.is_signer(&resolved_new_signer) { - return Err(actor_error!( - ErrForbidden, - "{} is already a signer", - resolved_new_signer - )); + return Err(actor_error!(forbidden, "{} is already a signer", resolved_new_signer)); } // Add signer and increase threshold if set @@ -345,16 +345,16 @@ impl Actor { rt.transaction(|st: &mut State, rt| { if !st.is_signer(&resolved_old_signer) { - return Err(actor_error!(ErrForbidden, "{} is not a signer", resolved_old_signer)); + return Err(actor_error!(forbidden, "{} is not a signer", resolved_old_signer)); } if st.signers.len() == 1 { - return Err(actor_error!(ErrForbidden; "Cannot remove only signer")); + return Err(actor_error!(forbidden; "Cannot remove only signer")); } if !params.decrease && ((st.signers.len() - 1) as u64) < st.num_approvals_threshold { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "can't reduce signers to {} below threshold {} with decrease=false", st.signers.len(), st.num_approvals_threshold @@ -364,7 +364,7 @@ impl Actor { if params.decrease { if st.num_approvals_threshold < 2 { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "can't decrease approvals from {} to {}", st.num_approvals_threshold, st.num_approvals_threshold - 1 @@ -411,13 +411,11 @@ impl Actor { rt.transaction(|st: &mut State, rt| { if !st.is_signer(&from_resolved) { - return Err(actor_error!(ErrForbidden; "{} is not a signer", from_resolved)); + return Err(actor_error!(forbidden; "{} is not a signer", from_resolved)); } if st.is_signer(&to_resolved) { - return Err( - actor_error!(ErrIllegalArgument; "{} is already a signer", to_resolved), - ); + return Err(actor_error!(illegal_argument; "{} is already a signer", to_resolved)); } // Remove signer from state (retain preserves order of elements) @@ -453,7 +451,7 @@ impl Actor { rt.transaction(|st: &mut State, _| { // Check if valid threshold value if params.new_threshold == 0 || params.new_threshold > st.signers.len() as u64 { - return Err(actor_error!(ErrIllegalArgument; "New threshold value not supported")); + return Err(actor_error!(illegal_argument; "New threshold value not supported")); } // Update threshold on state @@ -474,16 +472,16 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&receiver))?; if params.unlock_duration <= 0 { - return Err(actor_error!(ErrIllegalArgument, "unlock duration must be positive")); + return Err(actor_error!(illegal_argument, "unlock duration must be positive")); } if params.amount.is_negative() { - return Err(actor_error!(ErrIllegalArgument, "amount to lock must be positive")); + return Err(actor_error!(illegal_argument, "amount to lock must be positive")); } rt.transaction(|st: &mut State, _| { if st.unlock_duration != 0 { - return Err(actor_error!(ErrForbidden, "modification of unlock disallowed")); + return Err(actor_error!(forbidden, "modification of unlock disallowed")); } st.set_locked(params.start_epoch, params.unlock_duration, params.amount); Ok(()) @@ -504,7 +502,7 @@ impl Actor { for previous_approver in &txn.approved { if *previous_approver == rt.message().caller() { return Err(actor_error!( - ErrForbidden, + forbidden, "{} already approved this message", previous_approver )); @@ -513,7 +511,10 @@ impl Actor { let st = rt.transaction(|st: &mut State, rt| { let mut ptx = make_map_with_root(&st.pending_txs, rt.store()).map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load pending transactions") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to load pending transactions", + ) })?; // update approved on the transaction @@ -557,9 +558,8 @@ where let mut applied = false; let threshold_met = txn.approved.len() as u64 >= st.num_approvals_threshold; if threshold_met { - st.check_available(rt.current_balance(), &txn.value, rt.curr_epoch()).map_err(|e| { - actor_error!(ErrInsufficientFunds, "insufficient funds unlocked: {}", e) - })?; + st.check_available(rt.current_balance(), &txn.value, rt.curr_epoch()) + .map_err(|e| actor_error!(insufficient_funds, "insufficient funds unlocked: {}", e))?; match rt.send(txn.to, txn.method, txn.params.clone(), txn.value.clone()) { Ok(ser) => { @@ -618,9 +618,7 @@ where format!("failed to load transaction {:?} for approval", txn_id), ) })? - .ok_or_else(|| { - actor_error!(ErrNotFound, "no such transaction {:?} for approval", txn_id) - })?; + .ok_or_else(|| actor_error!(not_found, "no such transaction {:?} for approval", txn_id))?; if !proposal_hash.is_empty() { let calculated_hash = compute_proposal_hash(txn, rt).map_err(|e| { @@ -632,7 +630,7 @@ where if proposal_hash != calculated_hash { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "hash does not match proposal params (ensure requester is an ID address)" )); } @@ -702,7 +700,7 @@ impl ActorCode for Actor { Self::lock_balance(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::default()) } - None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), + None => Err(actor_error!(unhandled_message, "Invalid method")), } } } diff --git a/actors/paych/src/lib.rs b/actors/paych/src/lib.rs index aa0130416..2dc7c6db8 100644 --- a/actors/paych/src/lib.rs +++ b/actors/paych/src/lib.rs @@ -81,13 +81,13 @@ impl Actor { let code_cid = rt .get_actor_code_cid(&resolved) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "no code for address {}", resolved))?; + .ok_or_else(|| actor_error!(illegal_argument, "no code for address {}", resolved))?; let typ = rt.resolve_builtin_actor_type(&code_cid); if typ != Some(Type::Account) { Err(actor_error!( - ErrForbidden, + forbidden, "actor {} must be an account, was {} ({:?})", raw, code_cid, @@ -116,22 +116,22 @@ impl Actor { let sig = sv .signature .as_ref() - .ok_or_else(|| actor_error!(ErrIllegalArgument, "voucher has no signature"))?; + .ok_or_else(|| actor_error!(illegal_argument, "voucher has no signature"))?; if st.settling_at != 0 && rt.curr_epoch() >= st.settling_at { - return Err(ActorError::new_unchecked( + return Err(ActorError::unchecked( ERR_CHANNEL_STATE_UPDATE_AFTER_SETTLED, "no vouchers can be processed after settling at epoch".to_string(), )); } if params.secret.len() > MAX_SECRET_SIZE { - return Err(actor_error!(ErrIllegalArgument, "secret must be at most 256 bytes long")); + return Err(actor_error!(illegal_argument, "secret must be at most 256 bytes long")); } // Generate unsigned bytes let sv_bz = sv.signing_bytes().map_err(|e| { - ActorError::ErrSerialization(format!("failed to serialized SignedVoucher: {}", e)) + ActorError::serialization(format!("failed to serialized SignedVoucher: {}", e)) })?; // Validate signature @@ -142,34 +142,34 @@ impl Actor { let pch_addr = rt.message().receiver(); let svpch_id_addr = rt.resolve_address(&sv.channel_addr).ok_or_else(|| { actor_error!( - ErrIllegalArgument, + illegal_argument, "voucher payment channel address {} does not resolve to an ID address", sv.channel_addr ) })?; if pch_addr != svpch_id_addr { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "voucher payment channel address {} does not match receiver {}", svpch_id_addr, pch_addr)); } if rt.curr_epoch() < sv.time_lock_min { - return Err(actor_error!(ErrIllegalArgument; "cannot use this voucher yet")); + return Err(actor_error!(illegal_argument; "cannot use this voucher yet")); } if sv.time_lock_max != 0 && rt.curr_epoch() > sv.time_lock_max { - return Err(actor_error!(ErrIllegalArgument; "this voucher has expired")); + return Err(actor_error!(illegal_argument; "this voucher has expired")); } if sv.amount.sign() == Sign::Minus { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "voucher amount must be non-negative, was {}", sv.amount)); } if !sv.secret_pre_image.is_empty() { let hashed_secret: &[u8] = &rt.hash_blake2b(¶ms.secret); if hashed_secret != sv.secret_pre_image.as_slice() { - return Err(actor_error!(ErrIllegalArgument; "incorrect secret")); + return Err(actor_error!(illegal_argument; "incorrect secret")); } } @@ -194,7 +194,7 @@ impl Actor { let mut lane_state = if let Some(state) = lane_state { if state.nonce >= sv.nonce { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "voucher has an outdated nonce, existing: {}, voucher: {}, cannot redeem", state.nonce, sv.nonce)); } @@ -209,18 +209,18 @@ impl Actor { let mut redeemed_from_others = BigInt::default(); for merge in sv.merges { if merge.lane == sv.lane { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "voucher cannot merge lanes into it's own lane")); } let mut other_ls = find_lane(&l_states, merge.lane)? .ok_or_else(|| { - actor_error!(ErrIllegalArgument; + actor_error!(illegal_argument; "voucher specifies invalid merge lane {}", merge.lane) })? .clone(); if other_ls.nonce >= merge.nonce { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "merged lane in voucher has outdated nonce, cannot redeem")); } @@ -246,12 +246,12 @@ impl Actor { let new_send_balance = balance_delta + &st.to_send; if new_send_balance < TokenAmount::from(0) { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "voucher would leave channel balance negative")); } if new_send_balance > rt.current_balance() { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "not enough funds in channel to cover voucher")); } @@ -291,7 +291,7 @@ impl Actor { rt.validate_immediate_caller_is([st.from, st.to].iter())?; if st.settling_at != 0 { - return Err(actor_error!(ErrIllegalState; "channel already settling")); + return Err(actor_error!(illegal_state; "channel already settling")); } st.settling_at = rt.curr_epoch() + SETTLE_DELAY; @@ -312,7 +312,7 @@ impl Actor { rt.validate_immediate_caller_is(&[st.from, st.to])?; if st.settling_at == 0 || rt.curr_epoch() < st.settling_at { - return Err(actor_error!(ErrForbidden; "payment channel not settling or settled")); + return Err(actor_error!(forbidden; "payment channel not settling or settled")); } // send ToSend to `to` @@ -335,7 +335,7 @@ where BS: Blockstore, { if id > MAX_LANE { - return Err(actor_error!(ErrIllegalArgument; "maximum lane ID is 2^63-1")); + return Err(actor_error!(illegal_argument; "maximum lane ID is 2^63-1")); } ls.get(id).map_err(|e| { @@ -370,7 +370,7 @@ impl ActorCode for Actor { Self::collect(rt)?; Ok(RawBytes::default()) } - _ => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + _ => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/power/src/lib.rs b/actors/power/src/lib.rs index 7b3e340a7..a10facfe3 100644 --- a/actors/power/src/lib.rs +++ b/actors/power/src/lib.rs @@ -140,7 +140,7 @@ impl Actor { st.update_stats_for_new_miner(window_post_proof_type).map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to update power stats for new miner {}: {}", &id_address, e @@ -214,7 +214,7 @@ impl Actor { // Ensure it is not possible to enter a large negative number which would cause // problems in cron processing. if params.event_epoch < 0 { - return Err(actor_error!(ErrIllegalArgument; + return Err(actor_error!(illegal_argument; "cron event epoch {} cannot be less than zero", params.event_epoch)); } @@ -297,7 +297,7 @@ impl Actor { st.add_pledge_total(pledge_delta); if st.total_pledge_collateral.is_negative() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "negative total pledge collateral {}", st.total_pledge_collateral )); @@ -345,7 +345,7 @@ impl Actor { })?; if let Some(arr) = arr { if arr.count() >= MAX_MINER_PROVE_COMMITS_PER_EPOCH { - return Err(ActorError::new_unchecked( + return Err(ActorError::unchecked( ERR_TOO_MANY_PROVE_COMMITS, format!( "miner {} attempting to prove commit over {} sectors in epoch", @@ -695,7 +695,7 @@ impl ActorCode for Actor { let res = Self::current_total_power(rt)?; Ok(RawBytes::serialize(res)?) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/power/src/state.rs b/actors/power/src/state.rs index 455c5ce88..421361afa 100644 --- a/actors/power/src/state.rs +++ b/actors/power/src/state.rs @@ -143,7 +143,7 @@ impl State { qa_power: &StoragePower, ) -> anyhow::Result<()> { let old_claim = get_claim(claims, miner)? - .ok_or_else(|| actor_error!(ErrNotFound, "no claim for actor {}", miner))?; + .ok_or_else(|| actor_error!(not_found, "no claim for actor {}", miner))?; self.total_qa_bytes_committed += qa_power; self.total_bytes_committed += power; @@ -182,21 +182,21 @@ impl State { if new_claim.raw_byte_power.is_negative() { return Err(anyhow!(actor_error!( - ErrIllegalState, + illegal_state, "negative claimed raw byte power: {}", new_claim.raw_byte_power ))); } if new_claim.quality_adj_power.is_negative() { return Err(anyhow!(actor_error!( - ErrIllegalState, + illegal_state, "negative claimed quality adjusted power: {}", new_claim.quality_adj_power ))); } if self.miner_above_min_power_count < 0 { return Err(anyhow!(actor_error!( - ErrIllegalState, + illegal_state, "negative amount of miners lather than min: {}", self.miner_above_min_power_count ))); @@ -266,15 +266,15 @@ impl State { where BS: Blockstore, { - let claims = make_map_with_root::<_, Claim>(&self.claims, store) - .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims"))?; + let claims = make_map_with_root::<_, Claim>(&self.claims, store).map_err(|e| { + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load claims") + })?; - if !claims - .contains_key(&miner_addr.to_bytes()) - .map_err(|e| e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to look up claim"))? - { + if !claims.contains_key(&miner_addr.to_bytes()).map_err(|e| { + e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to look up claim") + })? { return Err(actor_error!( - ErrForbidden, + forbidden, "unknown miner {} forbidden to interact with power actor", miner_addr )); @@ -353,14 +353,14 @@ pub fn set_claim( ) -> anyhow::Result<()> { if claim.raw_byte_power.is_negative() { return Err(anyhow!(actor_error!( - ErrIllegalState, + illegal_state, "negative claim raw power {}", claim.raw_byte_power ))); } if claim.quality_adj_power.is_negative() { return Err(anyhow!(actor_error!( - ErrIllegalState, + illegal_state, "negative claim quality-adjusted power {}", claim.quality_adj_power ))); diff --git a/actors/reward/src/lib.rs b/actors/reward/src/lib.rs index a5c1e46e2..a46dcc242 100644 --- a/actors/reward/src/lib.rs +++ b/actors/reward/src/lib.rs @@ -66,7 +66,7 @@ impl Actor { rt.create(&State::new(power))?; Ok(()) } else { - Err(actor_error!(ErrIllegalArgument, "argument should not be nil")) + Err(actor_error!(illegal_argument, "argument should not be nil")) } } @@ -91,30 +91,30 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&*SYSTEM_ACTOR_ADDR))?; let prior_balance = rt.current_balance(); if params.penalty.sign() == Sign::Minus { - return Err(actor_error!(ErrIllegalArgument, "negative penalty {}", params.penalty)); + return Err(actor_error!(illegal_argument, "negative penalty {}", params.penalty)); } if params.gas_reward.sign() == Sign::Minus { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "negative gas reward {}", params.gas_reward )); } if prior_balance < params.gas_reward { return Err(actor_error!( - ErrIllegalState, + illegal_state, "actor current balance {} insufficient to pay gas reward {}", prior_balance, params.gas_reward )); } if params.win_count <= 0 { - return Err(actor_error!(ErrIllegalArgument, "invalid win count {}", params.win_count)); + return Err(actor_error!(illegal_argument, "invalid win count {}", params.win_count)); } let miner_addr = rt .resolve_address(¶ms.miner) - .ok_or_else(|| actor_error!(ErrNotFound, "failed to resolve given owner address"))?; + .ok_or_else(|| actor_error!(not_found, "failed to resolve given owner address"))?; let penalty: TokenAmount = ¶ms.penalty * PENALTY_MULTIPLIER; @@ -133,7 +133,7 @@ impl Actor { block_reward = &total_reward - ¶ms.gas_reward; if block_reward.is_negative() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "programming error, block reward {} below zero", block_reward )); @@ -147,7 +147,7 @@ impl Actor { // * as they treat panics as an exit code. Revisit this. if total_reward > prior_balance { return Err(actor_error!( - ErrIllegalState, + illegal_state, "reward {} exceeds balance {}", total_reward, prior_balance @@ -210,7 +210,7 @@ impl Actor { { rt.validate_immediate_caller_is(std::iter::once(&*STORAGE_POWER_ACTOR_ADDR))?; let curr_realized_power = curr_realized_power - .ok_or_else(|| actor_error!(ErrIllegalArgument, "argument cannot be None"))?; + .ok_or_else(|| actor_error!(illegal_argument, "argument cannot be None"))?; rt.transaction(|st: &mut State, rt| { let prev = st.epoch; @@ -258,7 +258,7 @@ impl ActorCode for Actor { Self::update_network_kpi(rt, param.map(|v| v.0))?; Ok(RawBytes::default()) } - None => Err(actor_error!(ErrUnhandledMessage, "Invalid method")), + None => Err(actor_error!(unhandled_message, "Invalid method")), } } } diff --git a/actors/runtime/src/actor_error.rs b/actors/runtime/src/actor_error.rs index 23dc656c7..81932673e 100644 --- a/actors/runtime/src/actor_error.rs +++ b/actors/runtime/src/actor_error.rs @@ -15,36 +15,37 @@ pub struct ActorError { impl ActorError { /// Creates a new ActorError. This method does not check that the code is in the /// range of valid actor abort codes. - pub fn new_unchecked(code: ExitCode, msg: String) -> Self { + pub fn unchecked(code: ExitCode, msg: String) -> Self { Self { exit_code: code, msg } } - pub fn ErrIllegalArgument(msg: String) -> Self { + pub fn illegal_argument(msg: String) -> Self { Self { exit_code: ExitCode::USR_ILLEGAL_ARGUMENT, msg } } - pub fn ErrNotFound(msg: String) -> Self { + pub fn not_found(msg: String) -> Self { Self { exit_code: ExitCode::USR_NOT_FOUND, msg } } - pub fn ErrForbidden(msg: String) -> Self { + pub fn forbidden(msg: String) -> Self { Self { exit_code: ExitCode::USR_FORBIDDEN, msg } } - pub fn ErrInsufficientFunds(msg: String) -> Self { + pub fn insufficient_funds(msg: String) -> Self { Self { exit_code: ExitCode::USR_INSUFFICIENT_FUNDS, msg } } - pub fn ErrIllegalState(msg: String) -> Self { + pub fn illegal_state(msg: String) -> Self { Self { exit_code: ExitCode::USR_ILLEGAL_STATE, msg } } - pub fn ErrSerialization(msg: String) -> Self { + pub fn serialization(msg: String) -> Self { Self { exit_code: ExitCode::USR_SERIALIZATION, msg } } - pub fn ErrUnhandledMessage(msg: String) -> Self { + pub fn unhandled_message(msg: String) -> Self { Self { exit_code: ExitCode::USR_UNHANDLED_MESSAGE, msg } } - pub fn ErrUnspecified(msg: String) -> Self { + pub fn unspecified(msg: String) -> Self { Self { exit_code: ExitCode::USR_UNSPECIFIED, msg } } - pub fn ErrInternalSendAborted(msg: String) -> Self { - Self { exit_code: ExitCode::from(24), msg } // TODO use symbolic constant when it's defined. + pub fn internal_send_aborted(msg: String) -> Self { + // TODO use symbolic constant for USR_SEND_ABORTED when it's defined. + Self { exit_code: ExitCode::from(24), msg } } /// Returns the exit code of the error. @@ -89,14 +90,6 @@ impl From for ActorError { } } -/// Performs conversions from SyscallResult, whose error type is ExitCode, -/// to ActorErrors. This facilitates propagation. -// impl From for ActorError { -// fn from(e: ExitCode) -> Self { -// ActorError { exit_code: e, msg: "".to_string() } -// } -// } - /// Convenience macro for generating Actor Errors #[macro_export] macro_rules! actor_error { diff --git a/actors/runtime/src/runtime/actor_blockstore.rs b/actors/runtime/src/runtime/actor_blockstore.rs index 75d90e56c..497efd0bd 100644 --- a/actors/runtime/src/runtime/actor_blockstore.rs +++ b/actors/runtime/src/runtime/actor_blockstore.rs @@ -19,17 +19,16 @@ impl fvm_ipld_blockstore::Blockstore for ActorBlockstore { fn get(&self, cid: &Cid) -> Result>> { // If this fails, the _CID_ is invalid. I.e., we have a bug. fvm::ipld::get(cid).map(Some).map_err(|c| { - actor_error!(ErrIllegalState; "get failed with {:?} on CID '{}'", c, cid).into() + actor_error!(illegal_state; "get failed with {:?} on CID '{}'", c, cid).into() }) } fn put_keyed(&self, k: &Cid, block: &[u8]) -> Result<()> { let code = Code::try_from(k.hash().code()) - .map_err(|e| actor_error!(ErrSerialization, e.to_string()))?; + .map_err(|e| actor_error!(serialization, e.to_string()))?; let k2 = self.put(code, &Block::new(k.codec(), block))?; if k != &k2 { - Err(actor_error!(ErrSerialization; "put block with cid {} but has cid {}", k, k2) - .into()) + Err(actor_error!(serialization; "put block with cid {} but has cid {}", k, k2).into()) } else { Ok(()) } @@ -43,7 +42,7 @@ impl fvm_ipld_blockstore::Blockstore for ActorBlockstore { // codec at the moment. const SIZE: u32 = 32; let k = fvm::ipld::put(code.into(), SIZE, block.codec, block.data.as_ref()) - .map_err(|c| actor_error!(ErrIllegalState; "put failed with {:?}", c))?; + .map_err(|c| actor_error!(illegal_state; "put failed with {:?}", c))?; Ok(k) } } diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index 93667fd43..c1ad1e18a 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -60,7 +60,7 @@ impl FvmRuntime { fn assert_not_validated(&mut self) -> Result<(), ActorError> { if self.caller_validated { return Err(actor_error!( - ErrUnspecified, // FIXME is this the right one? + unspecified, // FIXME is this the right one? "Method must validate caller identity exactly once" )); } @@ -121,7 +121,7 @@ where if addresses.into_iter().any(|a| *a == caller_addr) { Ok(()) } else { - return Err(actor_error!(ErrForbidden; + return Err(actor_error!(forbidden; "caller {} is not one of supported", caller_addr )); } @@ -140,7 +140,7 @@ where match self.resolve_builtin_actor_type(&caller_cid) { Some(typ) if types.into_iter().any(|t| *t == typ) => Ok(()), - _ => Err(actor_error!(ErrForbidden; + _ => Err(actor_error!(forbidden; "caller cid type {} not one of supported", caller_cid)), } } @@ -179,7 +179,7 @@ where // unexpected bad value to the syscall). fvm::rand::get_chain_randomness(personalization, rand_epoch, entropy).map_err(|e| match e { ErrorNumber::LimitExceeded => { - actor_error!(ErrIllegalArgument; "randomness lookback exceeded: {}", e) + actor_error!(illegal_argument; "randomness lookback exceeded: {}", e) } e => panic!("get chain randomness failed with an unexpected error: {}", e), }) @@ -195,7 +195,7 @@ where fvm::rand::get_beacon_randomness(personalization, rand_epoch, entropy).map_err( |e| match e { ErrorNumber::LimitExceeded => { - actor_error!(ErrIllegalArgument; "randomness lookback exceeded: {}", e) + actor_error!(illegal_argument; "randomness lookback exceeded: {}", e) } e => panic!("get chain randomness failed with an unexpected error: {}", e), }, @@ -206,11 +206,11 @@ where let root = fvm::sself::root()?; if root != *EMPTY_ARR_CID { return Err( - actor_error!(ErrIllegalState; "failed to create state; expected empty array CID, got: {}", root), + actor_error!(illegal_state; "failed to create state; expected empty array CID, got: {}", root), ); } let new_root = ActorBlockstore.put_cbor(obj, Code::Blake2b256) - .map_err(|e| actor_error!(ErrIllegalArgument; "failed to write actor state during creation: {}", e.to_string()))?; + .map_err(|e| actor_error!(illegal_argument; "failed to write actor state during creation: {}", e.to_string()))?; fvm::sself::set_root(&new_root)?; Ok(()) } @@ -219,9 +219,7 @@ where let root = fvm::sself::root()?; Ok(ActorBlockstore .get_cbor(&root) - .map_err( - |_| actor_error!(ErrIllegalArgument; "failed to get actor for Readonly state"), - )? + .map_err(|_| actor_error!(illegal_argument; "failed to get actor for Readonly state"))? .expect("State does not exist for actor state root")) } @@ -231,13 +229,13 @@ where F: FnOnce(&mut C, &mut Self) -> Result, { let state_cid = fvm::sself::root() - .map_err(|_| actor_error!(ErrIllegalArgument; "failed to get actor root state CID"))?; + .map_err(|_| actor_error!(illegal_argument; "failed to get actor root state CID"))?; log::debug!("getting cid: {}", state_cid); let mut state = ActorBlockstore .get_cbor::(&state_cid) - .map_err(|_| actor_error!(ErrIllegalArgument; "failed to get actor state"))? + .map_err(|_| actor_error!(illegal_argument; "failed to get actor state"))? .expect("State does not exist for actor state root"); self.in_transaction = true; @@ -246,7 +244,7 @@ where let ret = result?; let new_root = ActorBlockstore.put_cbor(&state, Code::Blake2b256) - .map_err(|e| actor_error!(ErrIllegalArgument; "failed to write actor state in transaction: {}", e.to_string()))?; + .map_err(|e| actor_error!(illegal_argument; "failed to write actor state in transaction: {}", e.to_string()))?; fvm::sself::set_root(&new_root)?; Ok(ret) } @@ -263,7 +261,7 @@ where value: TokenAmount, ) -> Result { if self.in_transaction { - return Err(actor_error!(ErrUnspecified; "runtime.send() is not allowed")); + return Err(actor_error!(unspecified; "runtime.send() is not allowed")); } match fvm::send::send(&to, method, params, value) { Ok(ret) => { @@ -271,7 +269,7 @@ where Ok(ret.return_data) } else { // The returned code can't be simply propagated as it may be a system exit code. - Err(ActorError::ErrInternalSendAborted(format!( + Err(ActorError::internal_send_aborted(format!( "send to {} method {} aborted with code {}", to, method, ret.exit_code ))) @@ -284,7 +282,7 @@ where // How do we know the receiver is what triggered this? // An error number doesn't carry enough information at this level // above the raw syscall (and even then). - actor_error!(ErrNotFound; "receiver not found") + actor_error!(not_found; "receiver not found") } ErrorNumber::InsufficientFunds => { // Actually this is more like an illegal argument where the caller attempted @@ -292,10 +290,10 @@ where // token amount type. Yes, the caller doesn't have that amount, but if they'd // attempted to transfer a representable amount it would fail with // SYS_INSUFFICIENT_FUNDS instead, so this difference is wierd. - actor_error!(ErrInsufficientFunds; "not enough funds") + actor_error!(insufficient_funds; "not enough funds") } err => { - actor_error!(ErrUnspecified; "unexpected error: {}", err) + actor_error!(unspecified; "unexpected error: {}", err) } }), } @@ -308,7 +306,7 @@ where fn create_actor(&mut self, code_id: Cid, actor_id: ActorID) -> Result<(), ActorError> { fvm::actor::create_actor(actor_id, &code_id).map_err(|e| match e { ErrorNumber::IllegalArgument => { - ActorError::ErrIllegalArgument("failed to create actor".into()) + ActorError::illegal_argument("failed to create actor".into()) } _ => panic!("create failed with unknown error: {}", e), }) diff --git a/actors/runtime/src/runtime/mod.rs b/actors/runtime/src/runtime/mod.rs index eb38b229b..b5402acde 100644 --- a/actors/runtime/src/runtime/mod.rs +++ b/actors/runtime/src/runtime/mod.rs @@ -21,8 +21,8 @@ use fvm_shared::version::NetworkVersion; use fvm_shared::{ActorID, MethodNum}; pub use self::actor_code::*; -use crate::{ActorError}; pub use self::policy::*; +use crate::ActorError; mod actor_code; diff --git a/actors/runtime/src/test_utils.rs b/actors/runtime/src/test_utils.rs index 047762c6e..f215707ed 100644 --- a/actors/runtime/src/test_utils.rs +++ b/actors/runtime/src/test_utils.rs @@ -841,7 +841,7 @@ impl Runtime for MockRuntime { match expected_msg.exit_code { ExitCode::OK => Ok(expected_msg.send_return), - x => Err(ActorError::new_unchecked(x, "Expected message Fail".to_string())), + x => Err(ActorError::unchecked(x, "Expected message Fail".to_string())), } } @@ -965,51 +965,64 @@ impl Syscalls for MockRuntime { ) -> anyhow::Result { let exp = self.expectations.borrow_mut().expect_compute_unsealed_sector_cid.take().ok_or_else( - || actor_error!(ErrIllegalState; "Unexpected syscall to ComputeUnsealedSectorCID"), + || actor_error!(illegal_state; "Unexpected syscall to ComputeUnsealedSectorCID"), )?; if exp.reg != reg { - return Err(anyhow!(actor_error!(ErrIllegalState; + return Err(anyhow!(actor_error!(illegal_state; "Unexpected compute_unsealed_sector_cid : reg mismatch" ))); } if exp.pieces[..].eq(pieces) { - return Err(anyhow!(actor_error!(ErrIllegalState; + return Err(anyhow!(actor_error!(illegal_state; "Unexpected compute_unsealed_sector_cid : pieces mismatch" ))); } if exp.exit_code != ExitCode::OK { - return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); + return Err(anyhow!(ActorError::unchecked( + exp.exit_code, + "Expected Failure".to_string(), + ))); } Ok(exp.cid) } fn verify_seal(&self, seal: &SealVerifyInfo) -> anyhow::Result<()> { - let exp = - self.expectations.borrow_mut().expect_verify_seal.take().ok_or_else( - || actor_error!(ErrIllegalState; "Unexpected syscall to verify seal"), - )?; + let exp = self + .expectations + .borrow_mut() + .expect_verify_seal + .take() + .ok_or_else(|| actor_error!(illegal_state; "Unexpected syscall to verify seal"))?; if exp.seal != *seal { - return Err(anyhow!(actor_error!(ErrIllegalState; "Unexpected seal verification"),)); + return Err(anyhow!(actor_error!(illegal_state; "Unexpected seal verification"),)); } if exp.exit_code != ExitCode::OK { - return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); + return Err(anyhow!(ActorError::unchecked( + exp.exit_code, + "Expected Failure".to_string(), + ))); } Ok(()) } fn verify_post(&self, post: &WindowPoStVerifyInfo) -> anyhow::Result<()> { - let exp = - self.expectations.borrow_mut().expect_verify_post.take().ok_or_else( - || actor_error!(ErrIllegalState; "Unexpected syscall to verify PoSt"), - )?; + let exp = self + .expectations + .borrow_mut() + .expect_verify_post + .take() + .ok_or_else(|| actor_error!(illegal_state; "Unexpected syscall to verify PoSt"))?; if exp.post != *post { - return Err(anyhow!(actor_error!(ErrIllegalState; "Unexpected PoSt verification"),)); + return Err(anyhow!(actor_error!(illegal_state; "Unexpected PoSt verification"),)); } if exp.exit_code != ExitCode::OK { - return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); + return Err(anyhow!(ActorError::unchecked( + exp.exit_code, + "Expected Failure".to_string(), + ))); } Ok(()) } @@ -1020,21 +1033,24 @@ impl Syscalls for MockRuntime { extra: &[u8], ) -> anyhow::Result> { let exp = self.expectations.borrow_mut().expect_verify_consensus_fault.take().ok_or_else( - || actor_error!(ErrIllegalState; "Unexpected syscall to verify_consensus_fault"), + || actor_error!(illegal_state; "Unexpected syscall to verify_consensus_fault"), )?; if exp.require_correct_input { if exp.block_header_1 != h1 { - return Err(anyhow!(actor_error!(ErrIllegalState; "Header 1 mismatch"))); + return Err(anyhow!(actor_error!(illegal_state; "Header 1 mismatch"))); } if exp.block_header_2 != h2 { - return Err(anyhow!(actor_error!(ErrIllegalState; "Header 2 mismatch"))); + return Err(anyhow!(actor_error!(illegal_state; "Header 2 mismatch"))); } if exp.block_header_extra != extra { - return Err(anyhow!(actor_error!(ErrIllegalState; "Header extra mismatch"),)); + return Err(anyhow!(actor_error!(illegal_state; "Header extra mismatch"),)); } } if exp.exit_code != ExitCode::OK { - return Err(anyhow!(ActorError::new_unchecked(exp.exit_code, "Expected Failure".to_string(),))); + return Err(anyhow!(ActorError::unchecked( + exp.exit_code, + "Expected Failure".to_string(), + ))); } Ok(exp.fault) } diff --git a/actors/runtime/src/util/cbor.rs b/actors/runtime/src/util/cbor.rs index a2f38e8d3..0e3522fda 100644 --- a/actors/runtime/src/util/cbor.rs +++ b/actors/runtime/src/util/cbor.rs @@ -1,7 +1,7 @@ use fvm_ipld_encoding::{to_vec, RawBytes}; use serde::{de, ser}; -use crate::{ActorError}; +use crate::ActorError; /// Serializes a structure as a CBOR vector of bytes, returning a serialization error on failure. /// `desc` is a noun phrase for the object being serialized, included in any error message. @@ -9,9 +9,8 @@ pub fn serialize_vec(value: &T, desc: &str) -> Result, ActorError> where T: ser::Serialize + ?Sized, { - to_vec(value).map_err(|e| { - ActorError::ErrSerialization(format!("failed to serialize {}: {}", desc, e)) - }) + to_vec(value) + .map_err(|e| ActorError::serialization(format!("failed to serialize {}: {}", desc, e))) } /// Serializes a structure as CBOR bytes, returning a serialization error on failure. @@ -26,9 +25,8 @@ where /// Deserialises CBOR-encoded bytes as a structure, returning a serialization error on failure. /// `desc` is a noun phrase for the object being deserialized, included in any error message. pub fn deserialize(v: &RawBytes, desc: &str) -> Result { - v.deserialize().map_err(|e| { - ActorError::ErrSerialization(format!("failed to deserialize {}: {}", desc, e)) - }) + v.deserialize() + .map_err(|e| ActorError::serialization(format!("failed to deserialize {}: {}", desc, e))) } /// Deserialises CBOR-encoded bytes as a method parameters object. diff --git a/actors/runtime/src/util/chaos/mod.rs b/actors/runtime/src/util/chaos/mod.rs index b6cab6dca..986443ec7 100644 --- a/actors/runtime/src/util/chaos/mod.rs +++ b/actors/runtime/src/util/chaos/mod.rs @@ -164,7 +164,7 @@ impl Actor { Ok(()) }), - _ => Err(actor_error!(ErrIllegalArgument; "Invalid mutate state command given" )), + _ => Err(actor_error!(illegal_argument; "Invalid mutate state command given" )), } } @@ -172,7 +172,7 @@ impl Actor { if arg.uncontrolled { panic!("Uncontrolled abort/error"); } - Err(ActorError::new_unchecked(arg.code, arg.message)) + Err(ActorError::unchecked(arg.code, arg.message)) } pub fn inspect_runtime(rt: &mut RT) -> Result @@ -246,7 +246,7 @@ impl ActorCode for Actor { Ok(RawBytes::serialize(inspect)?) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/runtime/src/util/downcast.rs b/actors/runtime/src/util/downcast.rs index 7e0652fa9..2b8b1d621 100644 --- a/actors/runtime/src/util/downcast.rs +++ b/actors/runtime/src/util/downcast.rs @@ -7,7 +7,7 @@ use fvm_ipld_encoding::Error as EncodingError; use fvm_ipld_hamt::Error as HamtError; use fvm_shared::error::ExitCode; -use crate::{ActorError}; +use crate::ActorError; /// Trait to allow multiple error types to be able to be downcasted into an `ActorError`. pub trait ActorDowncast { @@ -24,7 +24,7 @@ impl ActorDowncast for anyhow::Error { match downcast_util(self) { Ok(actor_error) => actor_error.wrap(msg), Err(other) => { - ActorError::new_unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)) + ActorError::unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)) } } } @@ -40,7 +40,9 @@ impl ActorDowncast for AmtError { fn downcast_default(self, default_exit_code: ExitCode, msg: impl AsRef) -> ActorError { match self { AmtError::Dynamic(e) => e.downcast_default(default_exit_code, msg), - other => ActorError::new_unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)), + other => { + ActorError::unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)) + } } } fn downcast_wrap(self, msg: impl AsRef) -> anyhow::Error { @@ -55,7 +57,9 @@ impl ActorDowncast for HamtError { fn downcast_default(self, default_exit_code: ExitCode, msg: impl AsRef) -> ActorError { match self { HamtError::Dynamic(e) => e.downcast_default(default_exit_code, msg), - other => ActorError::new_unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)), + other => { + ActorError::unchecked(default_exit_code, format!("{}: {}", msg.as_ref(), other)) + } } } fn downcast_wrap(self, msg: impl AsRef) -> anyhow::Error { @@ -79,7 +83,7 @@ fn downcast_util(error: anyhow::Error) -> anyhow::Result { // Check if error is Encoding error, if so return `ErrSerialization` let error = match error.downcast::() { Ok(enc_error) => { - return Ok(ActorError::new_unchecked(ExitCode::USR_SERIALIZATION, enc_error.to_string())) + return Ok(ActorError::unchecked(ExitCode::USR_SERIALIZATION, enc_error.to_string())) } Err(other) => other, }; diff --git a/actors/system/src/lib.rs b/actors/system/src/lib.rs index 490a182f0..025f2e7cf 100644 --- a/actors/system/src/lib.rs +++ b/actors/system/src/lib.rs @@ -84,7 +84,7 @@ impl ActorCode for Actor { Self::constructor(rt)?; Ok(RawBytes::default()) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/verifreg/src/lib.rs b/actors/verifreg/src/lib.rs index 976003a44..5b3e87878 100644 --- a/actors/verifreg/src/lib.rs +++ b/actors/verifreg/src/lib.rs @@ -53,7 +53,7 @@ impl Actor { // root should be an ID address let id_addr = rt .resolve_address(&root_key) - .ok_or_else(|| actor_error!(ErrIllegalArgument, "root should be an ID address"))?; + .ok_or_else(|| actor_error!(illegal_argument, "root should be an ID address"))?; let st = State::new(rt.store(), id_addr).map_err(|e| { e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "Failed to create verifreg state") @@ -70,7 +70,7 @@ impl Actor { { if ¶ms.allowance < &MINIMUM_VERIFIED_DEAL_SIZE { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "Allowance {} below minimum deal size for add verifier {}", params.allowance, params.address @@ -88,7 +88,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&st.root_key))?; if verifier == st.root_key { - return Err(actor_error!(ErrIllegalArgument, "Rootkey cannot be added as verifier")); + return Err(actor_error!(illegal_argument, "Rootkey cannot be added as verifier")); } rt.transaction(|st: &mut State, rt| { @@ -117,7 +117,7 @@ impl Actor { })?; if found { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "verified client {} cannot become a verifier", verifier )); @@ -166,7 +166,7 @@ impl Actor { e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to remove verifier") })? .ok_or_else(|| { - actor_error!(ErrIllegalArgument, "failed to remove verifier: not found") + actor_error!(illegal_argument, "failed to remove verifier: not found") })?; st.verifiers = verifiers.flush().map_err(|e| { @@ -191,7 +191,7 @@ impl Actor { if params.allowance < *MINIMUM_VERIFIED_DEAL_SIZE { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "Allowance {} below MinVerifiedDealSize for add verified client {}", params.allowance, params.address @@ -207,7 +207,7 @@ impl Actor { let st: State = rt.state()?; if client == st.root_key { - return Err(actor_error!(ErrIllegalArgument, "Rootkey cannot be added as verifier")); + return Err(actor_error!(illegal_argument, "Rootkey cannot be added as verifier")); } rt.transaction(|st: &mut State, rt| { @@ -222,7 +222,10 @@ impl Actor { let mut verified_clients = make_map_with_root_and_bitwidth(&st.verified_clients, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to load verified clients", + ) })?; // Validate caller is one of the verifiers. @@ -235,9 +238,7 @@ impl Actor { format!("failed to get Verifier {}", verifier), ) })? - .ok_or_else(|| { - actor_error!(ErrNotFound, format!("no such Verifier {}", verifier)) - })?; + .ok_or_else(|| actor_error!(not_found, format!("no such Verifier {}", verifier)))?; // Validate client to be added isn't a verifier let found = verifiers.contains_key(&client.to_bytes()).map_err(|e| { @@ -245,7 +246,7 @@ impl Actor { })?; if found { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "verifier {} cannot be added as a verified client", client )); @@ -254,7 +255,7 @@ impl Actor { // Compute new verifier cap and update. if verifier_cap < ¶ms.allowance { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "Add more DataCap {} for VerifiedClient than allocated {}", params.allowance, verifier_cap @@ -327,7 +328,7 @@ impl Actor { if params.deal_size < *MINIMUM_VERIFIED_DEAL_SIZE { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "Verified Dealsize {} is below minimum in usedbytes", params.deal_size )); @@ -337,7 +338,10 @@ impl Actor { let mut verified_clients = make_map_with_root_and_bitwidth(&st.verified_clients, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to load verified clients", + ) })?; let BigIntDe(vc_cap) = verified_clients @@ -348,10 +352,10 @@ impl Actor { format!("failed to get verified client {}", &client), ) })? - .ok_or_else(|| actor_error!(ErrNotFound, "no such verified client {}", client))?; + .ok_or_else(|| actor_error!(not_found, "no such verified client {}", client))?; if vc_cap.is_negative() { return Err(actor_error!( - ErrIllegalState, + illegal_state, "negative cap for client {}: {}", client, vc_cap @@ -360,7 +364,7 @@ impl Actor { if ¶ms.deal_size > vc_cap { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "Deal size of {} is greater than verifier_cap {} for verified client {}", params.deal_size, vc_cap, @@ -382,7 +386,7 @@ impl Actor { })? .ok_or_else(|| { actor_error!( - ErrIllegalState, + illegal_state, "Failed to delete verified client {}: not found", client ) @@ -417,7 +421,7 @@ impl Actor { rt.validate_immediate_caller_is(std::iter::once(&*STORAGE_MARKET_ACTOR_ADDR))?; if params.deal_size < *MINIMUM_VERIFIED_DEAL_SIZE { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "Below minimum VerifiedDealSize requested in RestoreBytes: {}", params.deal_size )); @@ -432,14 +436,17 @@ impl Actor { let st: State = rt.state()?; if client == st.root_key { - return Err(actor_error!(ErrIllegalArgument, "Cannot restore allowance for Rootkey")); + return Err(actor_error!(illegal_argument, "Cannot restore allowance for Rootkey")); } rt.transaction(|st: &mut State, rt| { let mut verified_clients = make_map_with_root_and_bitwidth(&st.verified_clients, rt.store(), HAMT_BIT_WIDTH) .map_err(|e| { - e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load verified clients") + e.downcast_default( + ExitCode::USR_ILLEGAL_STATE, + "failed to load verified clients", + ) })?; let verifiers = make_map_with_root_and_bitwidth::<_, BigIntDe>( &st.verifiers, @@ -456,7 +463,7 @@ impl Actor { })?; if found { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "cannot restore allowance for a verifier {}", client )); @@ -535,7 +542,7 @@ impl Actor { if verifier_1 == verifier_2 { return Err(actor_error!( - ErrIllegalArgument, + illegal_argument, "need two different verifiers to send remove datacap request" )); } @@ -556,7 +563,7 @@ impl Actor { // check that `client` is currently a verified client if !is_verifier(rt, st, client)? { - return Err(actor_error!(ErrNotFound, "{} is not a verified client", client)); + return Err(actor_error!(not_found, "{} is not a verified client", client)); } // get existing cap allocated to client @@ -573,12 +580,12 @@ impl Actor { // check that `verifier_1` is currently a verified client if !is_verifier(rt, st, verifier_1)? { - return Err(actor_error!(ErrNotFound, "{} is not a verified client", verifier_1)); + return Err(actor_error!(not_found, "{} is not a verified client", verifier_1)); } // check that `verifier_2` is currently a verified client if !is_verifier(rt, st, verifier_2)? { - return Err(actor_error!(ErrNotFound, "{} is not a verified client", verifier_2)); + return Err(actor_error!(not_found, "{} is not a verified client", verifier_2)); } // validate signatures @@ -637,14 +644,14 @@ impl Actor { st.remove_data_cap_proposal_ids = proposal_ids.flush().map_err(|e| { actor_error! { - ErrIllegalState, + illegal_state, "failed to flush proposal ids: {}", e } })?; st.verified_clients = verified_clients.flush().map_err(|e| { actor_error! { - ErrIllegalState, + illegal_state, "failed to flush verified clients: {}", e } @@ -693,7 +700,7 @@ where let maybe_id = proposal_ids.get(&key.to_bytes()).map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to get proposal id for verifier {} and client {}: {}", verifier, client, @@ -710,7 +717,7 @@ where let next_id = RemoveDataCapProposalID(curr_id.0 + 1); proposal_ids.set(BytesKey::from(key.to_bytes()), next_id.clone()).map_err(|e| { actor_error!( - ErrIllegalState, + illegal_state, "failed to update proposal id for verifier {} and client {}: {}", verifier, client, @@ -740,13 +747,13 @@ where let b = RawBytes::serialize(proposal).map_err(|e| { actor_error!( - ErrSerialization; "failed to marshal remove datacap request: {}", e) + serialization; "failed to marshal remove datacap request: {}", e) })?; // verify signature of proposal - rt.verify_signature(&request.signature, &request.verifier, &b).map_err(|e|{ - actor_error!(ErrIllegalArgument; "invalid signature for datacap removal request: {}", e) - }) + rt.verify_signature(&request.signature, &request.verifier, &b).map_err( + |e| actor_error!(illegal_argument; "invalid signature for datacap removal request: {}", e), + ) } impl ActorCode for Actor { @@ -788,7 +795,7 @@ impl ActorCode for Actor { Self::remove_verified_client_data_cap(rt, cbor::deserialize_params(params)?)?; Ok(RawBytes::default()) } - None => Err(actor_error!(ErrUnhandledMessage; "Invalid method")), + None => Err(actor_error!(unhandled_message; "Invalid method")), } } } diff --git a/actors/verifreg/tests/verifreg_actor_test.rs b/actors/verifreg/tests/verifreg_actor_test.rs index cd37116ae..e887ffde0 100644 --- a/actors/verifreg/tests/verifreg_actor_test.rs +++ b/actors/verifreg/tests/verifreg_actor_test.rs @@ -101,7 +101,10 @@ mod verifiers { fn add_verifier_enforces_min_size() { let (h, mut rt) = new_harness(); let allowance = MINIMUM_VERIFIED_DEAL_SIZE.clone() - 1; - expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.add_verifier(&mut rt, &VERIFIER, &allowance)); + expect_abort( + ExitCode::USR_ILLEGAL_ARGUMENT, + h.add_verifier(&mut rt, &VERIFIER, &allowance), + ); h.check_state(); } @@ -699,7 +702,10 @@ mod datacap { let (h, mut rt) = new_harness(); h.add_verifier(&mut rt, &VERIFIER, &VERIFIER_ALLOWANCE).unwrap(); let deal_size = MINIMUM_VERIFIED_DEAL_SIZE.clone(); - expect_abort(ExitCode::USR_ILLEGAL_ARGUMENT, h.restore_bytes(&mut rt, &VERIFIER, &deal_size)); + expect_abort( + ExitCode::USR_ILLEGAL_ARGUMENT, + h.restore_bytes(&mut rt, &VERIFIER, &deal_size), + ); h.check_state() } } From 0e99acc13710606588d24a5c71da8ee215338ce3 Mon Sep 17 00:00:00 2001 From: anorth <445306+anorth@users.noreply.github.com> Date: Wed, 6 Apr 2022 21:43:09 +1000 Subject: [PATCH 03/10] last bits --- actors/init/tests/init_actor_test.rs | 2 +- actors/market/tests/market_actor_test.rs | 2 +- actors/miner/tests/miner_actor_test_wpost.rs | 2 +- actors/multisig/tests/multisig_actor_test.rs | 6 +++--- actors/paych/tests/paych_actor_test.rs | 12 ++++++------ actors/reward/tests/reward_actor_test.rs | 2 +- actors/runtime/src/test_utils.rs | 20 ++++++++++---------- actors/verifreg/tests/verifreg_actor_test.rs | 14 +++++++------- 8 files changed, 30 insertions(+), 30 deletions(-) diff --git a/actors/init/tests/init_actor_test.rs b/actors/init/tests/init_actor_test.rs index 18be9d29f..9a0bf7134 100644 --- a/actors/init/tests/init_actor_test.rs +++ b/actors/init/tests/init_actor_test.rs @@ -36,7 +36,7 @@ fn abort_cant_call_exec() { let err = exec_and_verify(&mut rt, *POWER_ACTOR_CODE_ID, &"").expect_err("Exec should have failed"); - assert_eq!(err.exit_code(), ExitCode::ErrForbidden); + assert_eq!(err.exit_code(), ExitCode::USR_FORBIDDEN); } #[test] diff --git a/actors/market/tests/market_actor_test.rs b/actors/market/tests/market_actor_test.rs index c32c10a5e..6592e4d00 100644 --- a/actors/market/tests/market_actor_test.rs +++ b/actors/market/tests/market_actor_test.rs @@ -225,7 +225,7 @@ fn account_actor_check() { rt.set_caller(*MINER_ACTOR_CODE_ID, provider_addr); assert_eq!( - ExitCode::ErrForbidden, + ExitCode::USR_FORBIDDEN, rt.call::( Method::AddBalance as u64, &RawBytes::serialize(provider_addr).unwrap(), diff --git a/actors/miner/tests/miner_actor_test_wpost.rs b/actors/miner/tests/miner_actor_test_wpost.rs index 087b94271..1d7a60b53 100644 --- a/actors/miner/tests/miner_actor_test_wpost.rs +++ b/actors/miner/tests/miner_actor_test_wpost.rs @@ -205,7 +205,7 @@ fn invalid_submissions() { params, PoStConfig::empty(), ); - expect_abort_contains_message(ExitCode::ErrNotFound, "no such partition", result); + expect_abort_contains_message(ExitCode::USR_NOT_FOUND, "no such partition", result); rt.reset(); } diff --git a/actors/multisig/tests/multisig_actor_test.rs b/actors/multisig/tests/multisig_actor_test.rs index c61a40972..ba6f85a1f 100644 --- a/actors/multisig/tests/multisig_actor_test.rs +++ b/actors/multisig/tests/multisig_actor_test.rs @@ -160,7 +160,7 @@ fn test_add_signer() { increase: false, expect_signers: vec![anne, bob, chuck], expect_approvals: 3, - code: ExitCode::ErrForbidden, + code: ExitCode::USR_FORBIDDEN, }, TestCase{ desc: "fail to add signer with ID address that already exists even thugh we only have non ID address as approver", @@ -171,7 +171,7 @@ fn test_add_signer() { increase:false, expect_signers: vec![anne, bob, chuck], expect_approvals: 3, - code: ExitCode::ErrForbidden, + code: ExitCode::USR_FORBIDDEN, }, TestCase{ desc: "fail to add signer with ID address that already exists even thugh we only have non ID address as approver", @@ -182,7 +182,7 @@ fn test_add_signer() { increase:false, expect_signers: vec![anne, bob, chuck], expect_approvals: 3, - code: ExitCode::ErrForbidden, + code: ExitCode::USR_FORBIDDEN, } ]; diff --git a/actors/paych/tests/paych_actor_test.rs b/actors/paych/tests/paych_actor_test.rs index 5d560af23..b4b20b257 100644 --- a/actors/paych/tests/paych_actor_test.rs +++ b/actors/paych/tests/paych_actor_test.rs @@ -128,7 +128,7 @@ mod paych_constructor { caller_code: *INIT_ACTOR_CODE_ID, new_actor_code: *MULTISIG_ACTOR_CODE_ID, payer_code: *ACCOUNT_ACTOR_CODE_ID, - expected_exit_code: ExitCode::ErrForbidden, + expected_exit_code: ExitCode::USR_FORBIDDEN, }]; for test_case in test_cases { @@ -637,12 +637,12 @@ mod update_channel_state_extra { #[test] #[ignore = "old functionality -- test framework needs to be updated"] fn extra_call_fail() { - let (mut rt, sv) = construct_runtime(ExitCode::ErrPlaceholder); + let (mut rt, sv) = construct_runtime(ExitCode::USR_UNSPECIFIED); expect_error( &mut rt, Method::UpdateChannelState as u64, &RawBytes::serialize(UpdateChannelStateParams::from(sv)).unwrap(), - ExitCode::ErrPlaceholder, + ExitCode::USR_UNSPECIFIED, ); rt.verify(); } @@ -876,13 +876,13 @@ mod actor_collect { TestCase { dont_settle: true, exp_send_to: ExitCode::OK, - exp_collect_exit: ExitCode::ErrForbidden, + exp_collect_exit: ExitCode::USR_FORBIDDEN, }, // fails if Failed to send funds to `To` TestCase { dont_settle: false, - exp_send_to: ExitCode::ErrPlaceholder, - exp_collect_exit: ExitCode::ErrPlaceholder, + exp_send_to: ExitCode::USR_UNSPECIFIED, + exp_collect_exit: ExitCode::USR_UNSPECIFIED, }, ]; diff --git a/actors/reward/tests/reward_actor_test.rs b/actors/reward/tests/reward_actor_test.rs index 161dfe4ac..9f26e3669 100644 --- a/actors/reward/tests/reward_actor_test.rs +++ b/actors/reward/tests/reward_actor_test.rs @@ -254,7 +254,7 @@ mod test_award_block_reward { RawBytes::serialize(BigIntSer(&expected_reward)).unwrap(), expected_reward.clone(), RawBytes::default(), - ExitCode::ErrForbidden, + ExitCode::USR_FORBIDDEN, ); rt.expect_send( *BURNT_FUNDS_ACTOR_ADDR, diff --git a/actors/runtime/src/test_utils.rs b/actors/runtime/src/test_utils.rs index f215707ed..798d0067f 100644 --- a/actors/runtime/src/test_utils.rs +++ b/actors/runtime/src/test_utils.rs @@ -637,7 +637,7 @@ impl Runtime for MockRuntime { } } expectations.expect_validate_caller_addr = None; - return Err(actor_error!(SysErrForbidden; + return Err(actor_error!(forbidden; "caller address {:?} forbidden, allowed: {:?}", self.message().caller(), &addrs )); @@ -677,7 +677,7 @@ impl Runtime for MockRuntime { self.expectations.borrow_mut().expect_validate_caller_type = None; - Err(actor_error!(SysErrForbidden; "caller type {:?} forbidden, allowed: {:?}", + Err(actor_error!(forbidden; "caller type {:?} forbidden, allowed: {:?}", self.caller_type, types)) } @@ -769,7 +769,7 @@ impl Runtime for MockRuntime { fn create(&mut self, obj: &C) -> Result<(), ActorError> { if self.state.is_some() { - return Err(actor_error!(SysErrIllegalActor; "state already constructed")); + return Err(actor_error!(illegal_state; "state already constructed")); } self.state = Some(self.store.put_cbor(obj, Code::Blake2b256).unwrap()); Ok(()) @@ -785,7 +785,7 @@ impl Runtime for MockRuntime { F: FnOnce(&mut C, &mut Self) -> Result, { if self.in_transaction { - return Err(actor_error!(SysErrIllegalActor; "nested transaction")); + return Err(actor_error!(unspecified; "nested transaction")); } let mut read_only = self.state()?; self.in_transaction = true; @@ -810,7 +810,7 @@ impl Runtime for MockRuntime { ) -> Result { self.require_in_call(); if self.in_transaction { - return Err(actor_error!(SysErrIllegalActor; "side-effect within transaction")); + return Err(actor_error!(unspecified; "side-effect within transaction")); } assert!( @@ -831,9 +831,9 @@ impl Runtime for MockRuntime { { let mut balance = self.balance.borrow_mut(); if value > *balance { - return Err(actor_error!(SysErrSenderStateInvalid; - "cannot send value: {:?} exceeds balance: {:?}", - value, *balance + return Err(ActorError::unchecked( + ExitCode::SYS_SENDER_STATE_INVALID, + format!("cannot send value: {:?} exceeds balance: {:?}", value, *balance), )); } *balance -= value; @@ -855,7 +855,7 @@ impl Runtime for MockRuntime { fn create_actor(&mut self, code_id: Cid, actor_id: ActorID) -> Result<(), ActorError> { self.require_in_call(); if self.in_transaction { - return Err(actor_error!(SysErrIllegalActor; "side-effect within transaction")); + return Err(actor_error!(unspecified; "side-effect within transaction")); } let expect_create_actor = self .expectations @@ -871,7 +871,7 @@ impl Runtime for MockRuntime { fn delete_actor(&mut self, addr: &Address) -> Result<(), ActorError> { self.require_in_call(); if self.in_transaction { - return Err(actor_error!(SysErrIllegalActor; "side-effect within transaction")); + return Err(actor_error!(unspecified; "side-effect within transaction")); } let exp_act = self.expectations.borrow_mut().expect_delete_actor.take(); if exp_act.is_none() { diff --git a/actors/verifreg/tests/verifreg_actor_test.rs b/actors/verifreg/tests/verifreg_actor_test.rs index e887ffde0..0737e6290 100644 --- a/actors/verifreg/tests/verifreg_actor_test.rs +++ b/actors/verifreg/tests/verifreg_actor_test.rs @@ -88,7 +88,7 @@ mod verifiers { allowance: VERIFIER_ALLOWANCE.clone(), }; expect_abort( - ExitCode::SysErrForbidden, + ExitCode::USR_FORBIDDEN, rt.call::( Method::AddVerifier as MethodNum, &RawBytes::serialize(params).unwrap(), @@ -183,7 +183,7 @@ mod verifiers { rt.set_caller(*ACCOUNT_ACTOR_CODE_ID, caller); assert_ne!(h.root, caller); expect_abort( - ExitCode::SysErrForbidden, + ExitCode::USR_FORBIDDEN, rt.call::( Method::RemoveVerifier as MethodNum, &RawBytes::serialize(*VERIFIER).unwrap(), @@ -355,7 +355,7 @@ mod clients { let params = AddVerifierClientParams { address: *CLIENT, allowance: CLIENT_ALLOWANCE.clone() }; expect_abort( - ExitCode::ErrNotFound, + ExitCode::USR_NOT_FOUND, rt.call::( Method::AddVerifiedClient as MethodNum, &RawBytes::serialize(params).unwrap(), @@ -495,7 +495,7 @@ mod datacap { // Use full allowance. h.use_bytes(&mut rt, &CLIENT, &allowance).unwrap(); // Fail to use any more because client was removed. - expect_abort(ExitCode::ErrNotFound, h.use_bytes(&mut rt, &CLIENT, &allowance)); + expect_abort(ExitCode::USR_NOT_FOUND, h.use_bytes(&mut rt, &CLIENT, &allowance)); h.check_state() } @@ -507,7 +507,7 @@ mod datacap { let params = UseBytesParams { address: *CLIENT, deal_size: MINIMUM_VERIFIED_DEAL_SIZE.clone() }; expect_abort( - ExitCode::SysErrForbidden, + ExitCode::USR_FORBIDDEN, rt.call::( Method::UseBytes as MethodNum, &RawBytes::serialize(params).unwrap(), @@ -536,7 +536,7 @@ mod datacap { fn consume_requires_client_exists() { let (h, mut rt) = new_harness(); expect_abort( - ExitCode::ErrNotFound, + ExitCode::USR_NOT_FOUND, h.use_bytes(&mut rt, &CLIENT, &MINIMUM_VERIFIED_DEAL_SIZE), ); h.check_state() @@ -661,7 +661,7 @@ mod datacap { let params = RestoreBytesParams { address: *CLIENT, deal_size: MINIMUM_VERIFIED_DEAL_SIZE.clone() }; expect_abort( - ExitCode::SysErrForbidden, + ExitCode::USR_FORBIDDEN, rt.call::( Method::RestoreBytes as MethodNum, &RawBytes::serialize(params).unwrap(), From 7d21cb37976bc0274a5519e94df2cc4d9481f7fd Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Fri, 8 Apr 2022 11:49:09 +0200 Subject: [PATCH 04/10] use new ErrAssertionFailed exit code --- actors/runtime/src/actor_error.rs | 4 ++-- actors/runtime/src/runtime/fvm.rs | 16 ++++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/actors/runtime/src/actor_error.rs b/actors/runtime/src/actor_error.rs index 81932673e..c7a3949d8 100644 --- a/actors/runtime/src/actor_error.rs +++ b/actors/runtime/src/actor_error.rs @@ -43,8 +43,8 @@ impl ActorError { pub fn unspecified(msg: String) -> Self { Self { exit_code: ExitCode::USR_UNSPECIFIED, msg } } - pub fn internal_send_aborted(msg: String) -> Self { - // TODO use symbolic constant for USR_SEND_ABORTED when it's defined. + pub fn user_assertion_failed(msg: String) -> Self { + // TODO: use symbolic constant for ErrAssertionFailed when it's defined. Self { exit_code: ExitCode::from(24), msg } } diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index c1ad1e18a..b922504bf 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -60,7 +60,7 @@ impl FvmRuntime { fn assert_not_validated(&mut self) -> Result<(), ActorError> { if self.caller_validated { return Err(actor_error!( - unspecified, // FIXME is this the right one? + user_assertion_failed, "Method must validate caller identity exactly once" )); } @@ -261,7 +261,7 @@ where value: TokenAmount, ) -> Result { if self.in_transaction { - return Err(actor_error!(unspecified; "runtime.send() is not allowed")); + return Err(actor_error!(user_assertion_failed; "runtime.send() is not allowed")); } match fvm::send::send(&to, method, params, value) { Ok(ret) => { @@ -269,10 +269,14 @@ where Ok(ret.return_data) } else { // The returned code can't be simply propagated as it may be a system exit code. - Err(ActorError::internal_send_aborted(format!( - "send to {} method {} aborted with code {}", - to, method, ret.exit_code - ))) + // TODO: improve propagation once we return a RuntimeError. + Err(actor_error!( + user_assertion_failed, + format!( + "send to {} method {} aborted with code {}", + to, method, ret.exit_code + ) + )) } } Err(err) => Err(match err { From 338323e7a38de2ec7dce8051bd1890a087690f8c Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Fri, 8 Apr 2022 11:58:38 +0200 Subject: [PATCH 05/10] use git dependency --- Cargo.lock | 7 +++++++ Cargo.toml | 26 ++++++++++++++++++-------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 64fadc877..c8de71ee9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -927,6 +927,7 @@ dependencies = [ [[package]] name = "fvm_ipld_amt" version = "0.4.0" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "ahash", "anyhow", @@ -942,6 +943,7 @@ dependencies = [ [[package]] name = "fvm_ipld_bitfield" version = "0.5.0" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "cs_serde_bytes", "fvm_ipld_encoding", @@ -953,6 +955,7 @@ dependencies = [ [[package]] name = "fvm_ipld_blockstore" version = "0.1.0" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "anyhow", "cid", @@ -975,6 +978,7 @@ dependencies = [ [[package]] name = "fvm_ipld_encoding" version = "0.1.0" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "anyhow", "cid", @@ -990,6 +994,7 @@ dependencies = [ [[package]] name = "fvm_ipld_hamt" version = "0.4.0" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "anyhow", "byteorder", @@ -1009,6 +1014,7 @@ dependencies = [ [[package]] name = "fvm_sdk" version = "0.4.0" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "cid", "fvm_ipld_encoding", @@ -1052,6 +1058,7 @@ dependencies = [ [[package]] name = "fvm_shared" version = "0.4.1" +source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" dependencies = [ "anyhow", "bimap", diff --git a/Cargo.toml b/Cargo.toml index 552230c38..e4f96ccf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,16 @@ members = [ "test_vm", ] +[patch.crates-io] +# Needed until a new release is published +fvm_shared = { git = "https://github.com/filecoin-project/ref-fvm" } +fvm_sdk = { git = "https://github.com/filecoin-project/ref-fvm" } +fvm_ipld_hamt = { git = "https://github.com/filecoin-project/ref-fvm" } +fvm_ipld_amt = { git = "https://github.com/filecoin-project/ref-fvm" } +fvm_ipld_bitfield = { git = "https://github.com/filecoin-project/ref-fvm" } +fvm_ipld_encoding = { git = "https://github.com/filecoin-project/ref-fvm" } +fvm_ipld_blockstore = { git = "https://github.com/filecoin-project/ref-fvm" } + ## Uncomment when working locally on ref-fvm and this repo simultaneously. ## Assumes the ref-fvm checkout is in a sibling directory with the same name. ## (Valid while FVM modules aren't published to crates.io) @@ -54,14 +64,14 @@ members = [ ## Uncomment entries below when working locally on ref-fvm and this repo simultaneously. ## Assumes the ref-fvm checkout is in a sibling directory with the same name. ## (Valid once FVM modules are published to crates.io) -[patch.crates-io] -fvm_shared = { path = "../ref-fvm/shared" } -fvm_sdk = { path = "../ref-fvm/sdk" } -fvm_ipld_hamt = { path = "../ref-fvm/ipld/hamt" } -fvm_ipld_amt = { path = "../ref-fvm/ipld/amt" } -fvm_ipld_bitfield = { path = "../ref-fvm/ipld/bitfield"} -fvm_ipld_encoding = { path = "../ref-fvm/ipld/encoding"} -fvm_ipld_blockstore = { path = "../ref-fvm/ipld/blockstore"} +# [patch.crates-io] +# fvm_shared = { path = "../ref-fvm/shared" } +# fvm_sdk = { path = "../ref-fvm/sdk" } +# fvm_ipld_hamt = { path = "../ref-fvm/ipld/hamt" } +# fvm_ipld_amt = { path = "../ref-fvm/ipld/amt" } +# fvm_ipld_bitfield = { path = "../ref-fvm/ipld/bitfield"} +# fvm_ipld_encoding = { path = "../ref-fvm/ipld/encoding"} +# fvm_ipld_blockstore = { path = "../ref-fvm/ipld/blockstore"} [profile.wasm] inherits = "release" From d718b1db48d9e287ac96165424836e96aa6a4d3d Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Fri, 8 Apr 2022 15:56:00 +0200 Subject: [PATCH 06/10] apply CR --- actors/runtime/src/actor_error.rs | 6 ++++-- actors/runtime/src/runtime/fvm.rs | 7 ++++--- actors/runtime/src/test_utils.rs | 8 ++++---- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/actors/runtime/src/actor_error.rs b/actors/runtime/src/actor_error.rs index c7a3949d8..4919883c5 100644 --- a/actors/runtime/src/actor_error.rs +++ b/actors/runtime/src/actor_error.rs @@ -12,6 +12,9 @@ pub struct ActorError { msg: String, } +// TODO: use symbolic constant for ErrAssertionFailed when it's defined. +pub const EXIT_CODE_ERR_ASSERTION_FAILED: ExitCode = ExitCode::new(24); + impl ActorError { /// Creates a new ActorError. This method does not check that the code is in the /// range of valid actor abort codes. @@ -44,8 +47,7 @@ impl ActorError { Self { exit_code: ExitCode::USR_UNSPECIFIED, msg } } pub fn user_assertion_failed(msg: String) -> Self { - // TODO: use symbolic constant for ErrAssertionFailed when it's defined. - Self { exit_code: ExitCode::from(24), msg } + Self { exit_code: EXIT_CODE_ERR_ASSERTION_FAILED, msg } } /// Returns the exit code of the error. diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index b922504bf..7660a27c5 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -11,7 +11,7 @@ use fvm_shared::clock::ChainEpoch; use fvm_shared::crypto::randomness::DomainSeparationTag; use fvm_shared::crypto::signature::Signature; use fvm_shared::econ::TokenAmount; -use fvm_shared::error::{ErrorNumber, ExitCode}; +use fvm_shared::error::ErrorNumber; use fvm_shared::piece::PieceInfo; use fvm_shared::randomness::Randomness; use fvm_shared::sector::{ @@ -23,7 +23,7 @@ use fvm_shared::{ActorID, MethodNum}; use crate::runtime::actor_blockstore::ActorBlockstore; use crate::runtime::{ActorCode, ConsensusFault, MessageInfo, Policy, RuntimePolicy, Syscalls}; -use crate::{actor_error, ActorError, Runtime}; +use crate::{actor_error, ActorError, Runtime, EXIT_CODE_ERR_ASSERTION_FAILED}; lazy_static! { /// Cid of the empty array Cbor bytes (`EMPTY_ARR_BYTES`). @@ -270,6 +270,7 @@ where } else { // The returned code can't be simply propagated as it may be a system exit code. // TODO: improve propagation once we return a RuntimeError. + // Ref https://github.com/filecoin-project/builtin-actors/issues/144 Err(actor_error!( user_assertion_failed, format!( @@ -448,7 +449,7 @@ pub fn trampoline(params: u32) -> u32 { // We do this after handling the error, because the actor may have encountered an error before // it even could validate the caller. if !rt.caller_validated { - fvm::vm::abort(ExitCode::USR_UNSPECIFIED.value(), Some("failed to validate caller")) + fvm::vm::abort(EXIT_CODE_ERR_ASSERTION_FAILED.value(), Some("failed to validate caller")) } // Then handle the return value. diff --git a/actors/runtime/src/test_utils.rs b/actors/runtime/src/test_utils.rs index 798d0067f..33c7ab002 100644 --- a/actors/runtime/src/test_utils.rs +++ b/actors/runtime/src/test_utils.rs @@ -785,7 +785,7 @@ impl Runtime for MockRuntime { F: FnOnce(&mut C, &mut Self) -> Result, { if self.in_transaction { - return Err(actor_error!(unspecified; "nested transaction")); + return Err(actor_error!(user_assertion_failed; "nested transaction")); } let mut read_only = self.state()?; self.in_transaction = true; @@ -810,7 +810,7 @@ impl Runtime for MockRuntime { ) -> Result { self.require_in_call(); if self.in_transaction { - return Err(actor_error!(unspecified; "side-effect within transaction")); + return Err(actor_error!(user_assertion_failed; "side-effect within transaction")); } assert!( @@ -855,7 +855,7 @@ impl Runtime for MockRuntime { fn create_actor(&mut self, code_id: Cid, actor_id: ActorID) -> Result<(), ActorError> { self.require_in_call(); if self.in_transaction { - return Err(actor_error!(unspecified; "side-effect within transaction")); + return Err(actor_error!(user_assertion_failed; "side-effect within transaction")); } let expect_create_actor = self .expectations @@ -871,7 +871,7 @@ impl Runtime for MockRuntime { fn delete_actor(&mut self, addr: &Address) -> Result<(), ActorError> { self.require_in_call(); if self.in_transaction { - return Err(actor_error!(unspecified; "side-effect within transaction")); + return Err(actor_error!(user_assertion_failed; "side-effect within transaction")); } let exp_act = self.expectations.borrow_mut().expect_delete_actor.take(); if exp_act.is_none() { From e805594a76044584c7c60309343bc534e92b8a3a Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 11 Apr 2022 11:43:09 +0200 Subject: [PATCH 07/10] chore: update fvm_shared & fvm_sdk --- Cargo.lock | 53 +++++++++++++++++++++----------------- Cargo.toml | 17 ++++++------ actors/account/Cargo.toml | 2 +- actors/cron/Cargo.toml | 2 +- actors/init/Cargo.toml | 2 +- actors/market/Cargo.toml | 2 +- actors/miner/Cargo.toml | 2 +- actors/multisig/Cargo.toml | 2 +- actors/paych/Cargo.toml | 2 +- actors/power/Cargo.toml | 2 +- actors/reward/Cargo.toml | 2 +- actors/runtime/Cargo.toml | 4 +-- actors/system/Cargo.toml | 2 +- actors/verifreg/Cargo.toml | 2 +- test_vm/Cargo.toml | 2 +- 15 files changed, 52 insertions(+), 46 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c8de71ee9..9cd164a09 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -550,7 +550,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "num-derive", "num-traits", "serde", @@ -581,7 +581,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "log", "num-derive", "num-traits", @@ -598,7 +598,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "log", "num-derive", "num-traits", @@ -618,7 +618,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "libipld-core", "log", "num-derive", @@ -643,7 +643,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "itertools", "lazy_static", "log", @@ -664,7 +664,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "indexmap", "integer-encoding", "num-derive", @@ -683,7 +683,7 @@ dependencies = [ "fvm_ipld_amt", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "num-derive", "num-traits", "serde", @@ -699,7 +699,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "indexmap", "integer-encoding", "lazy_static", @@ -716,7 +716,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "lazy_static", "log", "num-derive", @@ -732,7 +732,7 @@ dependencies = [ "fil_actors_runtime", "fvm_ipld_blockstore", "fvm_ipld_encoding", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "num-derive", "num-traits", "serde", @@ -748,7 +748,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "lazy_static", "num-derive", "num-traits", @@ -770,7 +770,7 @@ dependencies = [ "fvm_ipld_encoding", "fvm_ipld_hamt", "fvm_sdk", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "getrandom", "hex", "indexmap", @@ -927,7 +927,8 @@ dependencies = [ [[package]] name = "fvm_ipld_amt" version = "0.4.0" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3394e5f9c2adb4d586519bc24bbfd659366e01e7ffa6cda676be94a62bab474" dependencies = [ "ahash", "anyhow", @@ -943,7 +944,8 @@ dependencies = [ [[package]] name = "fvm_ipld_bitfield" version = "0.5.0" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9011349297962982b8ab2663c220034525ec0f95f408c2b561d3d98867f1a803" dependencies = [ "cs_serde_bytes", "fvm_ipld_encoding", @@ -955,7 +957,8 @@ dependencies = [ [[package]] name = "fvm_ipld_blockstore" version = "0.1.0" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1985eae58ec2fbf54535ce115c72a2141459fb7fb4ff7379e17bffae0e302578" dependencies = [ "anyhow", "cid", @@ -978,7 +981,8 @@ dependencies = [ [[package]] name = "fvm_ipld_encoding" version = "0.1.0" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43bd635987aac46a753ec81767713af35cb50f182c7cc49d3a429643ede0e709" dependencies = [ "anyhow", "cid", @@ -994,7 +998,8 @@ dependencies = [ [[package]] name = "fvm_ipld_hamt" version = "0.4.0" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a03c6ae361a882360bc0c0f47265b294429f096baa8d9467247bbd62c6a6683c" dependencies = [ "anyhow", "byteorder", @@ -1013,12 +1018,13 @@ dependencies = [ [[package]] name = "fvm_sdk" -version = "0.4.0" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1da3325e5885d985e9066d65d030ac2ea4cef9f173cf0bbd04c2caa366562700" dependencies = [ "cid", "fvm_ipld_encoding", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "lazy_static", "log", "num-traits", @@ -1057,8 +1063,9 @@ dependencies = [ [[package]] name = "fvm_shared" -version = "0.4.1" -source = "git+https://github.com/filecoin-project/ref-fvm#78530c8156332a7ab44d21ffdf42dd407b0ed2c7" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "295109128cf0ae81063f1e033e56e3aab858b93eeabe446f80beb34709955de2" dependencies = [ "anyhow", "bimap", @@ -1683,7 +1690,7 @@ dependencies = [ "fvm_ipld_blockstore", "fvm_ipld_encoding", "fvm_ipld_hamt", - "fvm_shared 0.4.1", + "fvm_shared 0.5.1", "indexmap", "log", "num-derive", diff --git a/Cargo.toml b/Cargo.toml index e4f96ccf3..74bdafd19 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,15 +39,14 @@ members = [ "test_vm", ] -[patch.crates-io] -# Needed until a new release is published -fvm_shared = { git = "https://github.com/filecoin-project/ref-fvm" } -fvm_sdk = { git = "https://github.com/filecoin-project/ref-fvm" } -fvm_ipld_hamt = { git = "https://github.com/filecoin-project/ref-fvm" } -fvm_ipld_amt = { git = "https://github.com/filecoin-project/ref-fvm" } -fvm_ipld_bitfield = { git = "https://github.com/filecoin-project/ref-fvm" } -fvm_ipld_encoding = { git = "https://github.com/filecoin-project/ref-fvm" } -fvm_ipld_blockstore = { git = "https://github.com/filecoin-project/ref-fvm" } +#[patch.crates-io] +#fvm_shared = { git = "https://github.com/filecoin-project/ref-fvm" } +#fvm_sdk = { git = "https://github.com/filecoin-project/ref-fvm" } +#fvm_ipld_hamt = { git = "https://github.com/filecoin-project/ref-fvm" } +#fvm_ipld_amt = { git = "https://github.com/filecoin-project/ref-fvm" } +#fvm_ipld_bitfield = { git = "https://github.com/filecoin-project/ref-fvm" } +#fvm_ipld_encoding = { git = "https://github.com/filecoin-project/ref-fvm" } +#fvm_ipld_blockstore = { git = "https://github.com/filecoin-project/ref-fvm" } ## Uncomment when working locally on ref-fvm and this repo simultaneously. ## Assumes the ref-fvm checkout is in a sibling directory with the same name. diff --git a/actors/account/Cargo.toml b/actors/account/Cargo.toml index efd0bee10..29c530b7b 100644 --- a/actors/account/Cargo.toml +++ b/actors/account/Cargo.toml @@ -14,7 +14,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/cron/Cargo.toml b/actors/cron/Cargo.toml index 3df75a4f4..e261a02e1 100644 --- a/actors/cron/Cargo.toml +++ b/actors/cron/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" log = "0.4.14" diff --git a/actors/init/Cargo.toml b/actors/init/Cargo.toml index ea6412be2..bf99549a7 100644 --- a/actors/init/Cargo.toml +++ b/actors/init/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_hamt = "0.4.0" serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" diff --git a/actors/market/Cargo.toml b/actors/market/Cargo.toml index f355c2c51..78a49d488 100644 --- a/actors/market/Cargo.toml +++ b/actors/market/Cargo.toml @@ -16,7 +16,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } fvm_ipld_hamt = "0.4.0" -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_bitfield = "0.5.0" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/miner/Cargo.toml b/actors/miner/Cargo.toml index af6546ce0..121f8dcff 100644 --- a/actors/miner/Cargo.toml +++ b/actors/miner/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_bitfield = "0.5.0" fvm_ipld_amt = { version = "0.4.0", features = ["go-interop"] } fvm_ipld_hamt = "0.4.0" diff --git a/actors/multisig/Cargo.toml b/actors/multisig/Cargo.toml index d32cdbda7..132e5dc25 100644 --- a/actors/multisig/Cargo.toml +++ b/actors/multisig/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_hamt = "0.4.0" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/paych/Cargo.toml b/actors/paych/Cargo.toml index c017a922e..f9caad329 100644 --- a/actors/paych/Cargo.toml +++ b/actors/paych/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" serde = { version = "1.0.136", features = ["derive"] } diff --git a/actors/power/Cargo.toml b/actors/power/Cargo.toml index 6cf29ee3e..85d1e837e 100644 --- a/actors/power/Cargo.toml +++ b/actors/power/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_hamt = "0.4.0" num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/actors/reward/Cargo.toml b/actors/reward/Cargo.toml index 61b7ef2e3..7c2d02238 100644 --- a/actors/reward/Cargo.toml +++ b/actors/reward/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" log = "0.4.14" diff --git a/actors/runtime/Cargo.toml b/actors/runtime/Cargo.toml index 03f1b722a..234dcaf03 100644 --- a/actors/runtime/Cargo.toml +++ b/actors/runtime/Cargo.toml @@ -10,7 +10,7 @@ repository = "https://github.com/filecoin-project/builtin-actors" [dependencies] fvm_ipld_hamt = "0.4.0" fvm_ipld_amt = { version = "0.4.0", features = ["go-interop"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } num-traits = "0.2.14" num-derive = "0.3.3" serde = { version = "1.0.136", features = ["derive"] } @@ -27,7 +27,7 @@ thiserror = "1.0.30" getrandom = { version = "0.2.5", features = ["js"] } hex = { version = "0.4.3", optional = true } anyhow = "1.0.56" -fvm_sdk = { version = "0.4.0", optional = true } +fvm_sdk = { version = "0.5.0", optional = true } blake2b_simd = "1.0" fvm_ipld_blockstore = { version = "0.1" } fvm_ipld_encoding = "0.1.0" diff --git a/actors/system/Cargo.toml b/actors/system/Cargo.toml index f7d0346aa..59a19a67a 100644 --- a/actors/system/Cargo.toml +++ b/actors/system/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_encoding = "0.1.0" fvm_ipld_blockstore = { version = "0.1.0" } num-traits = "0.2.14" diff --git a/actors/verifreg/Cargo.toml b/actors/verifreg/Cargo.toml index 8bea62878..b483af0f2 100644 --- a/actors/verifreg/Cargo.toml +++ b/actors/verifreg/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "lib"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../runtime", features = ["fil-actor"] } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } serde = { version = "1.0.136", features = ["derive"] } num-traits = "0.2.14" num-derive = "0.3.3" diff --git a/test_vm/Cargo.toml b/test_vm/Cargo.toml index 23962500d..9708efcc0 100644 --- a/test_vm/Cargo.toml +++ b/test_vm/Cargo.toml @@ -11,7 +11,7 @@ keywords = ["filecoin", "web3", "wasm"] [dependencies] fil_actors_runtime = { version = "8.0.0-alpha.1", path = "../actors/runtime" } -fvm_shared = { version = "0.4.1", default-features = false } +fvm_shared = { version = "0.5.1", default-features = false } fvm_ipld_encoding = { version = "0.1.0", default-features = false } fvm_ipld_blockstore = { version = "0.1.0", default-features = false } fvm_ipld_hamt = "0.4.0" From 6e420798b9095084b181290beff56732ad63d95b Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 11 Apr 2022 14:56:49 +0200 Subject: [PATCH 08/10] chore: use upstream assertion failed exit code --- actors/runtime/src/actor_error.rs | 5 +---- actors/runtime/src/runtime/fvm.rs | 6 +++--- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/actors/runtime/src/actor_error.rs b/actors/runtime/src/actor_error.rs index 4919883c5..ba80e4ffc 100644 --- a/actors/runtime/src/actor_error.rs +++ b/actors/runtime/src/actor_error.rs @@ -12,9 +12,6 @@ pub struct ActorError { msg: String, } -// TODO: use symbolic constant for ErrAssertionFailed when it's defined. -pub const EXIT_CODE_ERR_ASSERTION_FAILED: ExitCode = ExitCode::new(24); - impl ActorError { /// Creates a new ActorError. This method does not check that the code is in the /// range of valid actor abort codes. @@ -47,7 +44,7 @@ impl ActorError { Self { exit_code: ExitCode::USR_UNSPECIFIED, msg } } pub fn user_assertion_failed(msg: String) -> Self { - Self { exit_code: EXIT_CODE_ERR_ASSERTION_FAILED, msg } + Self { exit_code: ExitCode::USR_ASSERTION_FAILED, msg } } /// Returns the exit code of the error. diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index 7660a27c5..b99116e56 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -11,7 +11,7 @@ use fvm_shared::clock::ChainEpoch; use fvm_shared::crypto::randomness::DomainSeparationTag; use fvm_shared::crypto::signature::Signature; use fvm_shared::econ::TokenAmount; -use fvm_shared::error::ErrorNumber; +use fvm_shared::error::{ErrorNumber, ExitCode}; use fvm_shared::piece::PieceInfo; use fvm_shared::randomness::Randomness; use fvm_shared::sector::{ @@ -23,7 +23,7 @@ use fvm_shared::{ActorID, MethodNum}; use crate::runtime::actor_blockstore::ActorBlockstore; use crate::runtime::{ActorCode, ConsensusFault, MessageInfo, Policy, RuntimePolicy, Syscalls}; -use crate::{actor_error, ActorError, Runtime, EXIT_CODE_ERR_ASSERTION_FAILED}; +use crate::{actor_error, ActorError, Runtime}; lazy_static! { /// Cid of the empty array Cbor bytes (`EMPTY_ARR_BYTES`). @@ -449,7 +449,7 @@ pub fn trampoline(params: u32) -> u32 { // We do this after handling the error, because the actor may have encountered an error before // it even could validate the caller. if !rt.caller_validated { - fvm::vm::abort(EXIT_CODE_ERR_ASSERTION_FAILED.value(), Some("failed to validate caller")) + fvm::vm::abort(ExitCode::USR_ASSERTION_FAILED.value(), Some("failed to validate caller")) } // Then handle the return value. From fde84c5ccfc30a542d94d80bb74429198006e68e Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 11 Apr 2022 15:13:19 +0200 Subject: [PATCH 09/10] fix: propagate non-system exit codes in send The real fix is discussed in #144, but this version is strictly "more correct" than the previous code. --- actors/runtime/src/runtime/fvm.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index b99116e56..33ac127da 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -271,12 +271,23 @@ where // The returned code can't be simply propagated as it may be a system exit code. // TODO: improve propagation once we return a RuntimeError. // Ref https://github.com/filecoin-project/builtin-actors/issues/144 - Err(actor_error!( - user_assertion_failed, + let exit_code = match ret.exit_code { + // This means the called actor did something wrong. We can't "make up" a + // reasonable exit code. + ExitCode::SYS_MISSING_RETURN + | ExitCode::SYS_ILLEGAL_INSTRUCTION + | ExitCode::SYS_ILLEGAL_EXIT_CODE => ExitCode::USR_UNSPECIFIED, + // We don't expect any other system errors. + code if code.is_system_error() => ExitCode::USR_ASSERTION_FAILED, + // Otherwise, pass it through. + code => code, + }; + Err(ActorError::unchecked( + exit_code, format!( "send to {} method {} aborted with code {}", to, method, ret.exit_code - ) + ), )) } } From 0093286083cfb4d01b8cfb9e70b580da484ee9ba Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Mon, 11 Apr 2022 15:43:34 +0200 Subject: [PATCH 10/10] fix: improve send exit codes & comments Many of these are temporary (waiting on #144), but this is as correct as we can get it for now. --- actors/runtime/src/runtime/fvm.rs | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/actors/runtime/src/runtime/fvm.rs b/actors/runtime/src/runtime/fvm.rs index 33ac127da..5685bae3d 100644 --- a/actors/runtime/src/runtime/fvm.rs +++ b/actors/runtime/src/runtime/fvm.rs @@ -295,21 +295,24 @@ where // Some of these errors are from operations in the Runtime or SDK layer // before or after the underlying VM send syscall. ErrorNumber::NotFound => { - // How do we know the receiver is what triggered this? - // An error number doesn't carry enough information at this level - // above the raw syscall (and even then). - actor_error!(not_found; "receiver not found") + // This means that the receiving actor doesn't exist. + // TODO: we can't reasonably determine the correct "exit code" here. + actor_error!(unspecified; "receiver not found") } ErrorNumber::InsufficientFunds => { - // Actually this is more like an illegal argument where the caller attempted - // to transfer an amount larger than that representable by the VM's - // token amount type. Yes, the caller doesn't have that amount, but if they'd - // attempted to transfer a representable amount it would fail with - // SYS_INSUFFICIENT_FUNDS instead, so this difference is wierd. + // This means that the send failed because we have insufficient funds. We will + // get a _syscall error_, not an exit code, because the target actor will not + // run (and therefore will not exit). actor_error!(insufficient_funds; "not enough funds") } + ErrorNumber::LimitExceeded => { + // This means we've exceeded the recursion limit. + // TODO: Define a better exit code. + actor_error!(user_assertion_failed; "recursion limit exceeded") + } err => { - actor_error!(unspecified; "unexpected error: {}", err) + // We don't expect any other syscall exit codes. + actor_error!(user_assertion_failed; "unexpected error: {}", err) } }), } @@ -456,7 +459,7 @@ pub fn trampoline(params: u32) -> u32 { let ret = C::invoke_method(&mut rt, method, ¶ms) .unwrap_or_else(|err| fvm::vm::abort(err.exit_code().value(), Some(err.msg()))); - // Abort with "unspecified" if the actor failed to validate the caller somewhere. + // Abort with "assertion failed" if the actor failed to validate the caller somewhere. // We do this after handling the error, because the actor may have encountered an error before // it even could validate the caller. if !rt.caller_validated {