From 9147619a107f272bc5d21c4452f09cc00b649ce0 Mon Sep 17 00:00:00 2001 From: turuslan Date: Thu, 9 Nov 2023 23:34:40 +0300 Subject: [PATCH 1/2] qtils error Signed-off-by: turuslan --- CMakeLists.txt | 2 + cmake/Hunter/config.cmake | 4 +- cmake/Hunter/hunter-gate-url.cmake | 4 +- cmake/dependencies.cmake | 3 + core/api/jrpc/decode_args.hpp | 2 +- core/api/jrpc/jrpc_method.hpp | 4 +- core/api/jrpc/jrpc_server_impl.cpp | 2 +- core/api/jrpc/jrpc_server_impl.hpp | 1 + .../service/author/impl/author_api_impl.cpp | 8 +- .../api/service/chain/impl/chain_api_impl.cpp | 4 +- .../internal/impl/internal_api_impl.cpp | 2 +- core/api/service/jrpc_fn.hpp | 2 +- .../api/service/state/impl/state_api_impl.cpp | 6 +- core/api/transport/error.hpp | 2 +- core/api/transport/impl/ws/ws_session.cpp | 3 +- .../impl/app_configuration_impl.cpp | 8 +- core/application/impl/chain_spec_impl.cpp | 12 +- core/application/impl/chain_spec_impl.hpp | 2 +- core/application/impl/util.cpp | 12 +- core/application/impl/util.hpp | 2 + core/authority_discovery/query/query_impl.cpp | 12 +- core/authority_discovery/query/query_impl.hpp | 1 + core/authorship/impl/block_builder_error.hpp | 2 +- core/authorship/impl/block_builder_impl.cpp | 11 +- core/authorship/impl/proposer_impl.cpp | 6 +- core/benchmark/block_execution_benchmark.cpp | 63 +++--- core/blockchain/block_storage_error.hpp | 2 +- core/blockchain/block_tree_error.hpp | 2 +- .../impl/block_header_repository_impl.cpp | 4 +- core/blockchain/impl/block_storage_impl.cpp | 6 +- core/blockchain/impl/block_tree_impl.cpp | 56 +++--- core/common/blob.hpp | 4 +- core/common/hexutil.cpp | 8 +- core/common/hexutil.hpp | 10 +- core/common/tagged.hpp | 8 +- core/consensus/babe/impl/babe.cpp | 22 +- .../babe/impl/babe_config_repository_impl.cpp | 8 +- .../consensus/babe/impl/babe_digests_util.cpp | 12 +- core/consensus/babe/impl/babe_error.hpp | 2 +- .../grandpa/authority_manager_error.hpp | 2 +- .../grandpa/impl/authority_manager_impl.cpp | 12 +- .../grandpa/impl/environment_impl.cpp | 4 +- core/consensus/grandpa/impl/grandpa_impl.cpp | 17 +- .../grandpa/impl/voting_round_impl.cpp | 42 ++-- .../grandpa/vote_graph/vote_graph_error.hpp | 2 +- .../grandpa/vote_graph/vote_graph_impl.cpp | 4 +- core/consensus/grandpa/voter_set.cpp | 6 +- core/consensus/grandpa/voting_round_error.hpp | 2 +- .../timeline/impl/block_addition_error.hpp | 2 +- .../timeline/impl/block_appender_base.cpp | 5 +- .../timeline/impl/block_executor_impl.cpp | 14 +- .../impl/block_header_appender_impl.cpp | 12 +- .../timeline/impl/block_production_error.hpp | 2 +- .../timeline/impl/slots_util_impl.cpp | 2 +- .../timeline/impl/timeline_error.hpp | 2 +- .../consensus/timeline/impl/timeline_impl.cpp | 8 +- .../validation/babe_block_validator.cpp | 6 +- core/crypto/bip39/dictionary.cpp | 2 +- core/crypto/bip39/dictionary.hpp | 1 + core/crypto/bip39/entropy_accumulator.cpp | 8 +- core/crypto/bip39/entropy_accumulator.hpp | 1 + .../crypto/bip39/impl/bip39_provider_impl.cpp | 2 +- core/crypto/bip39/mnemonic.cpp | 2 +- .../crypto/crypto_store/crypto_store_impl.cpp | 10 +- core/crypto/crypto_store/key_file_storage.cpp | 16 +- core/crypto/ecdsa/ecdsa_provider_impl.cpp | 10 +- core/crypto/ed25519/ed25519_provider_impl.cpp | 6 +- .../pbkdf2/impl/pbkdf2_provider_impl.cpp | 2 +- .../secp256k1/secp256k1_provider_impl.cpp | 10 +- core/crypto/sr25519/sr25519_provider_impl.cpp | 6 +- core/dispute_coordinator/impl/batches.cpp | 2 +- .../impl/dispute_coordinator_impl.cpp | 61 +++--- core/dispute_coordinator/impl/errors.hpp | 2 +- .../impl/rolling_session_window_impl.cpp | 10 +- .../dispute_coordinator/impl/runtime_info.cpp | 2 +- .../participation/impl/queues_impl.cpp | 12 +- core/host_api/impl/CMakeLists.txt | 2 - .../host_api/impl/child_storage_extension.cpp | 2 +- core/host_api/impl/crypto_extension.cpp | 20 +- core/host_api/impl/storage_extension.cpp | 14 +- core/injector/application_injector.cpp | 14 +- core/injector/get_peer_keypair.hpp | 6 +- core/log/formatters/boost_ec.hpp | 15 ++ core/log/logger.cpp | 2 +- core/metrics/impl/metrics_watcher.cpp | 4 +- core/metrics/impl/session_impl.cpp | 2 +- core/network/adapters/adapter_errors.hpp | 2 +- core/network/adapters/light.hpp | 4 +- .../adapters/protobuf_block_request.hpp | 8 +- .../adapters/protobuf_block_response.hpp | 4 +- .../adapters/protobuf_state_request.hpp | 4 +- .../adapters/protobuf_state_response.hpp | 2 +- core/network/adapters/uvar.hpp | 4 +- core/network/beefy/beefy.cpp | 5 +- core/network/beefy/protocol.cpp | 2 +- core/network/helpers/message_read_writer.hpp | 4 +- .../helpers/scale_message_read_writer.hpp | 4 +- core/network/impl/peer_manager_impl.cpp | 4 +- .../protocols/block_announce_protocol.cpp | 2 +- .../impl/protocols/protocol_base_impl.hpp | 2 +- .../network/impl/protocols/protocol_error.hpp | 2 +- .../protocol_fetch_available_data.hpp | 2 +- .../impl/protocols/protocol_fetch_chunk.hpp | 2 +- .../impl/protocols/protocol_req_pov.cpp | 2 +- .../protocols/request_response_protocol.hpp | 10 +- .../impl/protocols/state_protocol_impl.cpp | 10 +- .../impl/protocols/sync_protocol_impl.cpp | 30 +-- .../impl/state_protocol_observer_impl.cpp | 15 +- core/network/impl/state_sync_request_flow.cpp | 2 +- core/network/impl/stream_engine.cpp | 4 +- .../impl/sync_protocol_observer_impl.cpp | 9 +- core/network/impl/synchronizer_impl.cpp | 55 ++--- .../network/notifications/wait_read_close.hpp | 4 +- core/network/types/block_attributes.hpp | 145 ++----------- core/network/types/blocks_request.hpp | 4 - core/network/warp/cache.cpp | 4 +- core/offchain/impl/http_request.cpp | 2 + core/offchain/impl/offchain_worker_impl.cpp | 2 +- core/offchain/types.hpp | 6 - core/outcome/outcome.hpp | 8 +- core/parachain/approval/approval.cpp | 4 +- .../approval/approval_distribution.cpp | 41 ++-- .../availability/bitfield/store_impl.cpp | 2 +- core/parachain/availability/chunks.hpp | 55 ++--- .../availability/erasure_coding_error.cpp | 4 +- .../availability/erasure_coding_error.hpp | 2 +- core/parachain/availability/proof.hpp | 4 +- .../availability/recovery/recovery_impl.cpp | 2 +- core/parachain/pvf/pvf_impl.cpp | 20 +- .../impl/parachain_observer_impl.cpp | 4 +- .../validator/impl/parachain_processor.cpp | 34 ++-- core/primitives/arithmetic_error.hpp | 3 +- core/primitives/inherent_data.hpp | 4 +- core/primitives/ss58_codec.cpp | 4 +- core/primitives/token_error.hpp | 3 +- core/primitives/transaction_validity.hpp | 5 - .../binaryen/binaryen_memory_provider.cpp | 2 +- core/runtime/binaryen/module/module_impl.cpp | 4 +- .../binaryen/module/module_instance_impl.cpp | 8 +- core/runtime/common/module_instance.cpp | 4 +- .../common/runtime_transaction_error.hpp | 2 +- .../common/runtime_upgrade_tracker_impl.cpp | 2 +- .../common/trie_storage_provider_impl.cpp | 8 +- .../common/uncompress_code_if_needed.cpp | 6 +- core/runtime/executor.hpp | 29 ++- core/runtime/runtime_api/impl/beefy.cpp | 2 +- .../impl/transaction_payment_api.cpp | 2 +- core/runtime/wavm/module_instance.cpp | 8 +- core/scale/libp2p_types.cpp | 3 - core/storage/database_error.hpp | 2 +- core/storage/in_memory/in_memory_storage.cpp | 2 +- core/storage/rocksdb/rocksdb.cpp | 22 +- core/storage/rocksdb/rocksdb_batch.cpp | 4 +- core/storage/trie/compact_decode.cpp | 4 +- core/storage/trie/compact_encode.cpp | 13 +- .../trie/impl/topper_trie_batch_impl.cpp | 19 +- .../trie/polkadot_trie/polkadot_trie.hpp | 2 +- .../polkadot_trie_cursor_impl.cpp | 14 +- .../polkadot_trie_cursor_impl.hpp | 2 +- .../trie/polkadot_trie/polkadot_trie_impl.cpp | 6 +- .../storage/trie/polkadot_trie/trie_error.hpp | 2 +- .../trie/serialization/polkadot_codec.cpp | 41 ++-- .../trie_pruner/impl/trie_pruner_impl.cpp | 10 +- core/telemetry/impl/connection_impl.cpp | 2 + .../impl/transaction_pool_impl.cpp | 10 +- .../transaction_pool_error.hpp | 2 +- core/utils/benchmark_main.cpp | 5 +- core/utils/kagome_db_editor.cpp | 2 +- test/core/api/client/http_client.cpp | 8 +- test/core/api/client/http_client.hpp | 2 + test/core/api/client/ws_client.cpp | 8 +- test/core/api/client/ws_client.hpp | 1 + .../api/service/author/author_api_test.cpp | 5 +- .../core/api/service/chain/chain_api_test.cpp | 5 +- .../core/api/service/state/state_api_test.cpp | 16 +- .../authorship/block_builder_factory_test.cpp | 2 +- test/core/authorship/block_builder_test.cpp | 2 +- test/core/authorship/proposer_test.cpp | 19 +- test/core/blockchain/block_storage_test.cpp | 14 +- test/core/blockchain/block_tree_test.cpp | 21 +- .../grandpa/authority_manager_test.cpp | 2 +- .../timeline/block_executor_test.cpp | 4 +- .../core/consensus/timeline/timeline_test.cpp | 2 +- .../validation/block_validator_test.cpp | 42 ++-- .../crypto/crypto_store/crypto_store_test.cpp | 15 +- test/core/host_api/CMakeLists.txt | 2 +- .../host_api/child_storage_extension_test.cpp | 10 +- test/core/host_api/crypto_extension_test.cpp | 8 +- .../core/host_api/offchain_extension_test.cpp | 2 +- test/core/host_api/storage_extension_test.cpp | 2 +- test/core/network/rpc_libp2p_test.cpp | 8 +- .../network/sync_protocol_observer_test.cpp | 4 +- test/core/network/synchronizer_test.cpp | 4 +- .../network/types/block_attributes_test.cpp | 8 +- .../network/types/block_direction_test.cpp | 8 +- .../types/message_read_writer_test.cpp | 2 +- .../types/protobuf_block_request_test.cpp | 3 +- test/core/storage/rocksdb/rocksdb_fs_test.cpp | 7 +- .../rocksdb/rocksdb_integration_test.cpp | 6 +- .../trie/polkadot_trie/polkadot_trie_test.cpp | 9 +- .../polkadot_codec_node_encoding_test.cpp | 2 +- .../trie/trie_storage/trie_batch_test.cpp | 2 +- .../storage/trie_pruner/trie_pruner_test.cpp | 6 +- .../transaction_pool_test.cpp | 15 +- test/deps/CMakeLists.txt | 8 - test/deps/outcome_test.cpp | 184 ----------------- .../api/transport/jrpc_processor_stub.hpp | 2 +- test/testutil/outcome.hpp | 190 +++--------------- test/testutil/outcome/dummy_error.hpp | 2 +- test/testutil/storage/base_rocksdb_test.cpp | 4 - 210 files changed, 820 insertions(+), 1364 deletions(-) create mode 100644 core/log/formatters/boost_ec.hpp delete mode 100644 test/deps/outcome_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c972e7ee05..1ab0de36d6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,8 @@ cmake_minimum_required(VERSION 3.12) +cmake_policy(SET CMP0144 NEW) + find_program(CCACHE_FOUND ccache) if(CCACHE_FOUND) set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) diff --git a/cmake/Hunter/config.cmake b/cmake/Hunter/config.cmake index e3e3c9d48c..5a5504317e 100644 --- a/cmake/Hunter/config.cmake +++ b/cmake/Hunter/config.cmake @@ -40,7 +40,7 @@ hunter_config( hunter_config( libp2p - VERSION 0.1.17 + VERSION 0.1.17-qtils KEEP_PACKAGE_SOURCES ) @@ -66,7 +66,7 @@ hunter_config( hunter_config( scale - VERSION 1.1.0 + VERSION 1.1.0-qtils KEEP_PACKAGE_SOURCES ) diff --git a/cmake/Hunter/hunter-gate-url.cmake b/cmake/Hunter/hunter-gate-url.cmake index 14ea3c1954..14b32649dc 100644 --- a/cmake/Hunter/hunter-gate-url.cmake +++ b/cmake/Hunter/hunter-gate-url.cmake @@ -1,5 +1,5 @@ HunterGate( - URL https://github.com/qdrvm/hunter/archive/refs/tags/v0.23.257-qdrvm11.tar.gz - SHA1 b2a69ae501bdc99006fb86e55930640004468556 + URL https://github.com/qdrvm/hunter/archive/refs/heads/turuslan/qtils.zip + SHA1 219b754308ac6bab96ece8b560cd84c5a10323db LOCAL ) diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index ece0afc3bd..c5732e3328 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -16,6 +16,9 @@ endif() hunter_add_package(Boost COMPONENTS random filesystem program_options date_time) find_package(Boost CONFIG REQUIRED random filesystem program_options date_time) +hunter_add_package(qtils) +find_package(qtils CONFIG REQUIRED) + # https://docs.hunter.sh/en/latest/packages/pkg/xxhash.html hunter_add_package(xxhash) find_package(xxhash CONFIG REQUIRED) diff --git a/core/api/jrpc/decode_args.hpp b/core/api/jrpc/decode_args.hpp index cec2f78c6f..79c8de4929 100644 --- a/core/api/jrpc/decode_args.hpp +++ b/core/api/jrpc/decode_args.hpp @@ -25,7 +25,7 @@ namespace kagome::api::details { if (r) { return std::move(r.value()); } - throw jsonrpc::InvalidParametersFault{r.error().message()}; + throw jsonrpc::InvalidParametersFault{fmt::to_string(r.error())}; } static auto &mapAt(const jsonrpc::Value &j, const std::string &k) { diff --git a/core/api/jrpc/jrpc_method.hpp b/core/api/jrpc/jrpc_method.hpp index a62915030b..c85ffc5dc6 100644 --- a/core/api/jrpc/jrpc_method.hpp +++ b/core/api/jrpc/jrpc_method.hpp @@ -34,7 +34,7 @@ namespace kagome::api { // Init request if (auto &&init_result = request.init(params); not init_result) { - throw jsonrpc::Fault(init_result.error().message()); + throw jsonrpc::Fault(fmt::to_string(init_result.error())); } // Execute request @@ -42,7 +42,7 @@ namespace kagome::api { // Handle of failure if (not result) { - throw jsonrpc::Fault(result.error().message()); + throw jsonrpc::Fault(fmt::to_string(result.error())); } if constexpr (std::is_same_v) { diff --git a/core/api/jrpc/jrpc_server_impl.cpp b/core/api/jrpc/jrpc_server_impl.cpp index 43fb7f8f99..98b4ac5a54 100644 --- a/core/api/jrpc/jrpc_server_impl.cpp +++ b/core/api/jrpc/jrpc_server_impl.cpp @@ -80,7 +80,7 @@ namespace kagome::api { formatted_response->GetSize())); } catch (const Fault &ex) { - cb(outcome::failure(Error::JSON_FORMAT_FAILED)); + cb(Q_ERROR(Error::JSON_FORMAT_FAILED)); } metric_rpc_requests_count_->inc(); diff --git a/core/api/jrpc/jrpc_server_impl.hpp b/core/api/jrpc/jrpc_server_impl.hpp index 0bfa07b059..259df4ecc0 100644 --- a/core/api/jrpc/jrpc_server_impl.hpp +++ b/core/api/jrpc/jrpc_server_impl.hpp @@ -7,6 +7,7 @@ #pragma once #include +#include #include "api/jrpc/jrpc_server.hpp" #include "metrics/metrics.hpp" diff --git a/core/api/service/author/impl/author_api_impl.cpp b/core/api/service/author/impl/author_api_impl.cpp index cae39c3827..34ab093452 100644 --- a/core/api/service/author/impl/author_api_impl.cpp +++ b/core/api/service/author/impl/author_api_impl.cpp @@ -73,7 +73,7 @@ namespace kagome::api { } types.pop_back(); SL_INFO(logger_, "Unsupported key type, only [{}] are accepted", types); - return outcome::failure(crypto::CryptoStoreError::UNSUPPORTED_KEY_TYPE); + return Q_ERROR(crypto::CryptoStoreError::UNSUPPORTED_KEY_TYPE); }; if (crypto::KeyTypes::BABE == key_type_id or crypto::KeyTypes::AUTHORITY_DISCOVERY == key_type_id) { @@ -83,7 +83,7 @@ namespace kagome::api { OUTCOME_TRY(keypair, store_->generateSr25519Keypair(key_type_id, seed_typed)); if (public_key_typed != keypair.public_key) { - return outcome::failure(crypto::CryptoStoreError::WRONG_PUBLIC_KEY); + return Q_ERROR(crypto::CryptoStoreError::WRONG_PUBLIC_KEY); } } if (crypto::KeyTypes::GRANDPA == key_type_id) { @@ -94,7 +94,7 @@ namespace kagome::api { store_->generateEd25519Keypair(crypto::KeyTypes::GRANDPA, seed_typed)); if (public_key_typed != keypair.public_key) { - return outcome::failure(crypto::CryptoStoreError::WRONG_PUBLIC_KEY); + return Q_ERROR(crypto::CryptoStoreError::WRONG_PUBLIC_KEY); } } auto res = key_store_->saveKeyPair(key_type_id, public_key, seed); @@ -162,7 +162,7 @@ namespace kagome::api { AuthorApiImpl::removeExtrinsic( const std::vector &keys) { BOOST_ASSERT_MSG(false, "not implemented"); // NOLINT - return outcome::failure(std::errc::not_supported); + return Q_ERROR(std::errc::not_supported); } outcome::result diff --git a/core/api/service/chain/impl/chain_api_impl.cpp b/core/api/service/chain/impl/chain_api_impl.cpp index 8c3aa99531..9c61be67ff 100644 --- a/core/api/service/chain/impl/chain_api_impl.cpp +++ b/core/api/service/chain/impl/chain_api_impl.cpp @@ -87,7 +87,7 @@ namespace kagome::api { if (block) { return block.value(); } - return Error::BLOCK_NOT_FOUND; + return Q_ERROR(Error::BLOCK_NOT_FOUND); } outcome::result ChainApiImpl::getBlock() { @@ -96,7 +96,7 @@ namespace kagome::api { if (block) { return block.value(); } - return Error::BLOCK_NOT_FOUND; + return Q_ERROR(Error::BLOCK_NOT_FOUND); } outcome::result ChainApiImpl::getFinalizedHead() diff --git a/core/api/service/internal/impl/internal_api_impl.cpp b/core/api/service/internal/impl/internal_api_impl.cpp index 2831585afc..62b781d4fa 100644 --- a/core/api/service/internal/impl/internal_api_impl.cpp +++ b/core/api/service/internal/impl/internal_api_impl.cpp @@ -15,7 +15,7 @@ namespace kagome::api { OUTCOME_TRY(level, log::str2lvl(level_str)); if (not log::setLevelOfGroup(group, level)) { - return log::Error::WRONG_GROUP; + return Q_ERROR(log::Error::WRONG_GROUP); } return outcome::success(); diff --git a/core/api/service/jrpc_fn.hpp b/core/api/service/jrpc_fn.hpp index e9226de995..8765d4d209 100644 --- a/core/api/service/jrpc_fn.hpp +++ b/core/api/service/jrpc_fn.hpp @@ -23,7 +23,7 @@ namespace kagome::api { } return {}; } - throw jsonrpc::Fault(result.error().message()); + throw jsonrpc::Fault(fmt::to_string(result.error())); } else { call(); return {}; diff --git a/core/api/service/state/impl/state_api_impl.cpp b/core/api/service/state/impl/state_api_impl.cpp index 3742cfaec9..c847d90b2a 100644 --- a/core/api/service/state/impl/state_api_impl.cpp +++ b/core/api/service/state/impl/state_api_impl.cpp @@ -138,17 +138,17 @@ namespace kagome::api { auto to = opt_to.has_value() ? opt_to.value() : block_tree_->bestBlock().hash; if (keys.size() > static_cast(kMaxKeySetSize)) { - return Error::MAX_KEY_SET_SIZE_EXCEEDED; + return Q_ERROR(Error::MAX_KEY_SET_SIZE_EXCEEDED); } if (from != to) { OUTCOME_TRY(from_number, header_repo_->getNumberByHash(from)); OUTCOME_TRY(to_number, header_repo_->getNumberByHash(to)); if (to_number < from_number) { - return Error::END_BLOCK_LOWER_THAN_BEGIN_BLOCK; + return Q_ERROR(Error::END_BLOCK_LOWER_THAN_BEGIN_BLOCK); } if (to_number - from_number > kMaxBlockRange) { - return Error::MAX_BLOCK_RANGE_EXCEEDED; + return Q_ERROR(Error::MAX_BLOCK_RANGE_EXCEEDED); } } diff --git a/core/api/transport/error.hpp b/core/api/transport/error.hpp index fc19aa735a..61ec1509bc 100644 --- a/core/api/transport/error.hpp +++ b/core/api/transport/error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::api { enum class ApiTransportError { diff --git a/core/api/transport/impl/ws/ws_session.cpp b/core/api/transport/impl/ws/ws_session.cpp index 5df5f6f8a7..77277e26b1 100644 --- a/core/api/transport/impl/ws/ws_session.cpp +++ b/core/api/transport/impl/ws/ws_session.cpp @@ -10,7 +10,8 @@ #include #include -#include + +#include "log/formatters/boost_ec.hpp" namespace boost::beast { template diff --git a/core/application/impl/app_configuration_impl.cpp b/core/application/impl/app_configuration_impl.cpp index 995d414a5f..a7485b568a 100644 --- a/core/application/impl/app_configuration_impl.cpp +++ b/core/application/impl/app_configuration_impl.cpp @@ -581,11 +581,11 @@ namespace kagome::application { "Address cannot be used to bind to ({}). Only IPv4 and IPv6 " "interfaces are supported", multiaddress.getStringAddress()); - return NOT_SUPPORTED; + return Q_ERROR(NOT_SUPPORTED); } auto port = multiaddress.getFirstValueForProtocol(proto::TCP); if (not port) { - return NOT_SUPPORTED; + return Q_ERROR(NOT_SUPPORTED); } uint16_t port_number = 0; try { @@ -598,7 +598,7 @@ namespace kagome::application { wide_port, max_port, multiaddress.getStringAddress()); - return BAD_ADDRESS; + return Q_ERROR(BAD_ADDRESS); } port_number = static_cast(wide_port); } catch (...) { @@ -607,7 +607,7 @@ namespace kagome::application { "Passed value {} is not a valid port number within address {}", port.value(), multiaddress.getStringAddress()); - return BAD_ADDRESS; + return Q_ERROR(BAD_ADDRESS); } return getEndpointFrom(host.value(), port_number); } diff --git a/core/application/impl/chain_spec_impl.cpp b/core/application/impl/chain_spec_impl.cpp index 643ebd253a..35eb0ef310 100644 --- a/core/application/impl/chain_spec_impl.cpp +++ b/core/application/impl/chain_spec_impl.cpp @@ -60,7 +60,7 @@ namespace kagome::application { } catch (pt::json_parser_error &e) { log_->error( "Parser error: {}, line {}: {}", e.filename(), e.line(), e.message()); - return Error::PARSER_ERROR; + return Q_ERROR(Error::PARSER_ERROR); } OUTCOME_TRY(loadFields(tree)); @@ -195,7 +195,7 @@ namespace kagome::application { block_id_str.data() + block_id_str.size(), block_num); if (res.ec != std::errc()) { - return Error::PARSER_ERROR; + return Q_ERROR(Error::PARSER_ERROR); } block_id = block_num; } @@ -205,7 +205,7 @@ namespace kagome::application { outcome::result ChainSpecImpl::fetchCodeSubstituteByBlockInfo( const primitives::BlockInfo &block_info) const { if (!known_code_substitutes_->contains(block_info)) { - return Error::MISSING_ENTRY; + return Q_ERROR(Error::MISSING_ENTRY); } pt::ptree tree; @@ -214,7 +214,7 @@ namespace kagome::application { } catch (pt::json_parser_error &e) { log_->error( "Parser error: {}, line {}: {}", e.filename(), e.line(), e.message()); - return Error::PARSER_ERROR; + return Q_ERROR(Error::PARSER_ERROR); } auto code_substitutes_opt = tree.get_child_optional("codeSubstitutes"); @@ -234,7 +234,7 @@ namespace kagome::application { } } } - return Error::MISSING_ENTRY; + return Q_ERROR(Error::MISSING_ENTRY); } outcome::result ChainSpecImpl::loadGenesis( @@ -293,7 +293,7 @@ namespace kagome::application { OUTCOME_TRY(libp2p::peer::PeerId::fromBase58(peer_id_base58.value())); boot_nodes_.emplace_back(std::move(multiaddr)); } else { - return Error::MISSING_PEER_ID; + return Q_ERROR(Error::MISSING_PEER_ID); } } else { log_->warn("Unsupported multiaddress '{}'. Ignoring that boot node", diff --git a/core/application/impl/chain_spec_impl.hpp b/core/application/impl/chain_spec_impl.hpp index c378639e48..daecfee5f4 100644 --- a/core/application/impl/chain_spec_impl.hpp +++ b/core/application/impl/chain_spec_impl.hpp @@ -109,7 +109,7 @@ namespace kagome::application { if (not opt_entry) { log_->error("Required '{}' entry not found in the chain spec", entry_name); - return Error::MISSING_ENTRY; + return Q_ERROR(Error::MISSING_ENTRY); } return opt_entry.value(); } diff --git a/core/application/impl/util.cpp b/core/application/impl/util.cpp index 5ecd2c5a79..2599cca854 100644 --- a/core/application/impl/util.cpp +++ b/core/application/impl/util.cpp @@ -6,11 +6,9 @@ #include "application/impl/util.hpp" -#define UNWRAP_ERROR_CODE(ec) \ - { \ - if (ec) { \ - return outcome::failure(ec); \ - } \ +#define UNWRAP_ERROR_CODE(ec) \ + if (ec) { \ + return Q_ERROR(ec); \ } OUTCOME_CPP_DEFINE_CATEGORY(kagome::application::util, Error, e) { @@ -34,12 +32,12 @@ namespace kagome::application::util { if (not fs::exists(path, ec)) { UNWRAP_ERROR_CODE(ec) if (not fs::create_directory(path, ec)) { - return Error::FAILED_TO_CREATE_DIR; + return Q_ERROR(Error::FAILED_TO_CREATE_DIR); } UNWRAP_ERROR_CODE(ec) } else { if (not fs::is_directory(path, ec)) { - return Error::NOT_A_DIR; + return Q_ERROR(Error::NOT_A_DIR); } UNWRAP_ERROR_CODE(ec) } diff --git a/core/application/impl/util.hpp b/core/application/impl/util.hpp index 3b5a2b57eb..11e634dd65 100644 --- a/core/application/impl/util.hpp +++ b/core/application/impl/util.hpp @@ -6,6 +6,8 @@ #pragma once +#include + #include "filesystem/common.hpp" #include "outcome/outcome.hpp" diff --git a/core/authority_discovery/query/query_impl.cpp b/core/authority_discovery/query/query_impl.cpp index ae45dbb121..0cd2eb741d 100644 --- a/core/authority_discovery/query/query_impl.cpp +++ b/core/authority_discovery/query/query_impl.cpp @@ -173,7 +173,7 @@ namespace kagome::authority_discovery { ::authority_discovery::v2::SignedAuthorityRecord signed_record; if (not signed_record.ParseFromArray(signed_record_pb.data(), signed_record_pb.size())) { - return Error::DECODE_ERROR; + return Q_ERROR(Error::DECODE_ERROR); } libp2p::crypto::ProtobufKey protobuf_key{ common::Buffer{str2byte(signed_record.peer_signature().public_key())}}; @@ -189,10 +189,10 @@ namespace kagome::authority_discovery { ::authority_discovery::v2::AuthorityRecord record; if (not record.ParseFromString(signed_record.record())) { - return Error::DECODE_ERROR; + return Q_ERROR(Error::DECODE_ERROR); } if (record.addresses().empty()) { - return Error::NO_ADDRESSES; + return Q_ERROR(Error::NO_ADDRESSES); } libp2p::peer::PeerInfo peer{std::move(peer_id), {}}; auto peer_id_str = peer.id.toBase58(); @@ -203,7 +203,7 @@ namespace kagome::authority_discovery { continue; } if (id != peer_id_str) { - return Error::INCONSISTENT_PEER_ID; + return Q_ERROR(Error::INCONSISTENT_PEER_ID); } peer.addresses.emplace_back(std::move(address)); } @@ -212,7 +212,7 @@ namespace kagome::authority_discovery { sr_crypto_provider_->verify( auth_sig, str2byte(signed_record.record()), authority)); if (not auth_sig_ok) { - return Error::INVALID_SIGNATURE; + return Q_ERROR(Error::INVALID_SIGNATURE); } OUTCOME_TRY(peer_sig_ok, @@ -221,7 +221,7 @@ namespace kagome::authority_discovery { str2byte(signed_record.peer_signature().signature()), peer_key)); if (not peer_sig_ok) { - return Error::INVALID_SIGNATURE; + return Q_ERROR(Error::INVALID_SIGNATURE); } std::ignore = host_.getPeerRepository().getAddressRepository().addAddresses( diff --git a/core/authority_discovery/query/query_impl.hpp b/core/authority_discovery/query/query_impl.hpp index a9c93a7119..bb152a9906 100644 --- a/core/authority_discovery/query/query_impl.hpp +++ b/core/authority_discovery/query/query_impl.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include namespace kagome::authority_discovery { diff --git a/core/authorship/impl/block_builder_error.hpp b/core/authorship/impl/block_builder_error.hpp index b29bdcae24..64928162bb 100644 --- a/core/authorship/impl/block_builder_error.hpp +++ b/core/authorship/impl/block_builder_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::authorship { diff --git a/core/authorship/impl/block_builder_impl.cpp b/core/authorship/impl/block_builder_impl.cpp index d0ecac4979..6176c1aedf 100644 --- a/core/authorship/impl/block_builder_impl.cpp +++ b/core/authorship/impl/block_builder_impl.cpp @@ -59,7 +59,7 @@ namespace kagome::authorship { "block. (DispatchError {})", extrinsic.data.toHex().substr(0, 8), error->which()); - return BlockBuilderError::EXTRINSIC_APPLICATION_FAILED; + return Q_ERROR(BlockBuilderError::EXTRINSIC_APPLICATION_FAILED); } // https://github.com/paritytech/substrate/blob/943c520aa78fcfaf3509790009ad062e8d4c6990/client/block-builder/src/lib.rs#L204-L237 extrinsics_.push_back(extrinsic); @@ -73,9 +73,9 @@ namespace kagome::authorship { const primitives::InvalidTransaction &reason) -> return_type { switch (reason) { case primitives::InvalidTransaction::ExhaustsResources: - return BlockBuilderError::EXHAUSTS_RESOURCES; + return Q_ERROR(BlockBuilderError::EXHAUSTS_RESOURCES); case primitives::InvalidTransaction::BadMandatory: - return BlockBuilderError::BAD_MANDATORY; + return Q_ERROR(BlockBuilderError::BAD_MANDATORY); default: SL_WARN( logger_, @@ -83,7 +83,8 @@ namespace kagome::authorship { "the block. (InvalidTransaction response, code {})", extrinsic.data.toHex().substr(0, 8), static_cast(reason)); - return BlockBuilderError::EXTRINSIC_APPLICATION_FAILED; + return Q_ERROR( + BlockBuilderError::EXTRINSIC_APPLICATION_FAILED); } }, [this, &extrinsic]( @@ -93,7 +94,7 @@ namespace kagome::authorship { "the block. (UnknownTransaction response, code {})", extrinsic.data.toHex().substr(0, 8), static_cast(reason)); - return BlockBuilderError::EXTRINSIC_APPLICATION_FAILED; + return Q_ERROR(BlockBuilderError::EXTRINSIC_APPLICATION_FAILED); }); }); } diff --git a/core/authorship/impl/proposer_impl.cpp b/core/authorship/impl/proposer_impl.cpp index c2fefae195..396226fccd 100644 --- a/core/authorship/impl/proposer_impl.cpp +++ b/core/authorship/impl/proposer_impl.cpp @@ -62,11 +62,11 @@ namespace kagome::authorship { SL_DEBUG(logger_, "Adding inherent extrinsic: {}", xt.data); auto inserted_res = block_builder->pushExtrinsic(xt); if (not inserted_res) { - if (BlockBuilderError::EXHAUSTS_RESOURCES == inserted_res.error()) { + if (inserted_res.error().ec(BlockBuilderError::EXHAUSTS_RESOURCES)) { SL_WARN(logger_, "Dropping non-mandatory inherent extrinsic from overweight " "block."); - } else if (BlockBuilderError::BAD_MANDATORY == inserted_res.error()) { + } else if (inserted_res.error().ec(BlockBuilderError::BAD_MANDATORY)) { SL_ERROR(logger_, "Mandatory inherent extrinsic returned error. Block cannot " "be produced."); @@ -137,7 +137,7 @@ namespace kagome::authorship { SL_DEBUG(logger_, "Adding extrinsic: {}", tx->ext.data); auto inserted_res = block_builder->pushExtrinsic(tx->ext); if (not inserted_res) { - if (BlockBuilderError::EXHAUSTS_RESOURCES == inserted_res.error()) { + if (inserted_res.error().ec(BlockBuilderError::EXHAUSTS_RESOURCES)) { if (skipped < kMaxSkippedTransactions) { ++skipped; SL_DEBUG(logger_, diff --git a/core/benchmark/block_execution_benchmark.cpp b/core/benchmark/block_execution_benchmark.cpp index 89b8db4aa1..81931f11cf 100644 --- a/core/benchmark/block_execution_benchmark.cpp +++ b/core/benchmark/block_execution_benchmark.cpp @@ -28,41 +28,24 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::benchmark, return "Unknown BlockExecutionBenchmark error"; } -#define STR_SIMPLE(a) #a -#define STR(a) STR_SIMPLE(a) -#define CONCAT_SIMPLE(a, b) a##b -#define CONCAT(a, b) CONCAT_SIMPLE(a, b) - -static_assert(STR(CONCAT(2, 3)) == std::string_view("23")); - -// mind if you want to move it to global scope, __LINE__ is not very reliable, -// may use __COUNTER__ instead -#define OUTCOME_TRY_MSG(var, expr, msg, ...) \ - auto CONCAT(_res_, __LINE__) = (expr); \ - do { \ - if (CONCAT(_res_, __LINE__).has_error()) { \ - SL_ERROR(logger_, \ - "Failure on {}: {} ({})", \ - #expr, \ - CONCAT(_res_, __LINE__).error().message(), \ - fmt::format(msg, __VA_ARGS__)); \ - return CONCAT(_res_, __LINE__).as_failure(); \ - } \ - } while (false); \ - auto var = std::move(CONCAT(_res_, __LINE__).value()); - -#define OUTCOME_TRY_MSG_VOID(expr, msg, ...) \ - do { \ - auto CONCAT(_res_, __LINE__) = (expr); \ - if (CONCAT(_res_, __LINE__).has_error()) { \ - SL_ERROR(logger_, \ - "Failure on {}: {} ({})", \ - #expr, \ - CONCAT(_res_, __LINE__).error().message(), \ - fmt::format(msg, __VA_ARGS__)); \ - return CONCAT(_res_, __LINE__).as_failure(); \ - } \ - } while (false); +#define _OUTCOME_TRY_CB(expr, ...) \ + [&](qtils::Errors errors) { \ + SL_ERROR(logger_, \ + "Failure on {}: {} ({})", \ + #expr, \ + errors, \ + fmt::format(__VA_ARGS__)); \ + return errors; \ + } +#define _OUTCOME_TRY_MSG_void(tmp, expr, ...) \ + _Q_TRY_void(tmp, (_OUTCOME_TRY_CB(expr, __VA_ARGS__)), expr, Q_ERROR(nullptr)) +#define _OUTCOME_TRY_MSG_out(tmp, out, expr, ...) \ + _OUTCOME_TRY_MSG_void(tmp, expr, __VA_ARGS__); \ + auto out = std::move(tmp).value(); +#define OUTCOME_TRY_MSG(out, expr, ...) \ + _OUTCOME_TRY_MSG_out(OUTCOME_UNIQUE, out, expr, __VA_ARGS__) +#define OUTCOME_TRY_MSG_VOID(expr, ...) \ + _OUTCOME_TRY_MSG_void(OUTCOME_UNIQUE, expr, __VA_ARGS__) namespace kagome::benchmark { @@ -209,10 +192,12 @@ namespace kagome::benchmark { try { stream >> block_weight; } catch (std::exception &e) { - return BlockExecutionBenchmark::Error::BLOCK_WEIGHT_DECODE_FAILED; + return Q_ERROR( + BlockExecutionBenchmark::Error::BLOCK_WEIGHT_DECODE_FAILED); } if (stream.hasMore(1)) { - return BlockExecutionBenchmark::Error::BLOCK_WEIGHT_DECODE_FAILED; + return Q_ERROR( + BlockExecutionBenchmark::Error::BLOCK_WEIGHT_DECODE_FAILED); } return std::chrono::nanoseconds{static_cast(std::floor( @@ -227,7 +212,7 @@ namespace kagome::benchmark { config.start); if (!current_hash) { SL_ERROR(logger_, "Start block {} is not found!", config.start); - return Error::BLOCK_NOT_FOUND; + return Q_ERROR(Error::BLOCK_NOT_FOUND); } primitives::BlockInfo current_block_info = {config.start, *current_hash}; @@ -257,7 +242,7 @@ namespace kagome::benchmark { SL_ERROR(logger_, "Next block {} is not found!", current_block_info.number + 1); - return Error::BLOCK_NOT_FOUND; + return Q_ERROR(Error::BLOCK_NOT_FOUND); } current_block_info.hash = *next_hash; } diff --git a/core/blockchain/block_storage_error.hpp b/core/blockchain/block_storage_error.hpp index ec8c52d0ff..ec8c65ccc9 100644 --- a/core/blockchain/block_storage_error.hpp +++ b/core/blockchain/block_storage_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::blockchain { diff --git a/core/blockchain/block_tree_error.hpp b/core/blockchain/block_tree_error.hpp index a443704137..b0f8133bb4 100644 --- a/core/blockchain/block_tree_error.hpp +++ b/core/blockchain/block_tree_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::blockchain { /** diff --git a/core/blockchain/impl/block_header_repository_impl.cpp b/core/blockchain/impl/block_header_repository_impl.cpp index 11afe95ed0..010deeaef8 100644 --- a/core/blockchain/impl/block_header_repository_impl.cpp +++ b/core/blockchain/impl/block_header_repository_impl.cpp @@ -38,7 +38,7 @@ namespace kagome::blockchain { auto key_space = storage_->getSpace(Space::kLookupKey); auto res = key_space->get(num_to_idx_key); if (not res.has_value()) { - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } return primitives::BlockHash::fromSpan(res.value()); } @@ -54,7 +54,7 @@ namespace kagome::blockchain { header.hash_opt.emplace(block_hash); return header; } - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } outcome::result BlockHeaderRepositoryImpl::getBlockStatus( diff --git a/core/blockchain/impl/block_storage_impl.cpp b/core/blockchain/impl/block_storage_impl.cpp index d3683e1ede..a7828e7226 100644 --- a/core/blockchain/impl/block_storage_impl.cpp +++ b/core/blockchain/impl/block_storage_impl.cpp @@ -63,7 +63,7 @@ namespace kagome::blockchain { block_storage->logger_->critical( "Database is not consistent: Genesis block header not found, " "but exists num-to-hash record for block #0"); - return BlockStorageError::HEADER_NOT_FOUND; + return Q_ERROR(BlockStorageError::HEADER_NOT_FOUND); } } @@ -80,7 +80,7 @@ namespace kagome::blockchain { OUTCOME_TRY(leaves_opt, default_space->tryGet(storage::kBlockTreeLeavesLookupKey)); if (not leaves_opt.has_value()) { - return BlockStorageError::BLOCK_TREE_LEAVES_NOT_FOUND; + return Q_ERROR(BlockStorageError::BLOCK_TREE_LEAVES_NOT_FOUND); } OUTCOME_TRY( @@ -132,7 +132,7 @@ namespace kagome::blockchain { } else { SL_ERROR( logger_, "Failed to fetch header for block ({})", current_hash); - return BlockStorageError::HEADER_NOT_FOUND; + return Q_ERROR(BlockStorageError::HEADER_NOT_FOUND); } } diff --git a/core/blockchain/impl/block_tree_impl.cpp b/core/blockchain/impl/block_tree_impl.cpp index ce41b3375e..945925181c 100644 --- a/core/blockchain/impl/block_tree_impl.cpp +++ b/core/blockchain/impl/block_tree_impl.cpp @@ -50,7 +50,7 @@ namespace kagome::blockchain { for (auto &hash : block_tree_unordered_leaves) { auto res = header_repo->getNumberById(hash); if (res.has_error()) { - if (res == outcome::failure(BlockTreeError::HEADER_NOT_FOUND)) { + if (res.error().ec(BlockTreeError::HEADER_NOT_FOUND)) { SL_TRACE(log, "Leaf {} not found", hash); continue; } @@ -77,7 +77,7 @@ namespace kagome::blockchain { if (hash_opt_res.has_failure()) { SL_CRITICAL( log, "Search best block has failed: {}", hash_opt_res.error()); - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } const auto &hash_opt = hash_opt_res.value(); @@ -329,10 +329,10 @@ namespace kagome::blockchain { SL_CRITICAL(log, "Can't get header of target block: {}", target_block_hash_opt_res.error()); - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } else if (not target_block_hash_opt_res.value().has_value()) { SL_CRITICAL(log, "Can't get header of target block: header not found"); - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } const auto &target_block_hash = target_block_hash_opt_res.value().value(); @@ -347,7 +347,7 @@ namespace kagome::blockchain { } const auto &target_block_header_opt = target_block_header_opt_res.value(); if (not target_block_header_opt.has_value()) { - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } const auto &target_block_header = target_block_header_opt.value(); @@ -378,7 +378,7 @@ namespace kagome::blockchain { } const auto &header_opt = header_opt_res.value(); if (not header_opt.has_value()) { - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } const auto &header = header_opt.value(); @@ -511,7 +511,7 @@ namespace kagome::blockchain { [&](BlockTreeData &p) -> outcome::result { auto parent = p.tree_->find(header.parent_hash); if (!parent) { - return BlockTreeError::NO_PARENT; + return Q_ERROR(BlockTreeError::NO_PARENT); } OUTCOME_TRY(p.storage_->putBlockHeader(header)); @@ -539,7 +539,7 @@ namespace kagome::blockchain { // Check if we know parent of this block; if not, we cannot insert it auto parent = p.tree_->find(block.header.parent_hash); if (!parent) { - return BlockTreeError::NO_PARENT; + return Q_ERROR(BlockTreeError::NO_PARENT); } // Save block @@ -595,10 +595,10 @@ namespace kagome::blockchain { [&](BlockTreeData &p) -> outcome::result { // Check if block is leaf if (block_hash == getLastFinalizedNoLock(p).hash) { - return BlockTreeError::BLOCK_IS_FINALIZED; + return Q_ERROR(BlockTreeError::BLOCK_IS_FINALIZED); } if (not p.tree_->isLeaf(block_hash)) { - return BlockTreeError::BLOCK_IS_NOT_LEAF; + return Q_ERROR(BlockTreeError::BLOCK_IS_NOT_LEAF); } auto changes = p.tree_->removeLeaf(block_hash); OUTCOME_TRY(reorgAndPrune(p, changes)); @@ -615,7 +615,7 @@ namespace kagome::blockchain { auto node = p.tree_->find(block_hash); if (node == nullptr) { SL_WARN(log_, "Block {} doesn't exists in block tree", block_hash); - return BlockTreeError::BLOCK_NOT_EXISTS; + return Q_ERROR(BlockTreeError::BLOCK_NOT_EXISTS); } node->contains_approved_para_block = true; @@ -680,7 +680,7 @@ namespace kagome::blockchain { SL_TRACE(log_, "Block {} exists in block tree", primitives::BlockInfo(block_header.number, block_hash)); - return BlockTreeError::BLOCK_EXISTS; + return Q_ERROR(BlockTreeError::BLOCK_EXISTS); } auto parent = p.tree_->find(block_header.parent_hash); @@ -703,7 +703,7 @@ namespace kagome::blockchain { for (auto hash = block_header.parent_hash;;) { OUTCOME_TRY(header_opt, p.storage_->getBlockHeader(hash)); if (not header_opt.has_value()) { - return BlockTreeError::NO_PARENT; + return Q_ERROR(BlockTreeError::NO_PARENT); } auto &header = header_opt.value(); @@ -712,7 +712,7 @@ namespace kagome::blockchain { primitives::BlockInfo(header.number, hash)); if (header.number <= finalized) { - return BlockTreeError::BLOCK_ON_DEAD_END; + return Q_ERROR(BlockTreeError::BLOCK_ON_DEAD_END); } to_add.emplace(hash, std::move(header)); @@ -796,7 +796,7 @@ namespace kagome::blockchain { OUTCOME_TRY(header_opt, p.storage_->getBlockHeader(block_hash)); if (not header_opt.has_value()) { - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } auto &header = header_opt.value(); @@ -886,11 +886,11 @@ namespace kagome::blockchain { } else { OUTCOME_TRY(header, p.header_repo_->getBlockHeader(block_hash)); if (header.number >= last_finalized_block_info.number) { - return BlockTreeError::NON_FINALIZED_BLOCK_NOT_FOUND; + return Q_ERROR(BlockTreeError::NON_FINALIZED_BLOCK_NOT_FOUND); } OUTCOME_TRY(canon_hash, p.header_repo_->getHashByNumber(header.number)); if (block_hash != canon_hash) { - return BlockTreeError::BLOCK_ON_DEAD_END; + return Q_ERROR(BlockTreeError::BLOCK_ON_DEAD_END); } if (not p.justification_storage_policy_ ->shouldStoreFor(header, last_finalized_block_info.number) @@ -932,7 +932,7 @@ namespace kagome::blockchain { if (header.has_value()) { return header.value(); } - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } outcome::result BlockTreeImpl::getBlockHeader( @@ -952,7 +952,7 @@ namespace kagome::blockchain { if (body.has_value()) { return body.value(); } - return BlockTreeError::BODY_NOT_FOUND; + return Q_ERROR(BlockTreeError::BODY_NOT_FOUND); }); } @@ -966,7 +966,7 @@ namespace kagome::blockchain { if (justification.has_value()) { return justification.value(); } - return BlockTreeError::JUSTIFICATION_NOT_FOUND; + return Q_ERROR(BlockTreeError::JUSTIFICATION_NOT_FOUND); }); } @@ -978,7 +978,7 @@ namespace kagome::blockchain { if (block_number_res.has_error()) { log_->error( "cannot retrieve block {}: {}", block, block_number_res.error()); - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } auto start_block_number = block_number_res.value(); @@ -1004,7 +1004,7 @@ namespace kagome::blockchain { log_->error("cannot retrieve block with number {}: {}", finish_block_number, finish_block_hash_res.error()); - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } const auto &finish_block_hash = finish_block_hash_res.value(); @@ -1047,7 +1047,7 @@ namespace kagome::blockchain { log_->error("cannot retrieve block with hash {}: {}", hash, header_res.error()); - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } break; } @@ -1077,16 +1077,16 @@ namespace kagome::blockchain { OUTCOME_TRY(from, p.header_repo_->getNumberByHash(ancestor)); OUTCOME_TRY(to, p.header_repo_->getNumberByHash(descendant)); if (to < from) { - return BlockTreeError::TARGET_IS_PAST_MAX; + return Q_ERROR(BlockTreeError::TARGET_IS_PAST_MAX); } auto count = to - from + 1; OUTCOME_TRY(chain, getDescendingChainToBlockNoLock(p, descendant, count)); if (chain.size() != count) { - return BlockTreeError::EXISTING_BLOCK_NOT_FOUND; + return Q_ERROR(BlockTreeError::EXISTING_BLOCK_NOT_FOUND); } if (chain.back() != ancestor) { - return BlockTreeError::BLOCK_ON_DEAD_END; + return Q_ERROR(BlockTreeError::BLOCK_ON_DEAD_END); } std::reverse(chain.begin(), chain.end()); return chain; @@ -1214,7 +1214,7 @@ namespace kagome::blockchain { p.header_repo_->getHashByNumber(target_number)); if (canon_hash != target_hash) { - return BlockTreeError::BLOCK_ON_DEAD_END; + return Q_ERROR(BlockTreeError::BLOCK_ON_DEAD_END); } return bestBlockNoLock(p); @@ -1248,7 +1248,7 @@ namespace kagome::blockchain { } OUTCOME_TRY(header, p.storage_->getBlockHeader(block)); if (!header.has_value()) { - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } // if node is not in tree_ it must be finalized and thus have only one // child diff --git a/core/common/blob.hpp b/core/common/blob.hpp index eab9be6335..950e54dea9 100644 --- a/core/common/blob.hpp +++ b/core/common/blob.hpp @@ -165,7 +165,7 @@ namespace kagome::common { */ static outcome::result> fromString(std::string_view data) { if (data.size() != size_) { - return BlobError::INCORRECT_LENGTH; + return Q_ERROR(BlobError::INCORRECT_LENGTH); } Blob b; @@ -204,7 +204,7 @@ namespace kagome::common { */ static outcome::result> fromSpan(const BufferView &span) { if (span.size() != size_) { - return BlobError::INCORRECT_LENGTH; + return Q_ERROR(BlobError::INCORRECT_LENGTH); } Blob blob; diff --git a/core/common/hexutil.cpp b/core/common/hexutil.cpp index 31baeb537e..27222aa40f 100644 --- a/core/common/hexutil.cpp +++ b/core/common/hexutil.cpp @@ -82,13 +82,13 @@ namespace kagome::common { return blob; } catch (const boost::algorithm::not_enough_input &e) { - return UnhexError::NOT_ENOUGH_INPUT; + return Q_ERROR(UnhexError::NOT_ENOUGH_INPUT); } catch (const boost::algorithm::non_hex_input &e) { - return UnhexError::NON_HEX_INPUT; + return Q_ERROR(UnhexError::NON_HEX_INPUT); } catch (const std::exception &e) { - return UnhexError::UNKNOWN; + return Q_ERROR(UnhexError::UNKNOWN); } } @@ -97,7 +97,7 @@ namespace kagome::common { static const std::string leading_chrs = "0x"; if (hex_with_prefix.substr(0, leading_chrs.size()) != leading_chrs) { - return UnhexError::MISSING_0X_PREFIX; + return Q_ERROR(UnhexError::MISSING_0X_PREFIX); } auto without_prefix = hex_with_prefix.substr(leading_chrs.size()); diff --git a/core/common/hexutil.hpp b/core/common/hexutil.hpp index 19ca6738bc..f261b91be1 100644 --- a/core/common/hexutil.hpp +++ b/core/common/hexutil.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include @@ -25,6 +26,11 @@ namespace kagome::common { MISSING_0X_PREFIX, UNKNOWN }; +} // namespace kagome::common + +OUTCOME_HPP_DECLARE_ERROR(kagome::common, UnhexError); + +namespace kagome::common { /** * @brief Converts an integer to an uppercase hex representation @@ -93,7 +99,7 @@ namespace kagome::common { bytes = std::move(bts); if (bytes.size() > sizeof(T)) { - return UnhexError::VALUE_OUT_OF_RANGE; + return Q_ERROR(UnhexError::VALUE_OUT_OF_RANGE); } T result{0u}; @@ -111,5 +117,3 @@ namespace kagome::common { } } // namespace kagome::common - -OUTCOME_HPP_DECLARE_ERROR(kagome::common, UnhexError); diff --git a/core/common/tagged.hpp b/core/common/tagged.hpp index 8e1a6d22b5..08af9256d4 100644 --- a/core/common/tagged.hpp +++ b/core/common/tagged.hpp @@ -30,11 +30,11 @@ namespace kagome { public: typedef Tag tag; - template - explicit Tagged(Args &&...args) : Base(std::forward(args)...) {} + Tagged() + requires(std::is_default_constructible_v) + : Base() {} - Tagged(T &&value) noexcept(not std::is_lvalue_reference_v) - : Base(std::forward(value)) {} + Tagged(T value) : Base(std::move(value)) {} Tagged &operator=(T &&value) noexcept( not std::is_lvalue_reference_v) { diff --git a/core/consensus/babe/impl/babe.cpp b/core/consensus/babe/impl/babe.cpp index e271e7a217..181d02d402 100644 --- a/core/consensus/babe/impl/babe.cpp +++ b/core/consensus/babe/impl/babe.cpp @@ -187,7 +187,7 @@ namespace kagome::consensus::babe { "Authority not known, skipping slot processing. " "Probably authority list has changed."); } - return BlockProductionError::NO_VALIDATOR; + return Q_ERROR(BlockProductionError::NO_VALIDATOR); } Context ctx{.parent = best_block, @@ -261,7 +261,7 @@ namespace kagome::consensus::babe { "Babe author {} is not slot leader in current slot", ctx.keypair->public_key); - return BlockProductionError::NO_SLOT_LEADER; + return Q_ERROR(BlockProductionError::NO_SLOT_LEADER); } outcome::result Babe::babePreDigest( @@ -280,7 +280,7 @@ namespace kagome::consensus::babe { SL_ERROR( log_, "VRF proof is required to build block header but was not passed"); - return BabeError::MISSING_PROOF; + return Q_ERROR(BabeError::MISSING_PROOF); } babe_header.vrf_output = output.value(); } @@ -337,7 +337,7 @@ namespace kagome::consensus::babe { SL_INFO(log_, "Backing off claiming new slot for block authorship: finality is " "lagging."); - return BlockProductionError::BACKING_OFF; + return Q_ERROR(BlockProductionError::BACKING_OFF); } BOOST_ASSERT(ctx.keypair != nullptr); @@ -362,13 +362,13 @@ namespace kagome::consensus::babe { if (auto res = inherent_data.putData(kTimestampId, now); res.has_error()) { SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); - return BabeError::CAN_NOT_PREPARE_BLOCK; + return Q_ERROR(BabeError::CAN_NOT_PREPARE_BLOCK); } if (auto res = inherent_data.putData(kBabeSlotId, ctx.slot); res.has_error()) { SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); - return BabeError::CAN_NOT_PREPARE_BLOCK; + return Q_ERROR(BabeError::CAN_NOT_PREPARE_BLOCK); } parachain::ParachainInherentData parachain_inherent_data; @@ -401,7 +401,7 @@ namespace kagome::consensus::babe { if (auto res = inherent_data.putData(kParachainId, parachain_inherent_data); res.has_error()) { SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); - return BabeError::CAN_NOT_PREPARE_BLOCK; + return Q_ERROR(BabeError::CAN_NOT_PREPARE_BLOCK); } auto proposal_start = std::chrono::steady_clock::now(); @@ -410,7 +410,7 @@ namespace kagome::consensus::babe { babePreDigest(ctx, slot_type, output, authority_index); if (not babe_pre_digest_res) { SL_ERROR(log_, "cannot propose a block: {}", babe_pre_digest_res.error()); - return BabeError::CAN_NOT_PREPARE_BLOCK; + return Q_ERROR(BabeError::CAN_NOT_PREPARE_BLOCK); } const auto &babe_pre_digest = babe_pre_digest_res.value(); @@ -490,7 +490,7 @@ namespace kagome::consensus::babe { auto seal_res = sealBlock(ctx, block); if (!seal_res) { SL_ERROR(log_, "Failed to seal the block: {}", seal_res.error()); - return BabeError::CAN_NOT_SEAL_BLOCK; + return Q_ERROR(BabeError::CAN_NOT_SEAL_BLOCK); } // add seal digest item @@ -507,7 +507,7 @@ namespace kagome::consensus::babe { "If you are executing in debug mode, consider to rebuild in " "release", kMaxBlockSlotsOvertime); - return BabeError::WAS_NOT_BUILD_ON_TIME; + return Q_ERROR(BabeError::WAS_NOT_BUILD_ON_TIME); } const auto block_info = block.header.blockInfo(); @@ -517,7 +517,7 @@ namespace kagome::consensus::babe { // add block to the block tree if (auto add_res = block_tree_->addBlock(block); not add_res) { SL_ERROR(log_, "Could not add block {}: {}", block_info, add_res.error()); - return BabeError::CAN_NOT_SAVE_BLOCK; + return Q_ERROR(BabeError::CAN_NOT_SAVE_BLOCK); } changes_tracker->onBlockAdded( diff --git a/core/consensus/babe/impl/babe_config_repository_impl.cpp b/core/consensus/babe/impl/babe_config_repository_impl.cpp index 1c532e0ad8..36861dca2e 100644 --- a/core/consensus/babe/impl/babe_config_repository_impl.cpp +++ b/core/consensus/babe/impl/babe_config_repository_impl.cpp @@ -288,7 +288,7 @@ namespace kagome::consensus::babe { auto r = indexer_.search(descent, block, cb); OUTCOME_TRY(cb_res); if (not r) { - return Error::NOT_FOUND; + return Q_ERROR(Error::NOT_FOUND); } if (not next_epoch and r->second.value->state) { return *r->second.value->state; @@ -342,14 +342,14 @@ namespace kagome::consensus::babe { BabeConfigRepositoryImpl::loadPrev( const std::optional &prev) const { if (not prev) { - return Error::PREVIOUS_NOT_FOUND; + return Q_ERROR(Error::PREVIOUS_NOT_FOUND); } auto r = indexer_.get(*prev); if (not r) { - return Error::PREVIOUS_NOT_FOUND; + return Q_ERROR(Error::PREVIOUS_NOT_FOUND); } if (not r->value) { - return Error::PREVIOUS_NOT_FOUND; + return Q_ERROR(Error::PREVIOUS_NOT_FOUND); } OUTCOME_TRY(load(*prev, *r)); return *r->value->next_state; diff --git a/core/consensus/babe/impl/babe_digests_util.cpp b/core/consensus/babe/impl/babe_digests_util.cpp index 8a09505762..e172f18982 100644 --- a/core/consensus/babe/impl/babe_digests_util.cpp +++ b/core/consensus/babe/impl/babe_digests_util.cpp @@ -32,11 +32,11 @@ namespace kagome::consensus::babe { outcome::result getBabeBlockHeader( const primitives::BlockHeader &block_header) { [[unlikely]] if (block_header.number == 0) { - return DigestError::GENESIS_BLOCK_CAN_NOT_HAVE_DIGESTS; + return Q_ERROR(DigestError::GENESIS_BLOCK_CAN_NOT_HAVE_DIGESTS); } if (block_header.digest.empty()) { - return DigestError::REQUIRED_DIGESTS_NOT_FOUND; + return Q_ERROR(DigestError::REQUIRED_DIGESTS_NOT_FOUND); } const auto &digests = block_header.digest; @@ -52,23 +52,23 @@ namespace kagome::consensus::babe { } } - return DigestError::REQUIRED_DIGESTS_NOT_FOUND; + return Q_ERROR(DigestError::REQUIRED_DIGESTS_NOT_FOUND); } outcome::result getSeal(const primitives::BlockHeader &block_header) { [[unlikely]] if (block_header.number == 0) { - return DigestError::GENESIS_BLOCK_CAN_NOT_HAVE_DIGESTS; + return Q_ERROR(DigestError::GENESIS_BLOCK_CAN_NOT_HAVE_DIGESTS); } if (block_header.digest.empty()) { - return DigestError::REQUIRED_DIGESTS_NOT_FOUND; + return Q_ERROR(DigestError::REQUIRED_DIGESTS_NOT_FOUND); } const auto &digests = block_header.digest; // last digest of the block must be a seal - signature auto seal_opt = getFromVariant(digests.back()); if (not seal_opt.has_value()) { - return DigestError::NO_TRAILING_SEAL_DIGEST; + return Q_ERROR(DigestError::NO_TRAILING_SEAL_DIGEST); } OUTCOME_TRY(seal_digest, scale::decode(seal_opt->get().data)); diff --git a/core/consensus/babe/impl/babe_error.hpp b/core/consensus/babe/impl/babe_error.hpp index ac47d6161b..23020e1bad 100644 --- a/core/consensus/babe/impl/babe_error.hpp +++ b/core/consensus/babe/impl/babe_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::consensus::babe { diff --git a/core/consensus/grandpa/authority_manager_error.hpp b/core/consensus/grandpa/authority_manager_error.hpp index 31413e38cc..6ea1333286 100644 --- a/core/consensus/grandpa/authority_manager_error.hpp +++ b/core/consensus/grandpa/authority_manager_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::consensus::grandpa { enum class AuthorityManagerError { diff --git a/core/consensus/grandpa/impl/authority_manager_impl.cpp b/core/consensus/grandpa/impl/authority_manager_impl.cpp index 494a86e8cc..c05caf559e 100644 --- a/core/consensus/grandpa/impl/authority_manager_impl.cpp +++ b/core/consensus/grandpa/impl/authority_manager_impl.cpp @@ -131,12 +131,12 @@ namespace kagome::consensus::grandpa { GrandpaIndexedValue value; if (digests.forced) { if (not prev) { - return AuthorityManagerError::PREVIOUS_NOT_FOUND; + return Q_ERROR(AuthorityManagerError::PREVIOUS_NOT_FOUND); } while (true) { auto r = indexer_.get(*prev); if (not r or not r->value) { - return AuthorityManagerError::PREVIOUS_NOT_FOUND; + return Q_ERROR(AuthorityManagerError::PREVIOUS_NOT_FOUND); } if (prev->number <= digests.forced->delay_start or r->value->forced_target or r->value->state @@ -147,7 +147,7 @@ namespace kagome::consensus::grandpa { break; } if (not r->prev) { - return AuthorityManagerError::PREVIOUS_NOT_FOUND; + return Q_ERROR(AuthorityManagerError::PREVIOUS_NOT_FOUND); } prev = r->prev; } @@ -173,7 +173,7 @@ namespace kagome::consensus::grandpa { auto r = indexer_.search(descent, block, cb); OUTCOME_TRY(cb_res); if (not r) { - return AuthorityManagerError::NOT_FOUND; + return Q_ERROR(AuthorityManagerError::NOT_FOUND); } if (r->second.value->state) { return *r->second.value->state; @@ -219,11 +219,11 @@ namespace kagome::consensus::grandpa { AuthorityManagerImpl::loadPrev( const std::optional &prev) const { if (not prev) { - return AuthorityManagerError::PREVIOUS_NOT_FOUND; + return Q_ERROR(AuthorityManagerError::PREVIOUS_NOT_FOUND); } auto r = indexer_.get(*prev); if (not r or not r->value) { - return AuthorityManagerError::PREVIOUS_NOT_FOUND; + return Q_ERROR(AuthorityManagerError::PREVIOUS_NOT_FOUND); } OUTCOME_TRY(load(*prev, *r)); return *r->value->next; diff --git a/core/consensus/grandpa/impl/environment_impl.cpp b/core/consensus/grandpa/impl/environment_impl.cpp index 4ec1fd8987..8490b99916 100644 --- a/core/consensus/grandpa/impl/environment_impl.cpp +++ b/core/consensus/grandpa/impl/environment_impl.cpp @@ -171,7 +171,7 @@ namespace kagome::consensus::grandpa { } outcome::result best_undisputed_block_res{ - std::errc::state_not_recoverable}; + Q_ERROR(std::errc::state_not_recoverable)}; std::latch latch(1); dispute_coordinator_->determineUndisputedChain( @@ -389,7 +389,7 @@ namespace kagome::consensus::grandpa { auto &&justification = std::move(res.value()); if (justification.block_info != block_info) { - cb(VotingRoundError::JUSTIFICATION_FOR_WRONG_BLOCK); + cb(Q_ERROR(VotingRoundError::JUSTIFICATION_FOR_WRONG_BLOCK)); return; } diff --git a/core/consensus/grandpa/impl/grandpa_impl.cpp b/core/consensus/grandpa/impl/grandpa_impl.cpp index e7fe4e8384..56859cd669 100644 --- a/core/consensus/grandpa/impl/grandpa_impl.cpp +++ b/core/consensus/grandpa/impl/grandpa_impl.cpp @@ -269,7 +269,7 @@ namespace kagome::consensus::grandpa { SL_WARN(logger_, "Can't retrieve authorities for finalized block {}", best_block); - return VotingRoundError::VOTER_SET_NOT_FOUND_FOR_BLOCK; + return Q_ERROR(VotingRoundError::VOTER_SET_NOT_FOUND_FOR_BLOCK); } auto &authority_set = authorities_opt.value(); @@ -1393,8 +1393,9 @@ namespace kagome::consensus::grandpa { // This is justification for already finalized block if (current_round_->lastFinalizedBlock().number > justification.block_info.number) { - callbackCall(std::move(callback), - VotingRoundError::JUSTIFICATION_FOR_BLOCK_IN_PAST); + callbackCall( + std::move(callback), + Q_ERROR(VotingRoundError::JUSTIFICATION_FOR_BLOCK_IN_PAST)); return; } @@ -1402,7 +1403,7 @@ namespace kagome::consensus::grandpa { justification.block_info, IsBlockFinalized{false}); if (!authorities_opt) { callbackCall(std::move(callback), - VotingRoundError::NO_KNOWN_AUTHORITIES_FOR_BLOCK); + Q_ERROR(VotingRoundError::NO_KNOWN_AUTHORITIES_FOR_BLOCK)); return; } auto &authority_set = authorities_opt.value(); @@ -1439,15 +1440,17 @@ namespace kagome::consensus::grandpa { if (authority_set->id < current_round_->voterSetId()) { callbackCall( std::move(callback), - VotingRoundError::JUSTIFICATION_FOR_AUTHORITY_SET_IN_PAST); + Q_ERROR( + VotingRoundError::JUSTIFICATION_FOR_AUTHORITY_SET_IN_PAST)); return; } if (authority_set->id == current_round_->voterSetId() && justification.round_number < current_round_->roundNumber()) { if (not isWestendPastRound(block_tree_->getGenesisBlockHash(), justification.block_info)) { - callbackCall(std::move(callback), - VotingRoundError::JUSTIFICATION_FOR_ROUND_IN_PAST); + callbackCall( + std::move(callback), + Q_ERROR(VotingRoundError::JUSTIFICATION_FOR_ROUND_IN_PAST)); return; } } diff --git a/core/consensus/grandpa/impl/voting_round_impl.cpp b/core/consensus/grandpa/impl/voting_round_impl.cpp index b75c1be3ce..4584c8a872 100644 --- a/core/consensus/grandpa/impl/voting_round_impl.cpp +++ b/core/consensus/grandpa/impl/voting_round_impl.cpp @@ -733,14 +733,14 @@ namespace kagome::consensus::grandpa { BOOST_ASSERT(finalized_.has_value()); } else { - return VotingRoundError::ROUND_IS_NOT_FINALIZABLE; + return Q_ERROR(VotingRoundError::ROUND_IS_NOT_FINALIZABLE); } } if (not env_->hasAncestry(justification.block_info.hash, finalized_.value().hash)) { - return VotingRoundError:: - JUSTIFIED_BLOCK_IS_GREATER_THAN_ACTUALLY_FINALIZED; + return Q_ERROR( + VotingRoundError::JUSTIFIED_BLOCK_IS_GREATER_THAN_ACTUALLY_FINALIZED); } auto finalized = env_->finalize(voter_set_->id(), justification); @@ -783,7 +783,7 @@ namespace kagome::consensus::grandpa { "Round #{}: Precommit signed by {} was rejected: invalid signature", round_number_, signed_precommit.id); - return VotingRoundError::INVALID_SIGNATURE; + return Q_ERROR(VotingRoundError::INVALID_SIGNATURE); } // check that every signed precommit corresponds to the vote (i.e. @@ -833,7 +833,7 @@ namespace kagome::consensus::grandpa { "Round #{}: Received third precommit of caught equivocator from {}", round_number_, signed_precommit.id); - return VotingRoundError::REDUNDANT_EQUIVOCATION; + return Q_ERROR(VotingRoundError::REDUNDANT_EQUIVOCATION); } } @@ -844,7 +844,7 @@ namespace kagome::consensus::grandpa { round_number_, total_weight, threshold); - return VotingRoundError::NOT_ENOUGH_WEIGHT; + return Q_ERROR(VotingRoundError::NOT_ENOUGH_WEIGHT); } return outcome::success(); @@ -975,19 +975,18 @@ namespace kagome::consensus::grandpa { if (auto result = onSigned(grandpa_context, prevote); result.has_failure()) { - if (result == outcome::failure(VotingRoundError::DUPLICATED_VOTE)) { + if (result.error().ec(VotingRoundError::DUPLICATED_VOTE)) { return false; } - if (result - == outcome::failure(VotingRoundError::VOTE_OF_KNOWN_EQUIVOCATOR)) { + if (result.error().ec(VotingRoundError::VOTE_OF_KNOWN_EQUIVOCATOR)) { return false; } - if (result == outcome::failure(VotingRoundError::UNKNOWN_VOTER)) { + if (result.error().ec(VotingRoundError::UNKNOWN_VOTER)) { if (grandpa_context) { grandpa_context->unknown_voter_counter++; } } - if (result != outcome::failure(VotingRoundError::EQUIVOCATED_VOTE)) { + if (not result.error().ec(VotingRoundError::EQUIVOCATED_VOTE)) { logger_->warn("Round #{}: Prevote signed by {} was rejected: {}", round_number_, prevote.id, @@ -1042,14 +1041,13 @@ namespace kagome::consensus::grandpa { if (auto result = onSigned(grandpa_context, precommit); result.has_failure()) { - if (result == outcome::failure(VotingRoundError::DUPLICATED_VOTE)) { + if (result.error().ec(VotingRoundError::DUPLICATED_VOTE)) { return false; } - if (result - == outcome::failure(VotingRoundError::VOTE_OF_KNOWN_EQUIVOCATOR)) { + if (result.error().ec(VotingRoundError::VOTE_OF_KNOWN_EQUIVOCATOR)) { return false; } - if (result != outcome::failure(VotingRoundError::EQUIVOCATED_VOTE)) { + if (not result.error().ec(VotingRoundError::EQUIVOCATED_VOTE)) { logger_->warn("Round #{}: Precommit signed by {} was rejected: {}", round_number_, precommit.id, @@ -1157,7 +1155,7 @@ namespace kagome::consensus::grandpa { if (!index_and_weight_opt) { SL_DEBUG( logger_, "Voter {} is not in the current voter set", vote.id.toHex()); - return VotingRoundError::UNKNOWN_VOTER; + return Q_ERROR(VotingRoundError::UNKNOWN_VOTER); } const auto &[index, weight] = index_and_weight_opt.value(); @@ -1181,12 +1179,12 @@ namespace kagome::consensus::grandpa { // Ignore known equivocators if (equivocators[index]) { - return VotingRoundError::VOTE_OF_KNOWN_EQUIVOCATOR; + return Q_ERROR(VotingRoundError::VOTE_OF_KNOWN_EQUIVOCATOR); } // Ignore zero-weight voter if (weight == 0) { - return VotingRoundError::ZERO_WEIGHT_VOTER; + return Q_ERROR(VotingRoundError::ZERO_WEIGHT_VOTER); } auto push_res = tracker.push(vote, weight); @@ -1198,9 +1196,7 @@ namespace kagome::consensus::grandpa { auto log_lvl = log::Level::WARN; // TODO(Harrm): this looks like a kind of a crutch, // think of a better way to pass this information - if (result - == outcome::failure( - blockchain::BlockTreeError::HEADER_NOT_FOUND)) { + if (result.error().ec(blockchain::BlockTreeError::HEADER_NOT_FOUND)) { if (grandpa_context) { grandpa_context->missing_blocks.emplace(vote.getBlockInfo()); log_lvl = log::Level::DEBUG; @@ -1218,12 +1214,12 @@ namespace kagome::consensus::grandpa { return outcome::success(); } case VoteTracker::PushResult::DUPLICATED: { - return VotingRoundError::DUPLICATED_VOTE; + return Q_ERROR(VotingRoundError::DUPLICATED_VOTE); } case VoteTracker::PushResult::EQUIVOCATED: { equivocators[index] = true; graph_->remove(type, vote.id); - return VotingRoundError::EQUIVOCATED_VOTE; + return Q_ERROR(VotingRoundError::EQUIVOCATED_VOTE); } default: BOOST_UNREACHABLE_RETURN({}); diff --git a/core/consensus/grandpa/vote_graph/vote_graph_error.hpp b/core/consensus/grandpa/vote_graph/vote_graph_error.hpp index 3f18969908..077f0c5212 100644 --- a/core/consensus/grandpa/vote_graph/vote_graph_error.hpp +++ b/core/consensus/grandpa/vote_graph/vote_graph_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::consensus::grandpa { diff --git a/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp b/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp index d3eb02cfa0..45c2f1e034 100644 --- a/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp +++ b/core/consensus/grandpa/vote_graph/vote_graph_impl.cpp @@ -96,7 +96,7 @@ namespace kagome::consensus::grandpa { const Id &voter) { auto inw_res = voter_set_->indexAndWeight(voter); if (!inw_res.has_value()) { - return VotingRoundError::UNKNOWN_VOTER; + return Q_ERROR(VotingRoundError::UNKNOWN_VOTER); } const auto [index, weight] = inw_res.value(); @@ -144,7 +144,7 @@ namespace kagome::consensus::grandpa { return outcome::success(); } if (base_.number > block.number) { - return VoteGraphError::RECEIVED_BLOCK_LESS_THAN_BASE; + return Q_ERROR(VoteGraphError::RECEIVED_BLOCK_LESS_THAN_BASE); } OUTCOME_TRY(ancestry, chain_->getAncestry(base_.hash, block.hash)); diff --git a/core/consensus/grandpa/voter_set.cpp b/core/consensus/grandpa/voter_set.cpp index 996f5e4fe1..93c9d7620b 100644 --- a/core/consensus/grandpa/voter_set.cpp +++ b/core/consensus/grandpa/voter_set.cpp @@ -45,12 +45,12 @@ namespace kagome::consensus::grandpa { total_weight_ += weight; return outcome::success(); } - return Error::VOTER_ALREADY_EXISTS; + return Q_ERROR(Error::VOTER_ALREADY_EXISTS); } outcome::result VoterSet::voterId(Index index) const { if (index >= list_.size()) { - return Error::INDEX_OUTBOUND; + return Q_ERROR(Error::INDEX_OUTBOUND); } auto voter = std::get<0>(list_[index]); return voter; @@ -99,7 +99,7 @@ namespace kagome::consensus::grandpa { outcome::result VoterSet::voterWeight(Index index) const { if (index >= list_.size()) { - return Error::INDEX_OUTBOUND; + return Q_ERROR(Error::INDEX_OUTBOUND); } auto weight = std::get<1>(list_.at(index)); return weight; diff --git a/core/consensus/grandpa/voting_round_error.hpp b/core/consensus/grandpa/voting_round_error.hpp index 3d183917ab..c5415ea00b 100644 --- a/core/consensus/grandpa/voting_round_error.hpp +++ b/core/consensus/grandpa/voting_round_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::consensus::grandpa { diff --git a/core/consensus/timeline/impl/block_addition_error.hpp b/core/consensus/timeline/impl/block_addition_error.hpp index a7adf14439..ce33847015 100644 --- a/core/consensus/timeline/impl/block_addition_error.hpp +++ b/core/consensus/timeline/impl/block_addition_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::consensus { diff --git a/core/consensus/timeline/impl/block_appender_base.cpp b/core/consensus/timeline/impl/block_appender_base.cpp index 48d72a92d0..f0941f3a57 100644 --- a/core/consensus/timeline/impl/block_appender_base.cpp +++ b/core/consensus/timeline/impl/block_appender_base.cpp @@ -92,8 +92,7 @@ namespace kagome::consensus { // One of the reasons for this error is the presence of // preliminary votes for future blocks that have not yet been // applied. - if (result - == outcome::failure( + if (result.error().ec( grandpa::VotingRoundError::NOT_ENOUGH_WEIGHT)) { pp->emplace(block_info, justification); if (auto logger = wlogger.lock()) { @@ -101,7 +100,7 @@ namespace kagome::consensus { logger, "Postpone justification received for block {}: {}", block_info, - result); + result.error()); } } else { if (auto logger = wlogger.lock()) { diff --git a/core/consensus/timeline/impl/block_executor_impl.cpp b/core/consensus/timeline/impl/block_executor_impl.cpp index 7174d0333c..c09ef40eeb 100644 --- a/core/consensus/timeline/impl/block_executor_impl.cpp +++ b/core/consensus/timeline/impl/block_executor_impl.cpp @@ -71,9 +71,10 @@ namespace kagome::consensus { auto block_info = block.header.blockInfo(); if (auto header_res = block_tree_->getBlockHeader(block.header.parent_hash); header_res.has_error() - && header_res.error() == blockchain::BlockTreeError::HEADER_NOT_FOUND) { + && header_res.error().ec( + blockchain::BlockTreeError::HEADER_NOT_FOUND)) { logger_->warn("Skipping a block {} with unknown parent", block_info); - callback(BlockAdditionError::PARENT_NOT_FOUND); + callback(Q_ERROR(BlockAdditionError::PARENT_NOT_FOUND)); return; } else if (header_res.has_error()) { callback(header_res.as_failure()); @@ -97,7 +98,8 @@ namespace kagome::consensus { return; } block_was_applied_earlier = true; - } else if (body_res.error() != blockchain::BlockTreeError::BODY_NOT_FOUND) { + } else if (not body_res.error().ec( + blockchain::BlockTreeError::BODY_NOT_FOUND)) { callback(body_res.as_failure()); return; } @@ -222,10 +224,8 @@ namespace kagome::consensus { extrinsic_hash); auto res = self->tx_pool_->removeOne(extrinsic_hash); if (res.has_error() - && res - != outcome::failure( - transaction_pool::TransactionPoolError:: - TX_NOT_FOUND)) { + && not res.error().ec( + transaction_pool::TransactionPoolError::TX_NOT_FOUND)) { callback(res.as_failure()); return; } diff --git a/core/consensus/timeline/impl/block_header_appender_impl.cpp b/core/consensus/timeline/impl/block_header_appender_impl.cpp index 44fe08d85e..1d13510903 100644 --- a/core/consensus/timeline/impl/block_header_appender_impl.cpp +++ b/core/consensus/timeline/impl/block_header_appender_impl.cpp @@ -55,10 +55,10 @@ namespace kagome::consensus { if (auto header_res = block_tree_->getBlockHeader(block_header.parent_hash); header_res.has_error() - && header_res.error() - == blockchain::BlockTreeError::HEADER_NOT_FOUND) { + && header_res.error().ec( + blockchain::BlockTreeError::HEADER_NOT_FOUND)) { logger_->warn("Skipping a block {} with unknown parent", block_info); - callback(BlockAdditionError::PARENT_NOT_FOUND); + callback(Q_ERROR(BlockAdditionError::PARENT_NOT_FOUND)); return; } else if (header_res.has_error()) { callback(header_res.as_failure()); @@ -82,8 +82,8 @@ namespace kagome::consensus { callback(res.as_failure()); return; } - } else if (header_res.error() - != blockchain::BlockTreeError::HEADER_NOT_FOUND) { + } else if (not header_res.error().ec( + blockchain::BlockTreeError::HEADER_NOT_FOUND)) { callback(header_res.as_failure()); return; } else { @@ -108,7 +108,7 @@ namespace kagome::consensus { callback{std::move(callback)}](auto &&result) mutable { auto self = wself.lock(); if (!self) { - callback(BlockAdditionError::NO_INSTANCE); + callback(Q_ERROR(BlockAdditionError::NO_INSTANCE)); return; } auto const now = std::chrono::high_resolution_clock::now(); diff --git a/core/consensus/timeline/impl/block_production_error.hpp b/core/consensus/timeline/impl/block_production_error.hpp index 4f3856d2fe..2f4aa403b2 100644 --- a/core/consensus/timeline/impl/block_production_error.hpp +++ b/core/consensus/timeline/impl/block_production_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::consensus { diff --git a/core/consensus/timeline/impl/slots_util_impl.cpp b/core/consensus/timeline/impl/slots_util_impl.cpp index 24a5f81d11..f2342a8dbf 100644 --- a/core/consensus/timeline/impl/slots_util_impl.cpp +++ b/core/consensus/timeline/impl/slots_util_impl.cpp @@ -86,7 +86,7 @@ namespace kagome ::consensus { [[unlikely]] if (parent_info.number == 0) { return 0; } OUTCOME_TRY(slot1, getFirstBlockSlotNumber(parent_info)); if (slot < slot1) { - return TimelineError::SLOT_BEFORE_GENESIS; + return Q_ERROR(TimelineError::SLOT_BEFORE_GENESIS); } auto slots = slot - slot1; return slots / epochLength(); diff --git a/core/consensus/timeline/impl/timeline_error.hpp b/core/consensus/timeline/impl/timeline_error.hpp index bd00ce581a..ddd29d97ef 100644 --- a/core/consensus/timeline/impl/timeline_error.hpp +++ b/core/consensus/timeline/impl/timeline_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::consensus { diff --git a/core/consensus/timeline/impl/timeline_impl.cpp b/core/consensus/timeline/impl/timeline_impl.cpp index 53bbfd4f81..d600f4bfdd 100644 --- a/core/consensus/timeline/impl/timeline_impl.cpp +++ b/core/consensus/timeline/impl/timeline_impl.cpp @@ -721,8 +721,9 @@ namespace kagome::consensus { } } - static const auto &block_production_error_category = - make_error_code(BlockProductionError{}).category(); + auto is_block_production_error = [](const qtils::Error &error) { + return error.ec(); + }; /// Try to run block production here auto consensus = consensus_selector_->getProductionConsensus(best_block_); @@ -732,8 +733,7 @@ namespace kagome::consensus { "Slot {} in epoch {} has processed", current_slot_, current_epoch_); - } else if (res.as_failure().error().category() - == block_production_error_category) { + } else if (res.error().find(is_block_production_error)) { SL_DEBUG(log_, "Processing of slot {} was skipped: {}", current_slot_, diff --git a/core/consensus/validation/babe_block_validator.cpp b/core/consensus/validation/babe_block_validator.cpp index 1916d99391..1783146d19 100644 --- a/core/consensus/validation/babe_block_validator.cpp +++ b/core/consensus/validation/babe_block_validator.cpp @@ -84,7 +84,7 @@ namespace kagome::consensus { header.blockInfo(), to_string(slot_type), to_string(babe_config.allowed_slots)); - return ValidationError::SECONDARY_SLOT_ASSIGNMENTS_DISABLED; + return Q_ERROR(ValidationError::SECONDARY_SLOT_ASSIGNMENTS_DISABLED); } } @@ -95,7 +95,7 @@ namespace kagome::consensus { babe_header, seal, primitives::BabeSessionKey{authority_id.id})) { - return ValidationError::INVALID_SIGNATURE; + return Q_ERROR(ValidationError::INVALID_SIGNATURE); } // VRF must prove that the peer is the leader of the slot @@ -106,7 +106,7 @@ namespace kagome::consensus { threshold, babe_config.randomness, babe_header.needVRFWithThresholdCheck())) { - return ValidationError::INVALID_VRF; + return Q_ERROR(ValidationError::INVALID_VRF); } return outcome::success(); diff --git a/core/crypto/bip39/dictionary.cpp b/core/crypto/bip39/dictionary.cpp index 6f2a08dc31..5b631a1303 100644 --- a/core/crypto/bip39/dictionary.cpp +++ b/core/crypto/bip39/dictionary.cpp @@ -26,7 +26,7 @@ namespace kagome::crypto::bip39 { return loc->second; } - return DictionaryError::ENTRY_NOT_FOUND; + return Q_ERROR(DictionaryError::ENTRY_NOT_FOUND); } } // namespace kagome::crypto::bip39 diff --git a/core/crypto/bip39/dictionary.hpp b/core/crypto/bip39/dictionary.hpp index c786209685..e2b07198ac 100644 --- a/core/crypto/bip39/dictionary.hpp +++ b/core/crypto/bip39/dictionary.hpp @@ -9,6 +9,7 @@ #include "crypto/bip39/entropy_accumulator.hpp" #include "outcome/outcome.hpp" +#include #include namespace kagome::crypto::bip39 { diff --git a/core/crypto/bip39/entropy_accumulator.cpp b/core/crypto/bip39/entropy_accumulator.cpp index 59773b1e6f..ad3b07b03b 100644 --- a/core/crypto/bip39/entropy_accumulator.cpp +++ b/core/crypto/bip39/entropy_accumulator.cpp @@ -25,12 +25,12 @@ namespace kagome::crypto::bip39 { default: break; } - return Bip39EntropyError::WRONG_WORDS_COUNT; + return Q_ERROR(Bip39EntropyError::WRONG_WORDS_COUNT); } outcome::result> EntropyAccumulator::getEntropy() const { if (bits_.size() != total_bits_count_) { - return Bip39EntropyError::STORAGE_NOT_COMPLETE; + return Q_ERROR(Bip39EntropyError::STORAGE_NOT_COMPLETE); } // convert data @@ -53,7 +53,7 @@ namespace kagome::crypto::bip39 { outcome::result EntropyAccumulator::getChecksum() const { if (bits_.size() != total_bits_count_) { - return Bip39EntropyError::STORAGE_NOT_COMPLETE; + return Q_ERROR(Bip39EntropyError::STORAGE_NOT_COMPLETE); } uint8_t checksum = 0u; @@ -67,7 +67,7 @@ namespace kagome::crypto::bip39 { outcome::result EntropyAccumulator::append(const EntropyToken &value) { if (bits_.size() + value.size() > total_bits_count_) { - return Bip39EntropyError::STORAGE_IS_FULL; + return Q_ERROR(Bip39EntropyError::STORAGE_IS_FULL); } for (size_t i = 0; i < value.size(); ++i) { diff --git a/core/crypto/bip39/entropy_accumulator.hpp b/core/crypto/bip39/entropy_accumulator.hpp index 854f9f39c6..28ed360edf 100644 --- a/core/crypto/bip39/entropy_accumulator.hpp +++ b/core/crypto/bip39/entropy_accumulator.hpp @@ -10,6 +10,7 @@ #include "outcome/outcome.hpp" #include +#include #include namespace kagome::crypto::bip39 { diff --git a/core/crypto/bip39/impl/bip39_provider_impl.cpp b/core/crypto/bip39/impl/bip39_provider_impl.cpp index 6cbf673b12..1ab92908c0 100644 --- a/core/crypto/bip39/impl/bip39_provider_impl.cpp +++ b/core/crypto/bip39/impl/bip39_provider_impl.cpp @@ -53,7 +53,7 @@ namespace kagome::crypto { OUTCOME_TRY(calculated_checksum, entropy_accumulator.calculateChecksum()); if (mnemonic_checksum != calculated_checksum) { - return bip39::MnemonicError::INVALID_MNEMONIC; + return Q_ERROR(bip39::MnemonicError::INVALID_MNEMONIC); } // finally get entropy diff --git a/core/crypto/bip39/mnemonic.cpp b/core/crypto/bip39/mnemonic.cpp index d7a4e0518a..d34e879c7d 100644 --- a/core/crypto/bip39/mnemonic.cpp +++ b/core/crypto/bip39/mnemonic.cpp @@ -50,7 +50,7 @@ namespace kagome::crypto::bip39 { outcome::result Mnemonic::parse(std::string_view phrase) { if (!isValidUtf8(std::string(phrase))) { - return bip39::MnemonicError::INVALID_MNEMONIC; + return Q_ERROR(bip39::MnemonicError::INVALID_MNEMONIC); } Mnemonic mnemonic; diff --git a/core/crypto/crypto_store/crypto_store_impl.cpp b/core/crypto/crypto_store/crypto_store_impl.cpp index 64a51c958e..18dd146391 100644 --- a/core/crypto/crypto_store/crypto_store_impl.cpp +++ b/core/crypto/crypto_store/crypto_store_impl.cpp @@ -130,7 +130,7 @@ namespace kagome::crypto { } OUTCOME_TRY(phrase, file_storage_->searchForPhrase(key_type, pk)); if (not phrase) { - return CryptoStoreError::KEY_NOT_FOUND; + return Q_ERROR(CryptoStoreError::KEY_NOT_FOUND); } OUTCOME_TRY(bip, bip39_provider_->generateSeed(*phrase)); return ecdsa_suite_->generateKeypair(bip); @@ -144,7 +144,7 @@ namespace kagome::crypto { } OUTCOME_TRY(phrase, file_storage_->searchForPhrase(key_type, pk)); if (not phrase) { - return CryptoStoreError::KEY_NOT_FOUND; + return Q_ERROR(CryptoStoreError::KEY_NOT_FOUND); } OUTCOME_TRY(bip, bip39_provider_->generateSeed(*phrase)); return ed_suite_->generateKeypair(bip); @@ -158,7 +158,7 @@ namespace kagome::crypto { } OUTCOME_TRY(phrase, file_storage_->searchForPhrase(key_type, pk)); if (not phrase) { - return CryptoStoreError::KEY_NOT_FOUND; + return Q_ERROR(CryptoStoreError::KEY_NOT_FOUND); } OUTCOME_TRY(bip, bip39_provider_->generateSeed(*phrase)); return sr_suite_->generateKeypair(bip); @@ -187,7 +187,7 @@ namespace kagome::crypto { const CryptoStore::Path &key_path) const { std::string contents; if (not readFile(contents, key_path.string())) { - return CryptoStoreError::KEY_NOT_FOUND; + return Q_ERROR(CryptoStoreError::KEY_NOT_FOUND); } BOOST_ASSERT(ED25519_SEED_LENGTH == contents.size() or 2 * ED25519_SEED_LENGTH == contents.size()); // hex @@ -199,7 +199,7 @@ namespace kagome::crypto { OUTCOME_TRY(_seed, Ed25519Seed::fromHex(contents)); seed = _seed; } else { - return CryptoStoreError::UNSUPPORTED_CRYPTO_TYPE; + return Q_ERROR(CryptoStoreError::UNSUPPORTED_CRYPTO_TYPE); } OUTCOME_TRY(kp, ed_suite_->generateKeypair(seed, {})); return ed25519KeyToLibp2pKeypair(kp); diff --git a/core/crypto/crypto_store/key_file_storage.cpp b/core/crypto/crypto_store/key_file_storage.cpp index 97958c830d..95d2184c66 100644 --- a/core/crypto/crypto_store/key_file_storage.cpp +++ b/core/crypto/crypto_store/key_file_storage.cpp @@ -84,25 +84,25 @@ namespace kagome::crypto { bool does_exist = filesystem::exists(keystore_path_, ec); if (ec and ec != std::errc::no_such_file_or_directory) { logger_->error("Error initializing key storage: {}", ec); - return outcome::failure(ec); + return Q_ERROR(ec); } if (does_exist) { // check whether specified path is a directory if (not filesystem::is_directory(keystore_path_, ec)) { - return Error::KEYS_PATH_IS_NOT_DIRECTORY; + return Q_ERROR(Error::KEYS_PATH_IS_NOT_DIRECTORY); } if (ec) { logger_->error("Error scanning key storage: {}", ec); - return outcome::failure(ec); + return Q_ERROR(ec); } } else { // try create directory if (not filesystem::create_directories(keystore_path_, ec)) { - return Error::FAILED_CREATE_KEYS_DIRECTORY; + return Q_ERROR(Error::FAILED_CREATE_KEYS_DIRECTORY); } if (ec) { logger_->error("Error creating keystore dir: {}", ec); - return outcome::failure(ec); + return Q_ERROR(ec); } } @@ -114,7 +114,7 @@ namespace kagome::crypto { std::ofstream file; file.open(path.native(), std::ios::out | std::ios::trunc); if (!file.is_open()) { - return Error::FAILED_OPEN_FILE; + return Q_ERROR(Error::FAILED_OPEN_FILE); } auto hex = common::hex_lower_0x(private_key); file << hex; @@ -133,7 +133,7 @@ namespace kagome::crypto { fs::directory_iterator it{keystore_path_, ec}, end{}; if (ec) { logger_->error("Error scanning keystore: {}", ec); - return Error::FAILED_OPEN_FILE; + return Q_ERROR(Error::FAILED_OPEN_FILE); } for (; it != end; ++it) { if (!fs::is_regular_file(*it)) { @@ -169,7 +169,7 @@ namespace kagome::crypto { if (auto str = jsonUnquote(content)) { return str; } - return Error::INVALID_FILE_FORMAT; + return Q_ERROR(Error::INVALID_FILE_FORMAT); } OUTCOME_TRY(common::unhexWith0x(content)); return content; diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.cpp b/core/crypto/ecdsa/ecdsa_provider_impl.cpp index f92d53cc3d..3e45d50d81 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.cpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.cpp @@ -39,7 +39,7 @@ namespace kagome::crypto { auto seed = _seed; for (auto &junction : junctions) { if (not junction.hard) { - return Error::SOFT_JUNCTION_NOT_SUPPORTED; + return Q_ERROR(Error::SOFT_JUNCTION_NOT_SUPPORTED); } seed = hasher_->blake2b_256( scale::encode("Secp256k1HDKD"_bytes, seed, junction.cc).value()); @@ -50,7 +50,7 @@ namespace kagome::crypto { if (secp256k1_ec_pubkey_create( context_.get(), &ffi_pub, keys.secret_key.data()) == 0) { - return Error::DERIVE_FAILED; + return Q_ERROR(Error::DERIVE_FAILED); } size_t size = EcdsaPublicKey::size(); if (secp256k1_ec_pubkey_serialize(context_.get(), @@ -59,7 +59,7 @@ namespace kagome::crypto { &ffi_pub, SECP256K1_EC_COMPRESSED) == 0) { - return Error::DERIVE_FAILED; + return Q_ERROR(Error::DERIVE_FAILED); } return keys; } @@ -79,14 +79,14 @@ namespace kagome::crypto { secp256k1_nonce_function_rfc6979, nullptr) == 0) { - return Error::SIGN_FAILED; + return Q_ERROR(Error::SIGN_FAILED); } EcdsaSignature sig{}; int recid = 0; if (secp256k1_ecdsa_recoverable_signature_serialize_compact( context_.get(), sig.data(), &recid, &ffi_sig) == 0) { - return Error::SIGN_FAILED; + return Q_ERROR(Error::SIGN_FAILED); } sig[64] = static_cast(recid); return sig; diff --git a/core/crypto/ed25519/ed25519_provider_impl.cpp b/core/crypto/ed25519/ed25519_provider_impl.cpp index a2835c50b4..ac59537eb7 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.cpp +++ b/core/crypto/ed25519/ed25519_provider_impl.cpp @@ -36,7 +36,7 @@ namespace kagome::crypto { auto seed = _seed; for (auto &junction : junctions) { if (not junction.hard) { - return Error::SOFT_JUNCTION_NOT_SUPPORTED; + return Q_ERROR(Error::SOFT_JUNCTION_NOT_SUPPORTED); } seed = hasher_->blake2b_256( scale::encode("Ed25519HDKD"_bytes, seed, junction.cc).value()); @@ -68,7 +68,7 @@ namespace kagome::crypto { SL_ERROR(logger_, "Error during ed25519 sign; error code: {}", static_cast(res)); - return Error::SIGN_FAILED; + return Q_ERROR(Error::SIGN_FAILED); } return sig; } @@ -89,6 +89,6 @@ namespace kagome::crypto { SL_ERROR(logger_, "Error verifying a signature; error code: {}", static_cast(res)); - return Error::VERIFICATION_FAILED; + return Q_ERROR(Error::VERIFICATION_FAILED); } } // namespace kagome::crypto diff --git a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp index 1ddb5d59e7..5c2f24516f 100644 --- a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp +++ b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp @@ -29,7 +29,7 @@ namespace kagome::crypto { key_length, out.data()); if (res != 1) { - return Pbkdf2ProviderError::KEY_DERIVATION_FAILED; + return Q_ERROR(Pbkdf2ProviderError::KEY_DERIVATION_FAILED); } return out; diff --git a/core/crypto/secp256k1/secp256k1_provider_impl.cpp b/core/crypto/secp256k1/secp256k1_provider_impl.cpp index bfe916460e..2fd8e58137 100644 --- a/core/crypto/secp256k1/secp256k1_provider_impl.cpp +++ b/core/crypto/secp256k1/secp256k1_provider_impl.cpp @@ -29,7 +29,7 @@ namespace kagome::crypto { &outputlen, &pubkey, SECP256K1_EC_UNCOMPRESSED)) { - return Secp256k1ProviderError::RECOVERY_FAILED; + return Q_ERROR(Secp256k1ProviderError::RECOVERY_FAILED); } return pubkey_out; @@ -49,7 +49,7 @@ namespace kagome::crypto { &outputlen, &pubkey, SECP256K1_EC_COMPRESSED)) { - return Secp256k1ProviderError::RECOVERY_FAILED; + return Q_ERROR(Secp256k1ProviderError::RECOVERY_FAILED); } return pubkey_out; @@ -72,7 +72,7 @@ namespace kagome::crypto { recovery_id = 1; break; default: - return Secp256k1ProviderError::INVALID_V_VALUE; + return Q_ERROR(Secp256k1ProviderError::INVALID_V_VALUE); } return recovery_id; } @@ -88,13 +88,13 @@ namespace kagome::crypto { if (1 != secp256k1_ecdsa_recoverable_signature_parse_compact( context_.get(), &sig_rec, signature.data(), rec_id)) { - return Secp256k1ProviderError::INVALID_R_OR_S_VALUE; + return Q_ERROR(Secp256k1ProviderError::INVALID_R_OR_S_VALUE); } if (1 != secp256k1_ecdsa_recover( context_.get(), &pubkey, &sig_rec, message_hash.data())) { - return Secp256k1ProviderError::INVALID_SIGNATURE; + return Q_ERROR(Secp256k1ProviderError::INVALID_SIGNATURE); } return pubkey; diff --git a/core/crypto/sr25519/sr25519_provider_impl.cpp b/core/crypto/sr25519/sr25519_provider_impl.cpp index c77457a2c6..af72c2bb35 100644 --- a/core/crypto/sr25519/sr25519_provider_impl.cpp +++ b/core/crypto/sr25519/sr25519_provider_impl.cpp @@ -43,7 +43,7 @@ namespace kagome::crypto { message.data(), message.size()); } catch (...) { - return Sr25519ProviderError::SIGN_UNKNOWN_ERROR; + return Q_ERROR(Sr25519ProviderError::SIGN_UNKNOWN_ERROR); } return signature; @@ -58,7 +58,7 @@ namespace kagome::crypto { result = sr25519_verify_deprecated( signature.data(), message.data(), message.size(), public_key.data()); } catch (...) { - return Sr25519ProviderError::SIGN_UNKNOWN_ERROR; + return Q_ERROR(Sr25519ProviderError::SIGN_UNKNOWN_ERROR); } return result; } @@ -72,7 +72,7 @@ namespace kagome::crypto { result = sr25519_verify( signature.data(), message.data(), message.size(), public_key.data()); } catch (...) { - return Sr25519ProviderError::SIGN_UNKNOWN_ERROR; + return Q_ERROR(Sr25519ProviderError::SIGN_UNKNOWN_ERROR); } return outcome::success(result); } diff --git a/core/dispute_coordinator/impl/batches.cpp b/core/dispute_coordinator/impl/batches.cpp index 3d54cc303b..9f3284f082 100644 --- a/core/dispute_coordinator/impl/batches.cpp +++ b/core/dispute_coordinator/impl/batches.cpp @@ -25,7 +25,7 @@ namespace kagome::dispute { } if (batches_.size() >= 1000 /* kMaxBatchSize */) { // FIXME - return BatchError::MaxBatchLimitReached; + return Q_ERROR(BatchError::MaxBatchLimitReached); } auto batch = diff --git a/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp b/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp index 17d1ffd229..c90feda409 100644 --- a/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp +++ b/core/dispute_coordinator/impl/dispute_coordinator_impl.cpp @@ -24,6 +24,7 @@ #include "dispute_coordinator/participation/impl/participation_impl.hpp" #include "dispute_coordinator/provisioner/impl/prioritized_selection.hpp" #include "dispute_coordinator/provisioner/impl/random_selection.hpp" +#include "log/formatters/boost_ec.hpp" #include "network/router.hpp" #include "network/types/dispute_messages.hpp" #include "parachain/approval/approval_distribution.hpp" @@ -696,7 +697,7 @@ namespace kagome::dispute { "Missing public key for validator #{} that " "participated in concluded dispute", validator_index); - return SignatureValidationError::MissingPublicKey; + return Q_ERROR(SignatureValidationError::MissingPublicKey); } ValidatorId validator_public = @@ -1540,7 +1541,7 @@ namespace kagome::dispute { auto get_other_vote = [&](auto &some_kind_votes) -> outcome::result { if (some_kind_votes.empty()) { - return DisputeMessageCreationError::NoOppositeVote; + return Q_ERROR(DisputeMessageCreationError::NoOppositeVote); } auto it = some_kind_votes.begin(); @@ -1549,7 +1550,7 @@ namespace kagome::dispute { auto &[statement_kind, validator_signature] = it->second; if (validator_index >= validators.size()) { - return DisputeMessageCreationError::InvalidValidatorIndex; + return Q_ERROR(DisputeMessageCreationError::InvalidValidatorIndex); } auto validator_public = validators[validator_index]; @@ -1567,7 +1568,7 @@ namespace kagome::dispute { return validation_res.as_failure(); } if (not validation_res.value()) { - return DisputeMessageCreationError::InvalidStoredStatement; + return Q_ERROR(DisputeMessageCreationError::InvalidStoredStatement); } // make other signed statement @@ -1601,48 +1602,50 @@ namespace kagome::dispute { auto candidate_hash = valid_statement.candidate_hash; // Check statements concern same candidate: if (candidate_hash != invalid_statement.candidate_hash) { - return DisputeMessageConstructingError::CandidateHashMismatch; + return Q_ERROR(DisputeMessageConstructingError::CandidateHashMismatch); } auto session_index = valid_statement.session_index; if (session_index != invalid_statement.session_index) { - return DisputeMessageConstructingError::SessionIndexMismatch; + return Q_ERROR(DisputeMessageConstructingError::SessionIndexMismatch); } if (valid_index >= session_info.validators.size()) { - return DisputeMessageConstructingError:: - ValidStatementInvalidValidatorIndex; + return Q_ERROR( + DisputeMessageConstructingError::ValidStatementInvalidValidatorIndex); } if (invalid_index >= session_info.validators.size()) { - return DisputeMessageConstructingError:: - InvalidStatementInvalidValidatorIndex; + return Q_ERROR(DisputeMessageConstructingError:: + InvalidStatementInvalidValidatorIndex); } auto &valid_id = session_info.validators[valid_index]; if (valid_id != valid_statement.validator_public) { - return DisputeMessageConstructingError::InvalidValidKey; + return Q_ERROR(DisputeMessageConstructingError::InvalidValidKey); } auto &invalid_id = session_info.validators[invalid_index]; if (invalid_id != invalid_statement.validator_public) { - return DisputeMessageConstructingError::InvalidInvalidKey; + return Q_ERROR(DisputeMessageConstructingError::InvalidInvalidKey); } if (candidate_receipt.hash(*hasher_) != candidate_hash) { - return DisputeMessageConstructingError::InvalidCandidateReceipt; + return Q_ERROR(DisputeMessageConstructingError::InvalidCandidateReceipt); } auto valid_kind_opt = if_type(valid_statement.dispute_statement); if (not valid_kind_opt.has_value()) { - return DisputeMessageConstructingError::ValidStatementHasInvalidKind; + return Q_ERROR( + DisputeMessageConstructingError::ValidStatementHasInvalidKind); } auto &valid_kind = valid_kind_opt->get(); auto invalid_kind_opt = if_type(invalid_statement.dispute_statement); if (not invalid_kind_opt.has_value()) { - return DisputeMessageConstructingError::InvalidStatementHasValidKind; + return Q_ERROR( + DisputeMessageConstructingError::InvalidStatementHasValidKind); } auto &invalid_kind = invalid_kind_opt->get(); @@ -1875,7 +1878,7 @@ namespace kagome::dispute { // Return error if session information is missing. if (error_.has_value()) { - return cb(SessionObtainingError::SessionsUnavailable); + return cb(Q_ERROR(SessionObtainingError::SessionsUnavailable)); } SL_TRACE(log_, "Loading recent disputes from db"); @@ -1909,7 +1912,7 @@ namespace kagome::dispute { // Return error if session information is missing. if (error_.has_value()) { - return cb(SessionObtainingError::SessionsUnavailable); + return cb(Q_ERROR(SessionObtainingError::SessionsUnavailable)); } SL_TRACE(log_, "DisputeCoordinatorMessage::ActiveDisputes"); @@ -1960,7 +1963,7 @@ namespace kagome::dispute { // Return error if session information is missing. if (error_.has_value()) { - return cb(SessionObtainingError::SessionsUnavailable); + return cb(Q_ERROR(SessionObtainingError::SessionsUnavailable)); } SL_TRACE(log_, "DisputeCoordinatorMessage::QueryCandidateVotes"); @@ -2020,7 +2023,7 @@ namespace kagome::dispute { // Return error if session information is missing. if (error_.has_value()) { - return cb(SessionObtainingError::SessionsUnavailable); + return cb(Q_ERROR(SessionObtainingError::SessionsUnavailable)); } SL_TRACE(log_, "DisputeCoordinatorMessage::DetermineUndisputedChain"); @@ -2126,7 +2129,7 @@ namespace kagome::dispute { if (not authority_id_opt.has_value()) { SL_DEBUG(log_, "Peer {} is not validator - dropping message", peer_id); // TODO reputation_changes: vec![COST_NOT_A_VALIDATOR], - return sendDisputeResponse(DisputeProcessingError::NotAValidator, + return sendDisputeResponse(Q_ERROR(DisputeProcessingError::NotAValidator), std::move(cb)); } auto &authority_id = authority_id_opt.value(); @@ -2138,8 +2141,8 @@ namespace kagome::dispute { if (queue.size() >= kPeerQueueCapacity) { SL_DEBUG(log_, "Peer {} hit the rate limit - dropping message", peer_id); // TODO reputation_changes: vec![COST_APPARENT_FLOOD], - return sendDisputeResponse(DisputeProcessingError::AuthorityFlooding, - std::move(cb)); + return sendDisputeResponse( + Q_ERROR(DisputeProcessingError::AuthorityFlooding), std::move(cb)); } queue.emplace_back(request, std::move(cb)); @@ -2252,7 +2255,7 @@ namespace kagome::dispute { const auto &[validator_index, signature, kind] = unchecked_valid_vote; if (validator_index >= session_info.validators.size()) { // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], - return DisputeMessageCreationError::InvalidValidatorIndex; + return Q_ERROR(DisputeMessageCreationError::InvalidValidatorIndex); } auto validator_public = session_info.validators[validator_index]; @@ -2266,11 +2269,11 @@ namespace kagome::dispute { if (validation_res.has_error()) { // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], - return SignatureValidationError::InvalidSignature; + return Q_ERROR(SignatureValidationError::InvalidSignature); } if (not validation_res.value()) { // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], - return SignatureValidationError::InvalidSignature; + return Q_ERROR(SignatureValidationError::InvalidSignature); } checked_valid_vote = {{ @@ -2288,7 +2291,7 @@ namespace kagome::dispute { const auto &[validator_index, signature, kind] = unchecked_invalid_vote; if (validator_index >= session_info.validators.size()) { // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], - return DisputeMessageCreationError::InvalidValidatorIndex; + return Q_ERROR(DisputeMessageCreationError::InvalidValidatorIndex); } auto validator_public = session_info.validators[validator_index]; @@ -2302,11 +2305,11 @@ namespace kagome::dispute { if (validation_res.has_error()) { // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], - return SignatureValidationError::InvalidSignature; + return Q_ERROR(SignatureValidationError::InvalidSignature); } if (not validation_res.value()) { // TODO reputation_changes: vec![COST_INVALID_SIGNATURE], - return SignatureValidationError::InvalidSignature; + return Q_ERROR(SignatureValidationError::InvalidSignature); } checked_invalid_vote = {{ @@ -2369,7 +2372,7 @@ namespace kagome::dispute { // the worst. We don't want to push the pending response to the // batch either as that would be unbounded, only limited by the rate // limit. - (*cb_opt)(BatchError::RedundantMessage); + (*cb_opt)(Q_ERROR(BatchError::RedundantMessage)); } else { // FIXME testing code. must be removed auto prepared_import = diff --git a/core/dispute_coordinator/impl/errors.hpp b/core/dispute_coordinator/impl/errors.hpp index 9bdc468c00..594237a7f9 100644 --- a/core/dispute_coordinator/impl/errors.hpp +++ b/core/dispute_coordinator/impl/errors.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::dispute { diff --git a/core/dispute_coordinator/impl/rolling_session_window_impl.cpp b/core/dispute_coordinator/impl/rolling_session_window_impl.cpp index 507dc0ac10..2dd12cb257 100644 --- a/core/dispute_coordinator/impl/rolling_session_window_impl.cpp +++ b/core/dispute_coordinator/impl/rolling_session_window_impl.cpp @@ -34,7 +34,7 @@ namespace kagome::dispute { SL_DEBUG(log, "Call 'session_index_for_child' was failed: {}", session_index_res.error()); - return SessionObtainingError::SessionsUnavailable; + return Q_ERROR(SessionObtainingError::SessionsUnavailable); } const auto &session_index = session_index_res.value(); @@ -118,7 +118,7 @@ namespace kagome::dispute { session_index); if (sessions_res.has_error()) { - return SessionObtainingError::SessionsUnavailable; + return Q_ERROR(SessionObtainingError::SessionsUnavailable); } sessions = std::move(sessions_res.value()); @@ -211,7 +211,7 @@ namespace kagome::dispute { api_, sessions, block_hash, window_start, session_index); if (res.has_error()) { - return SessionObtainingError::SessionsUnavailable; + return Q_ERROR(SessionObtainingError::SessionsUnavailable); } else { SessionWindowAdvanced update{ .prev_window_start = old_window_start, @@ -268,7 +268,7 @@ namespace kagome::dispute { sessions.push_back(std::move(session_info)); } else if (not allow_failure) { - return SessionObtainingError::Missing; + return Q_ERROR(SessionObtainingError::Missing); } else { // Handle `allow_failure` true. @@ -278,7 +278,7 @@ namespace kagome::dispute { } } else if (not allow_failure) { - return SessionObtainingError::RuntimeApiError; + return Q_ERROR(SessionObtainingError::RuntimeApiError); } else { // Handle `allow_failure` true. diff --git a/core/dispute_coordinator/impl/runtime_info.cpp b/core/dispute_coordinator/impl/runtime_info.cpp index 985095d00e..4737638d2b 100644 --- a/core/dispute_coordinator/impl/runtime_info.cpp +++ b/core/dispute_coordinator/impl/runtime_info.cpp @@ -48,7 +48,7 @@ namespace kagome::dispute { OUTCOME_TRY(session_info_opt, api_->session_info(parent, session_index)); if (not session_info_opt.has_value()) { - return SessionObtainingError::NoSuchSession; + return Q_ERROR(SessionObtainingError::NoSuchSession); } auto &session_info = session_info_opt.value(); diff --git a/core/dispute_coordinator/participation/impl/queues_impl.cpp b/core/dispute_coordinator/participation/impl/queues_impl.cpp index 1db5700799..9b755e09b7 100644 --- a/core/dispute_coordinator/participation/impl/queues_impl.cpp +++ b/core/dispute_coordinator/participation/impl/queues_impl.cpp @@ -46,8 +46,7 @@ namespace kagome::dispute { std::optional block_number_opt{}; if (block_number_res.has_value()) { block_number_opt = block_number_res.value(); - } else if (block_number_res - != outcome::failure( + } else if (not block_number_res.error().ec( blockchain::BlockTreeError::HEADER_NOT_FOUND)) { return block_number_res.as_failure(); } else { @@ -62,7 +61,7 @@ namespace kagome::dispute { if (priority == ParticipationPriority::Priority) { if (priority_.size() >= kPriorityQueueSize) { - return QueueError::PriorityFull; + return Q_ERROR(QueueError::PriorityFull); } // Remove any best effort entry: best_effort_.erase(comparator); @@ -76,7 +75,7 @@ namespace kagome::dispute { } if (best_effort_.size() >= kBestEffortQueueSize) { - return QueueError::BestEffortFull; + return Q_ERROR(QueueError::BestEffortFull); } best_effort_.emplace(comparator, request); @@ -110,8 +109,7 @@ namespace kagome::dispute { std::optional block_number_opt{}; if (block_number_res.has_value()) { block_number_opt = block_number_res.value(); - } else if (block_number_res - != outcome::failure( + } else if (not block_number_res.error().ec( blockchain::BlockTreeError::HEADER_NOT_FOUND)) { return block_number_res.as_failure(); } else { @@ -125,7 +123,7 @@ namespace kagome::dispute { .candidate_hash = candidate_hash}; if (priority_.size() >= kPriorityQueueSize) { - return QueueError::PriorityFull; + return Q_ERROR(QueueError::PriorityFull); } if (auto it = best_effort_.find(comparator); it != best_effort_.end()) { diff --git a/core/host_api/impl/CMakeLists.txt b/core/host_api/impl/CMakeLists.txt index faf4712887..58296f5e0c 100644 --- a/core/host_api/impl/CMakeLists.txt +++ b/core/host_api/impl/CMakeLists.txt @@ -65,7 +65,6 @@ target_link_libraries(storage_extension blob logger storage - scale::scale_encode_append runtime_transaction_error ) kagome_install(storage_extension) @@ -78,7 +77,6 @@ target_link_libraries(child_storage_extension blob logger storage - scale::scale_encode_append runtime_transaction_error ) kagome_install(child_storage_extension) diff --git a/core/host_api/impl/child_storage_extension.cpp b/core/host_api/impl/child_storage_extension.cpp index 5ad3f4e338..b7003ac557 100644 --- a/core/host_api/impl/child_storage_extension.cpp +++ b/core/host_api/impl/child_storage_extension.cpp @@ -359,7 +359,7 @@ namespace kagome::host_api { } else { SL_ERROR( logger_, "Error in ext_storage_read_version_1: {}", value.error()); - throw std::runtime_error{value.error().message()}; + value.value(); } return memory.storeBuffer(scale::encode(res).value()); diff --git a/core/host_api/impl/crypto_extension.cpp b/core/host_api/impl/crypto_extension.cpp index b442b7de2c..5c6e79610e 100644 --- a/core/host_api/impl/crypto_extension.cpp +++ b/core/host_api/impl/crypto_extension.cpp @@ -436,23 +436,17 @@ namespace kagome::host_api { } namespace { - template - using failure_type = - decltype(outcome::result>(T{}).as_failure()); - /** * @brief converts outcome::failure_type to Secp256k1VerifyError error code * @param failure outcome::result containing error * @return error code */ - template - Secp256k1VerifyError convertFailureToError(const failure_type &failure) { - const outcome::result res = failure; - if (res == outcome::failure(Secp256k1ProviderError::INVALID_V_VALUE)) { + inline Secp256k1VerifyError convertFailureToError( + const qtils::Errors &errors) { + if (errors.ec(Secp256k1ProviderError::INVALID_V_VALUE)) { return secp256k1::secp256k1_verify_error::kInvalidV; } - if (res - == outcome::failure(Secp256k1ProviderError::INVALID_R_OR_S_VALUE)) { + if (errors.ec(Secp256k1ProviderError::INVALID_R_OR_S_VALUE)) { return secp256k1::secp256k1_verify_error::kInvalidRS; } @@ -481,8 +475,7 @@ namespace kagome::host_api { logger_->error("failed to recover uncompressed secp256k1 public key: {}", public_key.error()); - auto error_code = - convertFailureToError(public_key.as_failure()); + auto error_code = convertFailureToError(public_key.error()); auto error_result = scale::encode(static_cast(error_code)).value(); @@ -522,8 +515,7 @@ namespace kagome::host_api { logger_->error("failed to recover uncompressed secp256k1 public key: {}", public_key.error()); - auto error_code = - convertFailureToError(public_key.as_failure()); + auto error_code = convertFailureToError(public_key.error()); auto error_result = scale::encode(static_cast(error_code)).value(); return getMemory().storeBuffer(error_result); diff --git a/core/host_api/impl/storage_extension.cpp b/core/host_api/impl/storage_extension.cpp index 96e5a2e8b1..ba229db091 100644 --- a/core/host_api/impl/storage_extension.cpp +++ b/core/host_api/impl/storage_extension.cpp @@ -41,8 +41,8 @@ namespace kagome::host_api { for (; transactions_ != 0; --transactions_) { if (auto res = storage_provider_->rollbackTransaction(); res.has_error()) { - if (res.error() - != runtime::RuntimeTransactionError::NO_TRANSACTIONS_WERE_STARTED) { + if (not res.error().ec(runtime::RuntimeTransactionError:: + NO_TRANSACTIONS_WERE_STARTED)) { logger_->error(res.error()); } break; @@ -295,7 +295,7 @@ namespace kagome::host_api { auto res = storage_provider_->startTransaction(); if (res.has_error()) { logger_->error("Storage transaction start has failed: {}", res.error()); - throw std::runtime_error(res.error().message()); + res.value(); } ++transactions_; } @@ -306,7 +306,7 @@ namespace kagome::host_api { if (res.has_error()) { logger_->error("Storage transaction rollback has failed: {}", res.error()); - throw std::runtime_error(res.error().message()); + res.value(); } --transactions_; } @@ -316,7 +316,7 @@ namespace kagome::host_api { SL_TRACE_VOID_FUNC_CALL(logger_); if (res.has_error()) { logger_->error("Storage transaction commit has failed: {}", res.error()); - throw std::runtime_error(res.error().message()); + res.value(); } --transactions_; } @@ -342,7 +342,6 @@ namespace kagome::host_api { const auto &pairs = scale::decode(buffer); if (!pairs) { logger_->error("failed to decode pairs: {}", pairs.error()); - throw std::runtime_error(pairs.error().message()); } auto &&pv = pairs.value(); @@ -370,7 +369,6 @@ namespace kagome::host_api { codec.encodeNode(*trie->getRoot(), storage::trie::StateVersion::V0, {}); if (!enc) { logger_->error("failed to encode trie root: {}", enc.error()); - throw std::runtime_error(enc.error().message()); } const auto &hash = codec.hash256(enc.value()); @@ -394,7 +392,6 @@ namespace kagome::host_api { const auto &values = scale::decode(buffer); if (!values) { logger_->error("failed to decode values: {}", values.error()); - throw std::runtime_error(values.error().message()); } const auto &collection = values.value(); @@ -406,7 +403,6 @@ namespace kagome::host_api { logger_->error( "ext_blake2_256_enumerated_trie_root resulted with an error: {}", ordered_hash.error()); - throw std::runtime_error(ordered_hash.error().message()); } SL_TRACE_FUNC_CALL(logger_, ordered_hash.value()); auto res = memory.storeBuffer(ordered_hash.value()); diff --git a/core/injector/application_injector.cpp b/core/injector/application_injector.cpp index 42fc184458..1f36a97923 100644 --- a/core/injector/application_injector.cpp +++ b/core/injector/application_injector.cpp @@ -266,12 +266,7 @@ namespace { const application::AppConfiguration &config, sptr chain_spec) { auto path = config.keystorePath(chain_spec->id()); - auto key_file_storage_res = crypto::KeyFileStorage::createAt(path); - if (not key_file_storage_res) { - common::raise(key_file_storage_res.error()); - } - - return std::move(key_file_storage_res.value()); + return crypto::KeyFileStorage::createAt(path).value(); } sptr get_kademlia_config( @@ -324,9 +319,6 @@ namespace { std::move(state_pruner), injector.template create>()); - if (not block_tree_res.has_value()) { - common::raise(block_tree_res.error()); - } auto &block_tree = block_tree_res.value(); auto runtime_upgrade_tracker = @@ -436,10 +428,6 @@ namespace { std::move(storage), std::move(substitutes), std::move(block_storage)); - if (res.has_error()) { - throw std::runtime_error("Error creating RuntimeUpgradeTrackerImpl: " - + res.error().message()); - } return std::shared_ptr( std::move(res.value())); } diff --git a/core/injector/get_peer_keypair.hpp b/core/injector/get_peer_keypair.hpp index 3907ca74d9..a59816bd52 100644 --- a/core/injector/get_peer_keypair.hpp +++ b/core/injector/get_peer_keypair.hpp @@ -45,12 +45,8 @@ namespace kagome::injector { log->error("Unable to load user provided key from {}. Error: {}", path, key.error()); - common::raise(key.error()); - } else { - auto key_pair = - std::make_shared(std::move(key.value())); - return key_pair; } + return std::make_shared(std::move(key.value())); } auto path = app_config.chainPath(chain.id()) / "network/secret_ed25519"; diff --git a/core/log/formatters/boost_ec.hpp b/core/log/formatters/boost_ec.hpp new file mode 100644 index 0000000000..182e798e2d --- /dev/null +++ b/core/log/formatters/boost_ec.hpp @@ -0,0 +1,15 @@ +/** + * Copyright Quadrivium LLC + * All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +namespace boost::system { + inline auto format_as(const error_code &ec) { + return std::error_code{ec}; + } +} // namespace boost::system diff --git a/core/log/logger.cpp b/core/log/logger.cpp index 93a127104c..e555c22875 100644 --- a/core/log/logger.cpp +++ b/core/log/logger.cpp @@ -57,7 +57,7 @@ namespace kagome::log { } else if (str == "off" or str == "no") { return Level::OFF; } else { - return Error::WRONG_LEVEL; + return Q_ERROR(Error::WRONG_LEVEL); } } diff --git a/core/metrics/impl/metrics_watcher.cpp b/core/metrics/impl/metrics_watcher.cpp index 2770d387ba..c256a15560 100644 --- a/core/metrics/impl/metrics_watcher.cpp +++ b/core/metrics/impl/metrics_watcher.cpp @@ -69,9 +69,9 @@ namespace kagome::metrics { if (not fs::is_directory(storage_path_, ec)) { if (ec) { - return ec; + return Q_ERROR(ec); } - return std::errc::invalid_argument; + return Q_ERROR(std::errc::invalid_argument); } uintmax_t total_size = 0; diff --git a/core/metrics/impl/session_impl.cpp b/core/metrics/impl/session_impl.cpp index 0558040911..587f8fce7f 100644 --- a/core/metrics/impl/session_impl.cpp +++ b/core/metrics/impl/session_impl.cpp @@ -6,7 +6,7 @@ #include "metrics/impl/session_impl.hpp" -#include +#include "log/formatters/boost_ec.hpp" namespace kagome::metrics { diff --git a/core/network/adapters/adapter_errors.hpp b/core/network/adapters/adapter_errors.hpp index 04f58c7089..82335b1b43 100644 --- a/core/network/adapters/adapter_errors.hpp +++ b/core/network/adapters/adapter_errors.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::network { /** diff --git a/core/network/adapters/light.hpp b/core/network/adapters/light.hpp index d899fab9ff..fd240d1d2d 100644 --- a/core/network/adapters/light.hpp +++ b/core/network/adapters/light.hpp @@ -76,7 +76,7 @@ namespace kagome::network { ::protobuf_generated::api::v1::light::Request msg; if (not msg.ParseFromArray(from.base(), remains)) { - return AdaptersError::PARSE_FAILED; + return Q_ERROR(AdaptersError::PARSE_FAILED); } auto get_block = [&](auto &pb) { @@ -143,7 +143,7 @@ namespace kagome::network { ::protobuf_generated::api::v1::light::Response msg; if (not msg.ParseFromArray(from.base(), remains)) { - return AdaptersError::PARSE_FAILED; + return Q_ERROR(AdaptersError::PARSE_FAILED); } out.call = msg.has_remote_call_response(); diff --git a/core/network/adapters/protobuf_block_request.hpp b/core/network/adapters/protobuf_block_request.hpp index 6e65051a22..7e76a6ee69 100644 --- a/core/network/adapters/protobuf_block_request.hpp +++ b/core/network/adapters/protobuf_block_request.hpp @@ -30,7 +30,7 @@ namespace kagome::network { std::vector::iterator loaded) { ::api::v1::BlockRequest msg; - msg.set_fields(htobe32(t.fields)); + msg.set_fields(htobe32(static_cast(t.fields))); kagome::visit_in_place( t.from, @@ -62,10 +62,10 @@ namespace kagome::network { ::api::v1::BlockRequest msg; if (!msg.ParseFromArray(from.base(), remains)) { - return AdaptersError::PARSE_FAILED; + return Q_ERROR(AdaptersError::PARSE_FAILED); } - out.fields.load(be32toh(msg.fields())); + out.fields = toBlockAttributes(be32toh(msg.fields())); out.direction = static_cast(msg.direction()); switch (msg.from_block_case()) { @@ -84,7 +84,7 @@ namespace kagome::network { } break; default: - return AdaptersError::UNEXPECTED_VARIANT; + return Q_ERROR(AdaptersError::UNEXPECTED_VARIANT); } if (msg.max_blocks() > 0) { diff --git a/core/network/adapters/protobuf_block_response.hpp b/core/network/adapters/protobuf_block_response.hpp index df534538b5..95229e76b4 100644 --- a/core/network/adapters/protobuf_block_response.hpp +++ b/core/network/adapters/protobuf_block_response.hpp @@ -84,7 +84,7 @@ namespace kagome::network { ::api::v1::BlockResponse msg; if (!msg.ParseFromArray(from.base(), remains)) { - return AdaptersError::PARSE_FAILED; + return Q_ERROR(AdaptersError::PARSE_FAILED); } auto &dst_blocks = out.blocks; @@ -159,7 +159,7 @@ namespace kagome::network { OUTCOME_TRY(decoded, scale::decode(str2byte(buffer))); return decoded; } - return AdaptersError::EMPTY_DATA; + return Q_ERROR(AdaptersError::EMPTY_DATA); } static std::string vector_to_string(std::vector &&src) { diff --git a/core/network/adapters/protobuf_state_request.hpp b/core/network/adapters/protobuf_state_request.hpp index ab42c3bb66..67c843c55f 100644 --- a/core/network/adapters/protobuf_state_request.hpp +++ b/core/network/adapters/protobuf_state_request.hpp @@ -49,12 +49,12 @@ namespace kagome::network { ::api::v1::StateRequest msg; if (!msg.ParseFromArray(from.base(), remains)) { - return AdaptersError::PARSE_FAILED; + return Q_ERROR(AdaptersError::PARSE_FAILED); } auto hash = primitives::BlockHash::fromString(msg.block()); if (hash.has_error()) { - return AdaptersError::CAST_FAILED; + return Q_ERROR(AdaptersError::CAST_FAILED); } out.hash = std::move(hash.value()); diff --git a/core/network/adapters/protobuf_state_response.hpp b/core/network/adapters/protobuf_state_response.hpp index a2569ac522..713d8cd018 100644 --- a/core/network/adapters/protobuf_state_response.hpp +++ b/core/network/adapters/protobuf_state_response.hpp @@ -51,7 +51,7 @@ namespace kagome::network { ::api::v1::StateResponse msg; if (!msg.ParseFromArray(from.base(), remains)) { - return AdaptersError::PARSE_FAILED; + return Q_ERROR(AdaptersError::PARSE_FAILED); } for (const auto &kvEntry : msg.entries()) { diff --git a/core/network/adapters/uvar.hpp b/core/network/adapters/uvar.hpp index eff53aab1b..6068a08f40 100644 --- a/core/network/adapters/uvar.hpp +++ b/core/network/adapters/uvar.hpp @@ -63,7 +63,7 @@ namespace kagome::network { const std::vector &src, std::vector::const_iterator from) { if (from == src.end()) { - return AdaptersError::EMPTY_DATA; + return Q_ERROR(AdaptersError::EMPTY_DATA); } uint64_t sz = 0; @@ -81,7 +81,7 @@ namespace kagome::network { && ptr != end); if (sz != src.size() - (loaded + counter)) { - return AdaptersError::DATA_SIZE_CORRUPTED; + return Q_ERROR(AdaptersError::DATA_SIZE_CORRUPTED); } std::advance(from, counter); diff --git a/core/network/beefy/beefy.cpp b/core/network/beefy/beefy.cpp index 7327620b40..6a9b30483c 100644 --- a/core/network/beefy/beefy.cpp +++ b/core/network/beefy/beefy.cpp @@ -224,7 +224,7 @@ namespace kagome::network { primitives::BlockNumber max, primitives::BlockNumber min) const { OUTCOME_TRY(opt, block_tree_->getBlockHash(max)); if (not opt) { - return blockchain::BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(blockchain::BlockTreeError::HEADER_NOT_FOUND); } primitives::BlockInfo info{max, *opt}; while (true) { @@ -232,7 +232,8 @@ namespace kagome::network { // bug: beefy pallet doesn't produce digest with first validators OUTCOME_TRY(validators, beefy_api_->validatorSet(info.hash)); if (not validators) { - return runtime::RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND; + return Q_ERROR( + runtime::RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND); } return std::make_pair(info.number, std::move(*validators)); } diff --git a/core/network/beefy/protocol.cpp b/core/network/beefy/protocol.cpp index d1d89c3dff..334330d610 100644 --- a/core/network/beefy/protocol.cpp +++ b/core/network/beefy/protocol.cpp @@ -33,7 +33,7 @@ namespace kagome::network { if (opt) { return outcome::success(std::move(*opt)); } - return outcome::failure(ProtocolError::NO_RESPONSE); + return Q_ERROR(ProtocolError::NO_RESPONSE); } BeefyProtocol::BeefyProtocol(libp2p::Host &host, diff --git a/core/network/helpers/message_read_writer.hpp b/core/network/helpers/message_read_writer.hpp index fa56e7105d..bacc53924b 100644 --- a/core/network/helpers/message_read_writer.hpp +++ b/core/network/helpers/message_read_writer.hpp @@ -71,7 +71,7 @@ namespace kagome::network { const BufferContainer &src, BufferContainer::const_iterator from) { if (from == src.end()) { - return outcome::failure(std::errc::invalid_argument); + return Q_ERROR(std::errc::invalid_argument); } OUTCOME_TRY(it, AdapterType::read(out, src, from)); @@ -117,7 +117,7 @@ namespace kagome::network { const BufferContainer &src, BufferContainer::const_iterator from) { if (from == src.end()) { - return outcome::failure(std::errc::invalid_argument); + return Q_ERROR(std::errc::invalid_argument); } return AdapterType::read(out, src, from); diff --git a/core/network/helpers/scale_message_read_writer.hpp b/core/network/helpers/scale_message_read_writer.hpp index d9a320227a..216d58de91 100644 --- a/core/network/helpers/scale_message_read_writer.hpp +++ b/core/network/helpers/scale_message_read_writer.hpp @@ -40,7 +40,7 @@ namespace kagome::network { [self{shared_from_this()}, cb = std::move(cb)]( libp2p::basic::MessageReadWriter::ReadCallback read_res) { if (!read_res) { - return cb(outcome::failure(read_res.error())); + return cb(std::move(read_res.error())); } auto &raw = read_res.value(); @@ -51,7 +51,7 @@ namespace kagome::network { } auto msg_res = scale::decode(*raw); if (!msg_res) { - return cb(outcome::failure(msg_res.error())); + return cb(std::move(msg_res.error())); } return cb(outcome::success(std::move(msg_res.value()))); }); diff --git a/core/network/impl/peer_manager_impl.cpp b/core/network/impl/peer_manager_impl.cpp index 18a741b86b..baf81e122f 100644 --- a/core/network/impl/peer_manager_impl.cpp +++ b/core/network/impl/peer_manager_impl.cpp @@ -287,7 +287,7 @@ namespace kagome::network { PeerManagerImpl::retrieveCollatorData( PeerState &peer_state, const primitives::BlockHash &relay_parent) { if (!peer_state.collator_state) { - return Error::UNDECLARED_COLLATOR; + return Q_ERROR(Error::UNDECLARED_COLLATOR); } return std::make_pair(peer_state.collator_state.value().collator_id, peer_state.collator_state.value().parachain_id); @@ -721,7 +721,7 @@ namespace kagome::network { "Unable to create stream {} with {}: {}", validation_protocol->protocolName(), peer_id, - stream_result.error().message()); + stream_result.error()); return; } diff --git a/core/network/impl/protocols/block_announce_protocol.cpp b/core/network/impl/protocols/block_announce_protocol.cpp index 45f1f62809..e46a76b212 100644 --- a/core/network/impl/protocols/block_announce_protocol.cpp +++ b/core/network/impl/protocols/block_announce_protocol.cpp @@ -126,7 +126,7 @@ namespace kagome::network { return; } if (not self->onHandshake(peer_id, std::get<2>(r.value()))) { - cb(ProtocolError::GENESIS_NO_MATCH); + cb(Q_ERROR(ProtocolError::GENESIS_NO_MATCH)); return; } auto &stream = std::get<0>(r.value()); diff --git a/core/network/impl/protocols/protocol_base_impl.hpp b/core/network/impl/protocols/protocol_base_impl.hpp index 252ee74804..9815a01a82 100644 --- a/core/network/impl/protocols/protocol_base_impl.hpp +++ b/core/network/impl/protocols/protocol_base_impl.hpp @@ -62,7 +62,7 @@ namespace kagome::network { SL_TRACE(log, "Handled {} protocol stream from {}", protocol, - peer_id); + peer_id.error()); BOOST_ASSERT(stream); self->onIncomingStream(std::move(stream)); return; diff --git a/core/network/impl/protocols/protocol_error.hpp b/core/network/impl/protocols/protocol_error.hpp index 2453e5eb67..d16102cf3a 100644 --- a/core/network/impl/protocols/protocol_error.hpp +++ b/core/network/impl/protocols/protocol_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::network { diff --git a/core/network/impl/protocols/protocol_fetch_available_data.hpp b/core/network/impl/protocols/protocol_fetch_available_data.hpp index 2b7973d752..2b3b95f5aa 100644 --- a/core/network/impl/protocols/protocol_fetch_available_data.hpp +++ b/core/network/impl/protocols/protocol_fetch_available_data.hpp @@ -92,7 +92,7 @@ namespace kagome::network { } base().logger()->error("No fetch statement response."); - return {{ProtocolError::NO_RESPONSE}}; + return Q_ERROR(ProtocolError::NO_RESPONSE); } void onTxRequest(const RequestType &) override {} diff --git a/core/network/impl/protocols/protocol_fetch_chunk.hpp b/core/network/impl/protocols/protocol_fetch_chunk.hpp index a355b934db..dff16d68de 100644 --- a/core/network/impl/protocols/protocol_fetch_chunk.hpp +++ b/core/network/impl/protocols/protocol_fetch_chunk.hpp @@ -62,7 +62,7 @@ namespace kagome::network { auto res = pp_->OnFetchChunkRequest(std::move(request)); if (res.has_error()) { base().logger()->error("Fetching chunk response failed.(error={})", - res.error().message()); + res.error()); } else { visit_in_place( res.value(), diff --git a/core/network/impl/protocols/protocol_req_pov.cpp b/core/network/impl/protocols/protocol_req_pov.cpp index 93fad7719f..bd8a0eaa05 100644 --- a/core/network/impl/protocols/protocol_req_pov.cpp +++ b/core/network/impl/protocols/protocol_req_pov.cpp @@ -44,7 +44,7 @@ namespace kagome::network { base().logger()->warn( "Our PoV response has error.(candidate hash={}, error={})", request, - response.error().message()); + response.error()); } else { base().logger()->info("Our PoV response {} data.(candidate hash={})", boost::get(&response.value()) diff --git a/core/network/impl/protocols/request_response_protocol.hpp b/core/network/impl/protocols/request_response_protocol.hpp index 7cfc0fb064..8cbd0529e5 100644 --- a/core/network/impl/protocols/request_response_protocol.hpp +++ b/core/network/impl/protocols/request_response_protocol.hpp @@ -69,7 +69,7 @@ namespace kagome::network { auto self = wptr.lock(); if (!self) { self->base_.closeStream(std::move(wptr), std::move(stream)); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } @@ -130,7 +130,7 @@ namespace kagome::network { auto self = wptr.lock(); if (not self) { - cb(ProtocolError::GONE); + cb(Q_ERROR(ProtocolError::GONE)); self->base_.closeStream(std::move(wptr), std::move(stream)); return; } @@ -168,7 +168,7 @@ namespace kagome::network { auto self = wptr.lock(); if (not self) { - cb(ProtocolError::GONE, nullptr); + cb(Q_ERROR(ProtocolError::GONE), nullptr); self->base_.closeStream(std::move(wptr), std::move(stream)); return; } @@ -210,7 +210,7 @@ namespace kagome::network { auto self = wptr.lock(); if (!self) { - cb(ProtocolError::GONE); + cb(Q_ERROR(ProtocolError::GONE)); return; } @@ -265,7 +265,7 @@ namespace kagome::network { auto self = wptr.lock(); if (!self) { - cb(ProtocolError::GONE, nullptr); + cb(Q_ERROR(ProtocolError::GONE), nullptr); self->base_.closeStream(std::move(wptr), std::move(stream)); return; } diff --git a/core/network/impl/protocols/state_protocol_impl.cpp b/core/network/impl/protocols/state_protocol_impl.cpp index d2ae011935..e3162a59e6 100644 --- a/core/network/impl/protocols/state_protocol_impl.cpp +++ b/core/network/impl/protocols/state_protocol_impl.cpp @@ -52,7 +52,7 @@ namespace kagome::network { auto &&stream_res) mutable { auto self = wp.lock(); if (not self) { - cb(ProtocolError::GONE); + cb(Q_ERROR(ProtocolError::GONE)); return; } @@ -172,7 +172,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } @@ -191,7 +191,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } @@ -257,7 +257,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - cb(ProtocolError::GONE); + cb(Q_ERROR(ProtocolError::GONE)); return; } @@ -301,7 +301,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } diff --git a/core/network/impl/protocols/sync_protocol_impl.cpp b/core/network/impl/protocols/sync_protocol_impl.cpp index 98c9854de9..56310f0be4 100644 --- a/core/network/impl/protocols/sync_protocol_impl.cpp +++ b/core/network/impl/protocols/sync_protocol_impl.cpp @@ -169,7 +169,7 @@ namespace kagome::network { network::streamReadBuffer(stream_res); auto self = wp.lock(); if (not self) { - cb(ProtocolError::GONE); + cb(Q_ERROR(ProtocolError::GONE)); return; } @@ -229,19 +229,19 @@ namespace kagome::network { stream->remotePeerId().value()); logmsg += ", fields="; - if (block_request.fields & BlockAttribute::HEADER) { + if (has(block_request.fields, BlockAttribute::HEADER)) { logmsg += 'H'; } - if (block_request.fields & BlockAttribute::BODY) { + if (has(block_request.fields, BlockAttribute::BODY)) { logmsg += 'B'; } - if (block_request.fields & BlockAttribute::RECEIPT) { + if (has(block_request.fields, BlockAttribute::RECEIPT)) { logmsg += 'R'; } - if (block_request.fields & BlockAttribute::MESSAGE_QUEUE) { + if (has(block_request.fields, BlockAttribute::MESSAGE_QUEUE)) { logmsg += 'M'; } - if (block_request.fields & BlockAttribute::JUSTIFICATION) { + if (has(block_request.fields, BlockAttribute::JUSTIFICATION)) { logmsg += 'J'; } @@ -352,7 +352,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - cb(ProtocolError::GONE); + cb(Q_ERROR(ProtocolError::GONE)); return; } @@ -396,7 +396,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } @@ -438,19 +438,19 @@ namespace kagome::network { if (base_.logger()->level() >= log::Level::DEBUG) { std::string logmsg = "Requesting blocks: fields="; - if (block_request.fields & BlockAttribute::HEADER) { + if (has(block_request.fields, BlockAttribute::HEADER)) { logmsg += 'H'; } - if (block_request.fields & BlockAttribute::BODY) { + if (has(block_request.fields, BlockAttribute::BODY)) { logmsg += "B"; } - if (block_request.fields & BlockAttribute::RECEIPT) { + if (has(block_request.fields, BlockAttribute::RECEIPT)) { logmsg += "R"; } - if (block_request.fields & BlockAttribute::MESSAGE_QUEUE) { + if (has(block_request.fields, BlockAttribute::MESSAGE_QUEUE)) { logmsg += "M"; } - if (block_request.fields & BlockAttribute::JUSTIFICATION) { + if (has(block_request.fields, BlockAttribute::JUSTIFICATION)) { logmsg += "J"; } @@ -482,7 +482,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } @@ -500,7 +500,7 @@ namespace kagome::network { auto self = wp.lock(); if (not self) { stream->reset(); - response_handler(ProtocolError::GONE); + response_handler(Q_ERROR(ProtocolError::GONE)); return; } diff --git a/core/network/impl/state_protocol_observer_impl.cpp b/core/network/impl/state_protocol_observer_impl.cpp index 81737b7b69..9e1b5f2c21 100644 --- a/core/network/impl/state_protocol_observer_impl.cpp +++ b/core/network/impl/state_protocol_observer_impl.cpp @@ -7,7 +7,6 @@ #include "network/impl/state_protocol_observer_impl.hpp" #include #include -#include #include #include "blockchain/block_header_repository.hpp" @@ -104,11 +103,11 @@ namespace kagome::network { outcome::result StateProtocolObserverImpl::onStateRequest(const StateRequest &request) const { if (request.start.size() > 2) { - return Error::INVALID_CHILD_ROOTHASH; + return Q_ERROR(Error::INVALID_CHILD_ROOTHASH); } if (request.start.size() == 2 and not startsWith(request.start[0], storage::kChildStoragePrefix)) { - return Error::INVALID_CHILD_ROOTHASH; + return Q_ERROR(Error::INVALID_CHILD_ROOTHASH); } OUTCOME_TRY(header, blocks_headers_->getBlockHeader(request.hash)); if (not request.no_proof) { @@ -142,7 +141,7 @@ namespace kagome::network { response.entries.emplace_back(std::move(entry_res.first)); size += entry_res.second; } else { - return Error::NOTFOUND_CHILD_ROOTHASH; + return Q_ERROR(Error::NOTFOUND_CHILD_ROOTHASH); } } @@ -200,11 +199,11 @@ namespace kagome::network { auto &cursor = stack.back(); OUTCOME_TRY(cursor->seek(keys[0])); if (cursor->key() != keys[0]) { - return Error::NOTFOUND_CHILD_ROOTHASH; + return Q_ERROR(Error::NOTFOUND_CHILD_ROOTHASH); } auto value = cursor->value(); if (not value) { - return Error::VALUE_NOT_FOUND; + return Q_ERROR(Error::VALUE_NOT_FOUND); } OUTCOME_TRY(root, common::Hash256::fromSpan(*value)); OUTCOME_TRY(batch, get_batch(root)); @@ -218,7 +217,7 @@ namespace kagome::network { OUTCOME_TRY(cursor->seek(seek)); if (cursor->key() == seek) { if (not cursor->value()) { - return Error::VALUE_NOT_FOUND; + return Q_ERROR(Error::VALUE_NOT_FOUND); } OUTCOME_TRY(cursor->next()); } @@ -229,7 +228,7 @@ namespace kagome::network { while (cursor->isValid()) { auto value = cursor->value(); if (not value) { - return Error::VALUE_NOT_FOUND; + return Q_ERROR(Error::VALUE_NOT_FOUND); } auto key = cursor->key().value(); if (stack.size() == 1 diff --git a/core/network/impl/state_sync_request_flow.cpp b/core/network/impl/state_sync_request_flow.cpp index f3103f8e7c..baf07cf075 100644 --- a/core/network/impl/state_sync_request_flow.cpp +++ b/core/network/impl/state_sync_request_flow.cpp @@ -56,7 +56,7 @@ namespace kagome::network { const StateResponse &res) { storage::trie::PolkadotCodec codec; BOOST_ASSERT(not complete()); - OUTCOME_TRY(nodes, storage::trie::compactDecode(res.proof)); + BOOST_OUTCOME_TRY(auto nodes, storage::trie::compactDecode(res.proof)); auto diff_count = nodes.size(), diff_size = res.proof.size(); if (diff_count != 0) { stat_count_ += diff_count; diff --git a/core/network/impl/stream_engine.cpp b/core/network/impl/stream_engine.cpp index b1a118f605..5abcf599b1 100644 --- a/core/network/impl/stream_engine.cpp +++ b/core/network/impl/stream_engine.cpp @@ -201,9 +201,7 @@ namespace kagome::network { }); }); - if (stream_res - == outcome::failure( - std::make_error_code(std::errc::not_connected))) { + if (stream_res.error().ec(std::errc::not_connected)) { self->reputation_repository_->changeForATime( peer_id, reputation::cost::UNEXPECTED_DISCONNECT, diff --git a/core/network/impl/sync_protocol_observer_impl.cpp b/core/network/impl/sync_protocol_observer_impl.cpp index d4a5346b43..72263931f7 100644 --- a/core/network/impl/sync_protocol_observer_impl.cpp +++ b/core/network/impl/sync_protocol_observer_impl.cpp @@ -47,7 +47,7 @@ namespace kagome::network { const BlocksRequest &request, const libp2p::peer::PeerId &peer_id) const { auto request_id = request.fingerprint(); if (!requested_ids_.emplace(request_id).second) { - return Error::DUPLICATE_REQUEST_ID; + return Q_ERROR(Error::DUPLICATE_REQUEST_ID); } BlocksResponse response; @@ -157,11 +157,10 @@ namespace kagome::network { const BlocksRequest &request, BlocksResponse &response, const std::vector &hash_chain) const { - auto header_needed = - request.attributeIsSet(network::BlockAttribute::HEADER); - auto body_needed = request.attributeIsSet(network::BlockAttribute::BODY); + auto header_needed = has(request.fields, network::BlockAttribute::HEADER); + auto body_needed = has(request.fields, network::BlockAttribute::BODY); auto justification_needed = - request.attributeIsSet(network::BlockAttribute::JUSTIFICATION); + has(request.fields, network::BlockAttribute::JUSTIFICATION); for (const auto &hash : hash_chain) { auto &new_block = diff --git a/core/network/impl/synchronizer_impl.cpp b/core/network/impl/synchronizer_impl.cpp index 5817cb3aaf..0c428ef3e2 100644 --- a/core/network/impl/synchronizer_impl.cpp +++ b/core/network/impl/synchronizer_impl.cpp @@ -147,8 +147,9 @@ namespace kagome::network { auto last_finalized_block = block_tree_->getLastFinalized(); // Check if block from discarded side-chain if (last_finalized_block.number >= block_info.number) { - scheduler_->schedule( - [handler = std::move(handler)] { handler(Error::DISCARDED_BLOCK); }); + scheduler_->schedule([handler = std::move(handler)] { + handler(Q_ERROR(Error::DISCARDED_BLOCK)); + }); return false; } @@ -157,7 +158,7 @@ namespace kagome::network { if (best_block.number + kMaxDistanceToBlockForSubscription < block_info.number) { scheduler_->schedule([handler = std::move(handler)] { - handler(Error::ARRIVED_TOO_EARLY); + handler(Q_ERROR(Error::ARRIVED_TOO_EARLY)); }); return false; } @@ -394,7 +395,7 @@ namespace kagome::network { std::map &&observed) { // Interrupts process if node is shutting down if (node_is_shutting_down_) { - handler(Error::SHUTTING_DOWN); + handler(Q_ERROR(Error::SHUTTING_DOWN)); return; } @@ -415,7 +416,7 @@ namespace kagome::network { upper - 1, peer_id, r.first->second); - handler(Error::DUPLICATE_REQUEST); + handler(Q_ERROR(Error::DUPLICATE_REQUEST)); return; } @@ -459,7 +460,7 @@ namespace kagome::network { lower, upper - 1, peer_id); - handler(Error::EMPTY_RESPONSE); + handler(Q_ERROR(Error::EMPTY_RESPONSE)); self->recent_requests_.erase(std::tuple(peer_id, request_fingerprint)); return; } @@ -490,7 +491,7 @@ namespace kagome::network { // block must be existed because finding in interval of numbers of // blocks that must exist SL_WARN(self->log_, "Not found any common block with {}", peer_id); - handler(Error::EMPTY_RESPONSE); + handler(Q_ERROR(Error::EMPTY_RESPONSE)); return; } @@ -569,7 +570,7 @@ namespace kagome::network { // Interrupts process if node is shutting down if (node_is_shutting_down_) { if (handler) { - handler(Error::SHUTTING_DOWN); + handler(Q_ERROR(Error::SHUTTING_DOWN)); } return; } @@ -590,7 +591,7 @@ namespace kagome::network { from, r.first->second); if (handler) { - handler(Error::DUPLICATE_REQUEST); + handler(Q_ERROR(Error::DUPLICATE_REQUEST)); } return; } @@ -631,7 +632,7 @@ namespace kagome::network { peer_id, from); if (handler) { - handler(Error::EMPTY_RESPONSE); + handler(Q_ERROR(Error::EMPTY_RESPONSE)); } return; } @@ -654,7 +655,7 @@ namespace kagome::network { peer_id, from); if (handler) { - handler(Error::RESPONSE_WITHOUT_BLOCK_HEADER); + handler(Q_ERROR(Error::RESPONSE_WITHOUT_BLOCK_HEADER)); } return; } @@ -666,7 +667,7 @@ namespace kagome::network { peer_id, from); if (handler) { - handler(Error::RESPONSE_WITHOUT_BLOCK_BODY); + handler(Q_ERROR(Error::RESPONSE_WITHOUT_BLOCK_BODY)); } return; } @@ -686,7 +687,7 @@ namespace kagome::network { from, BlockInfo(header.number, block.hash)); if (handler) { - handler(Error::DISCARDED_BLOCK); + handler(Q_ERROR(Error::DISCARDED_BLOCK)); } return; } @@ -719,7 +720,7 @@ namespace kagome::network { from, BlockInfo(header.number, header.parent_hash)); if (handler) { - handler(Error::DISCARDED_BLOCK); + handler(Q_ERROR(Error::DISCARDED_BLOCK)); } return; } @@ -737,7 +738,7 @@ namespace kagome::network { peer_id, from); if (handler) { - handler(Error::WRONG_ORDER); + handler(Q_ERROR(Error::WRONG_ORDER)); } return; } @@ -754,7 +755,7 @@ namespace kagome::network { peer_id, from); if (handler) { - handler(Error::INVALID_HASH); + handler(Q_ERROR(Error::INVALID_HASH)); } return; } @@ -814,7 +815,7 @@ namespace kagome::network { SyncResultHandler &&handler) { if (node_is_shutting_down_) { if (handler) { - handler(Error::SHUTTING_DOWN); + handler(Q_ERROR(Error::SHUTTING_DOWN)); } return; } @@ -845,7 +846,7 @@ namespace kagome::network { target_block, r.first->second); if (handler) { - handler(Error::DUPLICATE_REQUEST); + handler(Q_ERROR(Error::DUPLICATE_REQUEST)); } return; } @@ -885,7 +886,7 @@ namespace kagome::network { peer_id, target_block); if (handler) { - handler(Error::EMPTY_RESPONSE); + handler(Q_ERROR(Error::EMPTY_RESPONSE)); } return; } @@ -911,7 +912,7 @@ namespace kagome::network { peer_id, target_block); if (handler) { - handler(Error::RESPONSE_WITHOUT_BLOCK_HEADER); + handler(Q_ERROR(Error::RESPONSE_WITHOUT_BLOCK_HEADER)); } return; } @@ -1120,7 +1121,7 @@ namespace kagome::network { block_info, n ? fmt::format("and {} others have", n) : fmt::format("has")); if (handler) { - handler(Error::DISCARDED_BLOCK); + handler(Q_ERROR(Error::DISCARDED_BLOCK)); } } @@ -1166,7 +1167,7 @@ namespace kagome::network { block_info, n ? fmt::format("and {} others have", n) : fmt::format("has")); if (handler) { - handler(Error::DISCARDED_BLOCK); + handler(Q_ERROR(Error::DISCARDED_BLOCK)); } return; } @@ -1191,8 +1192,8 @@ namespace kagome::network { notifySubscribers(block_info, block_addition_result); if (not block_addition_result.has_value()) { - if (block_addition_result - != outcome::failure(blockchain::BlockTreeError::BLOCK_EXISTS)) { + if (not block_addition_result.error().ec( + blockchain::BlockTreeError::BLOCK_EXISTS)) { auto n = discardBlock(block_data.hash); SL_WARN(log_, "Block {} {} been discarded: {}", @@ -1200,7 +1201,7 @@ namespace kagome::network { n ? fmt::format("and {} others have", n) : fmt::format("has"), block_addition_result.error()); if (handler) { - handler(Error::DISCARDED_BLOCK); + handler(Q_ERROR(Error::DISCARDED_BLOCK)); } } else { SL_DEBUG(log_, "Block {} is skipped as existing", block_info); @@ -1331,7 +1332,7 @@ namespace kagome::network { if (auto it = known_blocks_.find(hash); it != known_blocks_.end()) { auto number = it->second.data.header->number; - notifySubscribers({number, hash}, Error::DISCARDED_BLOCK); + notifySubscribers({number, hash}, Q_ERROR(Error::DISCARDED_BLOCK)); known_blocks_.erase(it); affected++; @@ -1360,7 +1361,7 @@ namespace kagome::network { break; } const auto &hash = generation_node.mapped(); - notifySubscribers({number, hash}, Error::DISCARDED_BLOCK); + notifySubscribers({number, hash}, Q_ERROR(Error::DISCARDED_BLOCK)); known_blocks_.erase(hash); ancestry_.erase(hash); diff --git a/core/network/notifications/wait_read_close.hpp b/core/network/notifications/wait_read_close.hpp index 4053480d28..361fb27b5f 100644 --- a/core/network/notifications/wait_read_close.hpp +++ b/core/network/notifications/wait_read_close.hpp @@ -13,12 +13,12 @@ namespace kagome::network::notifications { inline void waitReadClose(std::shared_ptr stream) { auto buf = std::make_shared>(1); - auto cb = [stream, buf](libp2p::outcome::result r) { + auto cb = [stream, buf](outcome::result r) { if (r) { stream->reset(); return; } - stream->close([](libp2p::outcome::result) {}); + stream->close([](outcome::result) {}); }; stream->read(*buf, buf->size(), std::move(cb)); } diff --git a/core/network/types/block_attributes.hpp b/core/network/types/block_attributes.hpp index 79987e0046..2dd9931f6c 100644 --- a/core/network/types/block_attributes.hpp +++ b/core/network/types/block_attributes.hpp @@ -12,13 +12,19 @@ #include "common/outcome_throw.hpp" #include "scale/scale_error.hpp" +#define BLOCK_ATTRIBUTE_OP(op) \ + constexpr auto operator op(BlockAttributes l, BlockAttributes r) { \ + return static_cast(static_cast(l) \ + op static_cast(r)); \ + } + namespace kagome::network { /** * Masks of bits, combination of which shows, which fields are to be presented * in the BlockResponse */ - enum class BlockAttribute : uint8_t { + enum class BlockAttributes : uint8_t { /// Include block header. HEADER = 1u, /// Include block body. @@ -28,128 +34,18 @@ namespace kagome::network { /// Include block message queue. MESSAGE_QUEUE = 1u << 3u, /// Include a justification for the block. - JUSTIFICATION = 1u << 4u - }; - - /** - * Block attributes - */ - class BlockAttributes { - public: - BlockAttributes() = default; - constexpr BlockAttributes(const BlockAttributes &other) noexcept = default; - BlockAttributes(BlockAttributes &&other) noexcept = default; - ~BlockAttributes() = default; - - constexpr BlockAttributes(BlockAttribute attribute) noexcept - : attributes(static_cast(attribute)) {} - - template >> - constexpr BlockAttributes(T attribute) noexcept : attributes(0) { - load(attribute); - } - - inline constexpr BlockAttributes &operator=(const BlockAttributes &other) = - default; - inline constexpr BlockAttributes &operator=(BlockAttributes &&other) = - default; - - template >> - constexpr void load(T value) { - attributes = mask_ & value; - } - - inline BlockAttributes &operator=(BlockAttribute attribute) { - attributes = static_cast(attribute); - return *this; - } - - inline constexpr BlockAttributes operator|( - const BlockAttributes &other) const { - BlockAttributes result; - result.attributes = attributes | static_cast(other.attributes); - return result; - } - - inline constexpr BlockAttributes operator|( - const BlockAttribute &attribute) const { - BlockAttributes result; - result.attributes = attributes | static_cast(attribute); - return result; - } - - inline BlockAttributes &operator|=(const BlockAttributes &other) { - attributes |= other.attributes; - return *this; - } - - inline BlockAttributes &operator|=(const BlockAttribute &attribute) { - attributes |= static_cast(attribute); - return *this; - } - - inline constexpr BlockAttributes operator&( - const BlockAttributes &other) const { - BlockAttributes result; - result.attributes = attributes & static_cast(other.attributes); - return result; - } - - inline constexpr BlockAttributes operator&( - const BlockAttribute &attribute) const { - BlockAttributes result; - result.attributes = attributes & static_cast(attribute); - return result; - } - - inline BlockAttributes &operator&=(const BlockAttributes &other) { - attributes &= other.attributes; - return *this; - } - - inline BlockAttributes &operator&=(BlockAttribute attribute) { - attributes &= static_cast(attribute); - return *this; - } - - inline BlockAttributes operator~() const { - BlockAttributes result; - result.attributes = ~attributes & mask_; - return result; - } - - inline bool operator==(const BlockAttributes &other) const { - return attributes == other.attributes; - } - - inline operator bool() const { - return attributes != 0; - } - - template >> - inline operator T() const { - return attributes; - } - - private: - static constexpr uint8_t mask_ = 0b00011111; - uint8_t attributes = 0; - - friend struct std::hash; + JUSTIFICATION = 1u << 4u, + _MASK = 0b11111, }; - - inline constexpr BlockAttributes operator|(const BlockAttribute &lhs, - const BlockAttribute &rhs) { - BlockAttributes result; - result.load(static_cast(lhs) | static_cast(rhs)); - return result; + BLOCK_ATTRIBUTE_OP(&) + BLOCK_ATTRIBUTE_OP(|) + inline BlockAttributes toBlockAttributes(uint8_t v) { + return BlockAttributes{v} & BlockAttributes::_MASK; } - - inline constexpr BlockAttributes operator~(const BlockAttribute &attribute) { - BlockAttributes result; - result.load(~static_cast(attribute)); - return result; + inline bool has(BlockAttributes l, BlockAttributes r) { + return (l & r) == r; } + using BlockAttribute = BlockAttributes; /** * @brief outputs object of type BlockAttributes to stream @@ -176,9 +72,8 @@ namespace kagome::network { Stream &operator>>(Stream &s, BlockAttributes &attributes) { uint8_t value = 0u; s >> value; - - attributes.load(value); - if ((uint8_t)attributes != value) { + attributes = toBlockAttributes(value); + if (static_cast(attributes) != value) { common::raise(scale::DecodeError::UNEXPECTED_VALUE); } return s; @@ -189,6 +84,8 @@ namespace kagome::network { template <> struct std::hash { auto operator()(const kagome::network::BlockAttributes &attr) const { - return std::hash()(attr.attributes); + return std::hash()(static_cast(attr)); } }; + +#undef BLOCK_ATTRIBUTE_OP diff --git a/core/network/types/blocks_request.hpp b/core/network/types/blocks_request.hpp index 54a28db769..df07bf0ddb 100644 --- a/core/network/types/blocks_request.hpp +++ b/core/network/types/blocks_request.hpp @@ -36,10 +36,6 @@ namespace kagome::network { BlockAttribute::HEADER | BlockAttribute::BODY | BlockAttribute::JUSTIFICATION; - bool attributeIsSet(const BlockAttribute &attribute) const { - return fields & attribute; - } - using Fingerprint = size_t; inline Fingerprint fingerprint() const; diff --git a/core/network/warp/cache.cpp b/core/network/warp/cache.cpp index 5a680f453d..0f37b29377 100644 --- a/core/network/warp/cache.cpp +++ b/core/network/warp/cache.cpp @@ -74,12 +74,12 @@ namespace kagome::network { OUTCOME_TRY(after_number, block_repository_->getNumberByHash(after_hash)); auto finalized = block_tree_->getLastFinalized(); if (after_number > finalized.number) { - return Error::NOT_FINALIZED; + return Q_ERROR(Error::NOT_FINALIZED); } OUTCOME_TRY(expected_hash, block_repository_->getHashByNumber(after_number)); if (after_hash != expected_hash) { - return Error::NOT_IN_CHAIN; + return Q_ERROR(Error::NOT_IN_CHAIN); } WarpSyncProof res; res.is_finished = true; diff --git a/core/offchain/impl/http_request.cpp b/core/offchain/impl/http_request.cpp index 5a0d5290ba..9714db8576 100644 --- a/core/offchain/impl/http_request.cpp +++ b/core/offchain/impl/http_request.cpp @@ -18,6 +18,8 @@ #include #include +#include "log/formatters/boost_ec.hpp" + namespace kagome::offchain { HttpRequest::HttpRequest(RequestId id) diff --git a/core/offchain/impl/offchain_worker_impl.cpp b/core/offchain/impl/offchain_worker_impl.cpp index faf783a014..393e350dfd 100644 --- a/core/offchain/impl/offchain_worker_impl.cpp +++ b/core/offchain/impl/offchain_worker_impl.cpp @@ -202,7 +202,7 @@ namespace kagome::offchain { auto &storage = getStorage(storage_type); auto result = storage.get(key); if (result.has_error() - and result != outcome::failure(storage::DatabaseError::NOT_FOUND)) { + and not result.error().ec(storage::DatabaseError::NOT_FOUND)) { SL_WARN(log_, "Can't get value in storage: {}", result.error()); } return result; diff --git a/core/offchain/types.hpp b/core/offchain/types.hpp index 156a403248..c359e54eb5 100644 --- a/core/offchain/types.hpp +++ b/core/offchain/types.hpp @@ -106,9 +106,6 @@ namespace kagome::offchain { s >> buff; auto peer_id_res = libp2p::peer::PeerId::fromBytes(buff); - if (peer_id_res.has_error()) { - throw std::runtime_error(peer_id_res.error().message()); - } v.peer_id = std::move(peer_id_res.value()); scale::CompactInteger size; @@ -118,9 +115,6 @@ namespace kagome::offchain { for (auto &address : v.address) { s >> buff; auto ma_res = libp2p::multi::Multiaddress::create(buff); - if (ma_res.has_error()) { - throw std::runtime_error(ma_res.error().message()); - } address = std::move(ma_res.value()); } diff --git a/core/outcome/outcome.hpp b/core/outcome/outcome.hpp index e14339ee26..7e30fb8db3 100644 --- a/core/outcome/outcome.hpp +++ b/core/outcome/outcome.hpp @@ -6,10 +6,4 @@ #pragma once -#include - -namespace outcome { - using libp2p::outcome::failure; - using libp2p::outcome::result; - using libp2p::outcome::success; -} // namespace outcome +#include diff --git a/core/parachain/approval/approval.cpp b/core/parachain/approval/approval.cpp index 58b03af631..6c7d576777 100644 --- a/core/parachain/approval/approval.cpp +++ b/core/parachain/approval/approval.cpp @@ -31,7 +31,7 @@ namespace kagome::parachain::approval { const consensus::Randomness &randomness, consensus::EpochNumber epoch_index) { if (authorities.size() <= authority_index) { - return Error::AuthorityOutOfBounds; + return Q_ERROR(Error::AuthorityOutOfBounds); } const auto &author = authorities[authority_index].id.id; @@ -47,7 +47,7 @@ namespace kagome::parachain::approval { (Strobe128 *)(transcript.data().data()), // NOLINT (VRFCOutput *)&vrf_output.get().output, &vrf_story)) { - return Error::ComputeRandomnessFailed; + return Q_ERROR(Error::ComputeRandomnessFailed); } return outcome::success(); diff --git a/core/parachain/approval/approval_distribution.cpp b/core/parachain/approval/approval_distribution.cpp index 56362594ed..dd34458718 100644 --- a/core/parachain/approval/approval_distribution.cpp +++ b/core/parachain/approval/approval_distribution.cpp @@ -14,6 +14,7 @@ #include "crypto/crypto_store.hpp" #include "crypto/hasher.hpp" #include "crypto/sr25519_provider.hpp" +#include "log/formatters/boost_ec.hpp" #include "log/formatters/optional.hpp" #include "network/peer_manager.hpp" #include "network/router.hpp" @@ -405,20 +406,20 @@ namespace { using AD = parachain::ApprovalDistribution; if (validator_index >= config.assignment_keys.size()) { - return AD::Error::VALIDATOR_INDEX_OUT_OF_BOUNDS; + return Q_ERROR(AD::Error::VALIDATOR_INDEX_OUT_OF_BOUNDS); } const auto &validator_public = config.assignment_keys[validator_index]; // OUTCOME_TRY(pk, network::ValidatorId::fromSpan(validator_public)); if (claimed_core_index >= config.n_cores) { - return AD::Error::CORE_INDEX_OUT_OF_BOUNDS; + return Q_ERROR(AD::Error::CORE_INDEX_OUT_OF_BOUNDS); } const auto is_in_backing = isInBackingGroup( config.validator_groups, validator_index, backing_group); if (is_in_backing) { - return AD::Error::IS_IN_BACKING_GROUP; + return Q_ERROR(AD::Error::IS_IN_BACKING_GROUP); } const auto &vrf_output = assignment.vrf.output; @@ -430,7 +431,7 @@ namespace { -> outcome::result { auto const sample = obj.sample; if (sample >= config.relay_vrf_modulo_samples) { - return AD::Error::SAMPLE_OUT_OF_BOUNDS; + return Q_ERROR(AD::Error::SAMPLE_OUT_OF_BOUNDS); } /// TODO(iceseer): vrf_verify_extra check return network::DelayTranche(0ull); @@ -439,7 +440,7 @@ namespace { -> outcome::result { auto const core_index = obj.core_index; if (core_index != claimed_core_index) { - return AD::Error::VRF_DELAY_CORE_INDEX_MISMATCH; + return Q_ERROR(AD::Error::VRF_DELAY_CORE_INDEX_MISMATCH); } network::DelayTranche tranche; @@ -453,7 +454,7 @@ namespace { &relay_vrf_story, core_index, &tranche)) { - return AD::Error::VRF_VERIFY_AND_GET_TRANCHE; + return Q_ERROR(AD::Error::VRF_VERIFY_AND_GET_TRANCHE); } return tranche; }); @@ -714,7 +715,7 @@ namespace kagome::parachain { } else { SL_ERROR(logger_, "Error while retrieve neccessary data.(error={})", - res.error().message()); + res.error()); } } @@ -781,7 +782,7 @@ namespace kagome::parachain { if (auto res = unsafe_vrf.compute_randomness( relay_vrf, *ac.authorities, *ac.randomness, *ac.babe_epoch); res.has_error()) { - logger_->warn("Relay VRF return error.(error={})", res.error().message()); + logger_->warn("Relay VRF return error.(error={})", res.error()); return; } @@ -817,7 +818,7 @@ namespace kagome::parachain { "(block_hash={}, session_index={}, error={})", block_entry.parent_hash, block_entry.session, - session_info_res.error().message()); + session_info_res.error()); return std::nullopt; } @@ -871,7 +872,7 @@ namespace kagome::parachain { "No session info for [session_index: {}, block_hash: {}]", session_index, block_hash); - return Error::NO_SESSION_INFO; + return Q_ERROR(Error::NO_SESSION_INFO); } SL_TRACE(logger_, @@ -1011,7 +1012,7 @@ namespace kagome::parachain { block_hash, parent_hash, imported_block.session_index); - return Error::NO_SESSION_INFO; + return Q_ERROR(Error::NO_SESSION_INFO); } const auto block_tick = @@ -1217,7 +1218,7 @@ namespace kagome::parachain { if (block_info.has_error()) { SL_WARN(self->logger_, "ImportedBlockInfo request failed: {}", - block_info.error().message()); + block_info.error()); return; } @@ -1256,7 +1257,7 @@ namespace kagome::parachain { SL_ERROR(self->logger_, "Internal error while retrieve block imported " "candidates: {}", - possible_candidate.error().message()); + possible_candidate.error()); return; } @@ -1416,7 +1417,7 @@ namespace kagome::parachain { "session_index={}, error={})", block_entry.parent_hash, block_entry.session, - session_info_res.error().message()); + session_info_res.error()); return AssignmentCheckResult::Bad; } @@ -1467,7 +1468,7 @@ namespace kagome::parachain { } else { logger_->warn( "Check assignment certificate failed.(error={}, candidate index={})", - res.error().message(), + res.error(), candidate_index); return AssignmentCheckResult::Bad; } @@ -1519,7 +1520,7 @@ namespace kagome::parachain { "session_index={}, error={})", approval.payload.payload.block_hash, block_entry.session, - session_info_res.error().message()); + session_info_res.error()); return ApprovalCheckResult::Bad; } @@ -2278,7 +2279,7 @@ namespace kagome::parachain { "(block_hash={}, session_index={}, error={})", block_entry.parent_hash, block_entry.session, - session_info_res.error().message()); + session_info_res.error()); return; } @@ -2514,7 +2515,7 @@ namespace kagome::parachain { "Adjust weight for block with parachain data failed.(block hash={}, " "error={})", block_hash, - result.error().message()); + result.error()); } } @@ -2683,7 +2684,7 @@ namespace kagome::parachain { if (ec) { SL_TRACE(self->logger_, "Tranche operation waiting failed timer: {}", - ec.message()); + ec); return; } self->handleTranche(block_hash, block_number, candidate_hash); @@ -2722,7 +2723,7 @@ namespace kagome::parachain { "(block_hash={}, session_index={}, error={})", block_entry.parent_hash, block_entry.session, - session_info_res.error().message()); + session_info_res.error()); return; } diff --git a/core/parachain/availability/bitfield/store_impl.cpp b/core/parachain/availability/bitfield/store_impl.cpp index 2d136839ea..0ee4058451 100644 --- a/core/parachain/availability/bitfield/store_impl.cpp +++ b/core/parachain/availability/bitfield/store_impl.cpp @@ -38,7 +38,7 @@ namespace kagome::parachain { logger_->warn( "Availability cores not present.(relay parent={}, error={})", relay_parent, - c.error().message()); + c.error()); return {}; } auto &cores = c.value(); diff --git a/core/parachain/availability/chunks.hpp b/core/parachain/availability/chunks.hpp index f6c0230ef2..7c5e326022 100644 --- a/core/parachain/availability/chunks.hpp +++ b/core/parachain/availability/chunks.hpp @@ -11,35 +11,31 @@ #include "parachain/availability/erasure_coding_error.hpp" #include "runtime/runtime_api/parachain_host_types.hpp" +#define _EC_CPP_TRY_void(tmp, expr) \ + auto &&tmp = expr; \ + if (ec_cpp::resultHasError(tmp)) { \ + return Q_ERROR(kagome::ErasureCodingError(kagome::toErasureCodingError( \ + ec_cpp::resultGetError(std::move(tmp))))); \ + } +#define _EC_CPP_TRY_out(tmp, out, expr) \ + _EC_CPP_TRY_void(tmp, expr); \ + auto out = ec_cpp::resultGetValue(std::move(tmp)); +#define EC_CPP_TRY(out, expr) _EC_CPP_TRY_out(OUTCOME_UNIQUE, out, expr) + namespace kagome::parachain { inline outcome::result minChunks(size_t validators) { - auto res = ec_cpp::getRecoveryThreshold(validators); - if (ec_cpp::resultHasError(res)) { - return ErasureCodingError( - toErasureCodingError(ec_cpp::resultGetError(std::move(res)))); - } - return ec_cpp::resultGetValue(std::move(res)); + EC_CPP_TRY(min, ec_cpp::getRecoveryThreshold(validators)); + return min; } inline outcome::result> toChunks( size_t validators, const runtime::AvailableData &data) { OUTCOME_TRY(message, scale::encode(data)); - auto create_result = ec_cpp::create(validators); - if (ec_cpp::resultHasError(create_result)) { - return ErasureCodingError(toErasureCodingError( - ec_cpp::resultGetError(std::move(create_result)))); - } - - auto encoder = ec_cpp::resultGetValue(std::move(create_result)); - auto encode_result = - encoder.encode(ec_cpp::Slice(message.data(), message.size())); - if (ec_cpp::resultHasError(encode_result)) { - return ErasureCodingError(toErasureCodingError( - ec_cpp::resultGetError(std::move(encode_result)))); - } - - auto shards = ec_cpp::resultGetValue(std::move(encode_result)); + EC_CPP_TRY(encoder, ec_cpp::create(validators)); + EC_CPP_TRY( + shards, + encoder.encode(ec_cpp::Slice(message.data(), message.size()))); BOOST_ASSERT(shards.size() == validators); std::vector chunks; @@ -54,13 +50,7 @@ namespace kagome::parachain { inline outcome::result fromChunks( size_t validators, const std::vector &chunks) { - auto create_result = ec_cpp::create(validators); - if (ec_cpp::resultHasError(create_result)) { - return ErasureCodingError(toErasureCodingError( - ec_cpp::resultGetError(std::move(create_result)))); - } - - auto encoder = ec_cpp::resultGetValue(std::move(create_result)); + EC_CPP_TRY(encoder, ec_cpp::create(validators)); std::vector _chunks; _chunks.resize(validators); for (size_t i = 0; i < chunks.size(); ++i) { @@ -70,12 +60,9 @@ namespace kagome::parachain { } } - auto reconstruct_result = encoder.reconstruct(_chunks); - if (ec_cpp::resultHasError(reconstruct_result)) { - return ErasureCodingError(toErasureCodingError( - ec_cpp::resultGetError(std::move(reconstruct_result)))); - } - auto data = ec_cpp::resultGetValue(std::move(reconstruct_result)); + EC_CPP_TRY(data, encoder.reconstruct(_chunks)); return scale::decode(data); } } // namespace kagome::parachain + +#undef ERASURE_CODING_ERROR diff --git a/core/parachain/availability/erasure_coding_error.cpp b/core/parachain/availability/erasure_coding_error.cpp index fcae77f114..ef0d6cc1c5 100644 --- a/core/parachain/availability/erasure_coding_error.cpp +++ b/core/parachain/availability/erasure_coding_error.cpp @@ -6,9 +6,11 @@ #include "parachain/availability/erasure_coding_error.hpp" +#include + OUTCOME_CPP_DEFINE_CATEGORY(kagome, ErasureCodingError, e) { auto error_code = kagome::fromErasureCodingError(e); - return fmt::format("ErasureCodingError({})", static_cast(error_code)); + return fmt::format("ErasureCodingError({})", fmt::underlying(error_code)); } OUTCOME_CPP_DEFINE_CATEGORY(kagome, ErasureCodingRootError, e) { diff --git a/core/parachain/availability/erasure_coding_error.hpp b/core/parachain/availability/erasure_coding_error.hpp index 52875455f0..8f4c55e89a 100644 --- a/core/parachain/availability/erasure_coding_error.hpp +++ b/core/parachain/availability/erasure_coding_error.hpp @@ -7,7 +7,7 @@ #pragma once #include -#include "outcome/outcome.hpp" +#include namespace kagome { /** diff --git a/core/parachain/availability/proof.hpp b/core/parachain/availability/proof.hpp index 9aa073c822..d789152f55 100644 --- a/core/parachain/availability/proof.hpp +++ b/core/parachain/availability/proof.hpp @@ -89,7 +89,7 @@ namespace kagome::parachain { if (merkle.isHash()) { auto it = db.find(*merkle.asHash()); if (it == db.end()) { - return ErasureCodingRootError::MISMATCH; + return Q_ERROR(ErasureCodingRootError::MISMATCH); } OUTCOME_TRY(n, codec.decodeNode(it->second)); return std::dynamic_pointer_cast(n); @@ -111,7 +111,7 @@ namespace kagome::parachain { OUTCOME_TRY(expected, common::Hash256::fromSpan(_expected)); auto actual = codec.hash256(chunk.chunk); if (actual != expected) { - return ErasureCodingRootError::MISMATCH; + return Q_ERROR(ErasureCodingRootError::MISMATCH); } return outcome::success(); } diff --git a/core/parachain/availability/recovery/recovery_impl.cpp b/core/parachain/availability/recovery/recovery_impl.cpp index 637c3de630..51ab6a361e 100644 --- a/core/parachain/availability/recovery/recovery_impl.cpp +++ b/core/parachain/availability/recovery/recovery_impl.cpp @@ -218,7 +218,7 @@ namespace kagome::parachain { OUTCOME_TRY(chunks, toChunks(active.validators.size(), data)); auto root = makeTrieProof(chunks); if (root != active.erasure_encoding_root) { - return ErasureCodingRootError::MISMATCH; + return Q_ERROR(ErasureCodingRootError::MISMATCH); } return outcome::success(); } diff --git a/core/parachain/pvf/pvf_impl.cpp b/core/parachain/pvf/pvf_impl.cpp index 4055f48a16..1da94cedd2 100644 --- a/core/parachain/pvf/pvf_impl.cpp +++ b/core/parachain/pvf/pvf_impl.cpp @@ -136,22 +136,22 @@ namespace kagome::parachain { const ParachainRuntime &code_zstd) const { OUTCOME_TRY(pov_encoded, scale::encode(pov)); if (pov_encoded.size() > data.max_pov_size) { - return PvfError::POV_SIZE; + return Q_ERROR(PvfError::POV_SIZE); } auto pov_hash = hasher_->blake2b_256(pov_encoded); if (pov_hash != receipt.descriptor.pov_hash) { - return PvfError::POV_HASH; + return Q_ERROR(PvfError::POV_HASH); } auto code_hash = hasher_->blake2b_256(code_zstd); if (code_hash != receipt.descriptor.validation_code_hash) { - return PvfError::CODE_HASH; + return Q_ERROR(PvfError::CODE_HASH); } OUTCOME_TRY(signature_valid, sr25519_provider_->verify(receipt.descriptor.signature, receipt.descriptor.signable(), receipt.descriptor.collator_id)); if (!signature_valid) { - return PvfError::SIGNATURE; + return Q_ERROR(PvfError::SIGNATURE); } auto timer = metric_pvf_execution_time.timer(); @@ -197,7 +197,7 @@ namespace kagome::parachain { "(persisted_validation_data)", descriptor.relay_parent, descriptor.para_id); - return PvfError::NO_PERSISTED_DATA; + return Q_ERROR(PvfError::NO_PERSISTED_DATA); } auto data_hash = hasher_->blake2b_256(scale::encode(*data).value()); if (descriptor.persisted_data_hash != data_hash) { @@ -212,7 +212,7 @@ namespace kagome::parachain { "findData relay_parent={} para_id={}: not found (validation_code)", descriptor.relay_parent, descriptor.para_id); - return PvfError::NO_PERSISTED_DATA; + return Q_ERROR(PvfError::NO_PERSISTED_DATA); } return std::make_pair(*data, *code); } @@ -220,7 +220,7 @@ namespace kagome::parachain { "findData relay_parent={} para_id={}: not found", descriptor.relay_parent, descriptor.para_id); - return PvfError::NO_PERSISTED_DATA; + return Q_ERROR(PvfError::NO_PERSISTED_DATA); } outcome::result PvfImpl::callWasm( @@ -248,7 +248,7 @@ namespace kagome::parachain { const CandidateReceipt &receipt, ValidationResult &&result) const { auto head_hash = hasher_->blake2b_256(result.head_data); if (head_hash != receipt.descriptor.para_head_hash) { - return PvfError::HEAD_HASH; + return Q_ERROR(PvfError::HEAD_HASH); } CandidateCommitments commitments{ .upward_msgs = std::move(result.upward_messages), @@ -261,7 +261,7 @@ namespace kagome::parachain { auto commitments_hash = hasher_->blake2b_256(scale::encode(commitments).value()); if (commitments_hash != receipt.commitments_hash) { - return PvfError::COMMITMENTS_HASH; + return Q_ERROR(PvfError::COMMITMENTS_HASH); } OUTCOME_TRY(valid, parachain_api_->check_validation_outputs( @@ -274,7 +274,7 @@ namespace kagome::parachain { "(check_validation_outputs)", receipt.descriptor.relay_parent, receipt.descriptor.para_id); - return PvfError::OUTPUTS; + return Q_ERROR(PvfError::OUTPUTS); } return commitments; } diff --git a/core/parachain/validator/impl/parachain_observer_impl.cpp b/core/parachain/validator/impl/parachain_observer_impl.cpp index b927721d4b..ab6a20fe2b 100644 --- a/core/parachain/validator/impl/parachain_observer_impl.cpp +++ b/core/parachain/validator/impl/parachain_observer_impl.cpp @@ -88,7 +88,7 @@ namespace kagome::parachain { ParachainObserverImpl::OnCollationRequest( network::CollationFetchingRequest request) { /// Need to decrease rank of the peer and return error. - return network::ProtocolError::PROTOCOL_NOT_IMPLEMENTED; + return Q_ERROR(network::ProtocolError::PROTOCOL_NOT_IMPLEMENTED); } void ParachainObserverImpl::onAdvertise(const libp2p::peer::PeerId &peer_id, @@ -111,7 +111,7 @@ namespace kagome::parachain { !check_res) { logger_->warn("Insert advertisement from {} failed: {}", peer_id, - check_res.error().message()); + check_res.error()); return; } diff --git a/core/parachain/validator/impl/parachain_processor.cpp b/core/parachain/validator/impl/parachain_processor.cpp index 5cb5b11e32..06660a61bb 100644 --- a/core/parachain/validator/impl/parachain_processor.cpp +++ b/core/parachain/validator/impl/parachain_processor.cpp @@ -293,10 +293,10 @@ namespace kagome::parachain { outcome::result ParachainProcessorImpl::canProcessParachains() const { if (!isValidatingNode()) { - return Error::NOT_A_VALIDATOR; + return Q_ERROR(Error::NOT_A_VALIDATOR); } if (!babe_status_observer_->get()) { - return Error::NOT_SYNCHRONIZED; + return Q_ERROR(Error::NOT_SYNCHRONIZED); } return outcome::success(); } @@ -322,7 +322,7 @@ namespace kagome::parachain { if (!validator) { SL_TRACE(logger_, "Not a validator, or no para keys."); - return Error::KEY_NOT_PRESENT; + return Q_ERROR(Error::KEY_NOT_PRESENT); } is_parachain_validator = true; @@ -380,11 +380,11 @@ namespace kagome::parachain { auto rps_result = initNewBackingTask(relay_parent); if (rps_result.has_value()) { storeStateByRelayParent(relay_parent, std::move(rps_result.value())); - } else if (rps_result.error() != Error::KEY_NOT_PRESENT) { + } else if (not rps_result.error().ec(Error::KEY_NOT_PRESENT)) { logger_->error( "Relay parent state was not created. (relay parent={}, error={})", relay_parent, - rps_result.error().message()); + rps_result.error()); } } @@ -616,7 +616,7 @@ namespace kagome::parachain { if (!pov_response_result) { self->logger_->warn("Request PoV on relay_parent {} failed {}", relay_parent, - pov_response_result.error().message()); + pov_response_result.error()); return; } @@ -697,13 +697,13 @@ namespace kagome::parachain { n_validators); result.has_error()) { self->logger_->warn("Validation task failed.(error={})", - result.error().message()); + result.error()); return result.as_failure(); } else { return result; } } - return Error::NO_INSTANCE; + return Q_ERROR(Error::NO_INSTANCE); })), this_context_->wrap( asAsync([wself{weak_from_this()}, peer_id, candidate_hash]( @@ -716,7 +716,7 @@ namespace kagome::parachain { self->logger_->warn( "After validation no parachain state on relay_parent {}", validate_and_second_result.relay_parent); - return Error::OUT_OF_VIEW; + return Q_ERROR(Error::OUT_OF_VIEW); } self->logger_->info( @@ -734,7 +734,7 @@ namespace kagome::parachain { } return outcome::success(); } - return Error::NO_INSTANCE; + return Q_ERROR(Error::NO_INSTANCE); }))); } @@ -1083,7 +1083,7 @@ namespace kagome::parachain { if (sign_result.has_error()) { logger_->error( "Unable to sign Commited Candidate Receipt. Failed with error: {}", - sign_result.error().message()); + sign_result.error()); return std::nullopt; } @@ -1283,11 +1283,11 @@ namespace kagome::parachain { auto rps = our_current_state_.state_by_relay_parent.find(relay_parent); if (rps == our_current_state_.state_by_relay_parent.end()) { - return Error::OUT_OF_VIEW; + return Q_ERROR(Error::OUT_OF_VIEW); } if (rps->second.peers_advertised.count(peer_id) != 0ull) { - return Error::DUPLICATE; + return Q_ERROR(Error::DUPLICATE); } rps->second.peers_advertised.insert(peer_id); @@ -1448,7 +1448,7 @@ namespace kagome::parachain { relay_parent, candidate.descriptor.para_id, candidate_hash); - return Error::VALIDATION_FAILED; + return Q_ERROR(Error::VALIDATION_FAILED); } auto validation_result = validateCandidate(candidate, pov, relay_parent); @@ -1459,8 +1459,8 @@ namespace kagome::parachain { candidate_hash, candidate.descriptor.relay_parent, candidate.descriptor.para_id, - validation_result.error().message()); - return Error::VALIDATION_FAILED; + validation_result.error()); + return Q_ERROR(Error::VALIDATION_FAILED); } need_to_process = our_current_state_.active_leaves.sharedAccess( @@ -1476,7 +1476,7 @@ namespace kagome::parachain { relay_parent, candidate.descriptor.para_id, candidate_hash); - return Error::VALIDATION_FAILED; + return Q_ERROR(Error::VALIDATION_FAILED); } auto &[comms, data] = validation_result.value(); diff --git a/core/primitives/arithmetic_error.hpp b/core/primitives/arithmetic_error.hpp index 58f6f494bd..cd5b5edb26 100644 --- a/core/primitives/arithmetic_error.hpp +++ b/core/primitives/arithmetic_error.hpp @@ -7,8 +7,7 @@ #pragma once #include - -#include "outcome/outcome.hpp" +#include namespace kagome::primitives { diff --git a/core/primitives/inherent_data.hpp b/core/primitives/inherent_data.hpp index 43acd1fa9f..e28cbdd41d 100644 --- a/core/primitives/inherent_data.hpp +++ b/core/primitives/inherent_data.hpp @@ -54,7 +54,7 @@ namespace kagome::primitives { it->second = common::Buffer(scale::encode(inherent).value()); return outcome::success(); } - return InherentDataError::IDENTIFIER_ALREADY_EXISTS; + return Q_ERROR(InherentDataError::IDENTIFIER_ALREADY_EXISTS); } /** Replace the data for an inherent. @@ -76,7 +76,7 @@ namespace kagome::primitives { auto buf = inherent->second; return scale::decode(buf); } - return InherentDataError::IDENTIFIER_DOES_NOT_EXIST; + return Q_ERROR(InherentDataError::IDENTIFIER_DOES_NOT_EXIST); } bool operator==(const InherentData &rhs) const; diff --git a/core/primitives/ss58_codec.cpp b/core/primitives/ss58_codec.cpp index 3dc71d854a..45b3c7e108 100644 --- a/core/primitives/ss58_codec.cpp +++ b/core/primitives/ss58_codec.cpp @@ -49,14 +49,14 @@ namespace kagome::primitives { if (common::BufferView(calculated_checksum) != common::BufferView(checksum)) { - return Ss58Error::INVALID_CHECKSUM; + return Q_ERROR(Ss58Error::INVALID_CHECKSUM); } size_t type_size = (ss58_account_id[0] < 64) ? 1 : 2; if (ss58_account_id.size() - kSs58ChecksumLength - type_size != AccountId::size()) { - return Ss58Error::INVALID_LENGTH; + return Q_ERROR(Ss58Error::INVALID_LENGTH); } primitives::AccountId account_id; diff --git a/core/primitives/token_error.hpp b/core/primitives/token_error.hpp index 2f82f95b54..c9059ff44c 100644 --- a/core/primitives/token_error.hpp +++ b/core/primitives/token_error.hpp @@ -7,8 +7,7 @@ #pragma once #include - -#include "outcome/outcome.hpp" +#include namespace kagome::primitives { diff --git a/core/primitives/transaction_validity.hpp b/core/primitives/transaction_validity.hpp index dd7ce4d346..84ce8d8f52 100644 --- a/core/primitives/transaction_validity.hpp +++ b/core/primitives/transaction_validity.hpp @@ -6,14 +6,9 @@ #pragma once -#include -#include - #include -#include #include "primitives/transaction.hpp" -#include "scale/tie.hpp" namespace kagome::primitives { diff --git a/core/runtime/binaryen/binaryen_memory_provider.cpp b/core/runtime/binaryen/binaryen_memory_provider.cpp index 9c5844c42d..88a334ffcb 100644 --- a/core/runtime/binaryen/binaryen_memory_provider.cpp +++ b/core/runtime/binaryen/binaryen_memory_provider.cpp @@ -43,7 +43,7 @@ namespace kagome::runtime::binaryen { memory_ = memory_factory_->make(rei->getMemory(), config); return outcome::success(); } - return Error::OUTDATED_EXTERNAL_INTERFACE; + return Q_ERROR(Error::OUTDATED_EXTERNAL_INTERFACE); } void BinaryenMemoryProvider::setExternalInterface( diff --git a/core/runtime/binaryen/module/module_impl.cpp b/core/runtime/binaryen/module/module_impl.cpp index 463b79134f..6b000cddfe 100644 --- a/core/runtime/binaryen/module/module_impl.cpp +++ b/core/runtime/binaryen/module/module_impl.cpp @@ -52,7 +52,7 @@ namespace kagome::runtime::binaryen { // that nolint suppresses false positive in a library function // NOLINTNEXTLINE(clang-analyzer-core.NonNullParamChecker) if (code.empty()) { - return Error::EMPTY_STATE_CODE; + return Q_ERROR(Error::EMPTY_STATE_CODE); } auto module = std::make_unique(); @@ -68,7 +68,7 @@ namespace kagome::runtime::binaryen { std::ostringstream msg; e.dump(msg); log->error(msg.str()); - return Error::INVALID_STATE_CODE; + return Q_ERROR(Error::INVALID_STATE_CODE); } } diff --git a/core/runtime/binaryen/module/module_instance_impl.cpp b/core/runtime/binaryen/module/module_instance_impl.cpp index 9dd93d6ae1..d93edc4346 100644 --- a/core/runtime/binaryen/module/module_instance_impl.cpp +++ b/core/runtime/binaryen/module/module_instance_impl.cpp @@ -110,7 +110,7 @@ namespace kagome::runtime::binaryen { module_instance_->wasm.getExportOrNull(wasm::Name{name.data()}); nullptr == res) { SL_DEBUG(logger_, "The requested function {} not found", name); - return RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND; + return Q_ERROR(RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND); } try { @@ -121,9 +121,9 @@ namespace kagome::runtime::binaryen { return PtrSize{res}; } catch (wasm::ExitException &e) { - return Error::UNEXPECTED_EXIT; + return Q_ERROR(Error::UNEXPECTED_EXIT); } catch (wasm::TrapException &e) { - return Error::EXECUTION_ERROR; + return Q_ERROR(Error::EXECUTION_ERROR); } } @@ -147,7 +147,7 @@ namespace kagome::runtime::binaryen { return std::nullopt; } } catch (wasm::TrapException &e) { - return Error::CAN_NOT_OBTAIN_GLOBAL; + return Q_ERROR(Error::CAN_NOT_OBTAIN_GLOBAL); } } diff --git a/core/runtime/common/module_instance.cpp b/core/runtime/common/module_instance.cpp index 9439a0547d..94aa2b233c 100644 --- a/core/runtime/common/module_instance.cpp +++ b/core/runtime/common/module_instance.cpp @@ -33,7 +33,7 @@ namespace kagome::runtime { if (not opt_heap_base) { log->error( "__heap_base global variable is not found in a runtime module"); - return ModuleInstance::Error::ABSENT_HEAP_BASE; + return Q_ERROR(ModuleInstance::Error::ABSENT_HEAP_BASE); } int32_t heap_base = boost::get(*opt_heap_base); BOOST_ASSERT(heap_base > 0); @@ -70,7 +70,7 @@ namespace kagome::runtime { std::max(max_data_segment_end, offset + segment.size()); }); if (static_cast(heap_base) < max_data_segment_end) { - return ModuleInstance::Error::HEAP_BASE_TOO_LOW; + return Q_ERROR(ModuleInstance::Error::HEAP_BASE_TOO_LOW); } memory.resize(heap_base); diff --git a/core/runtime/common/runtime_transaction_error.hpp b/core/runtime/common/runtime_transaction_error.hpp index 54c6fee41c..56c861d63c 100644 --- a/core/runtime/common/runtime_transaction_error.hpp +++ b/core/runtime/common/runtime_transaction_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::runtime { diff --git a/core/runtime/common/runtime_upgrade_tracker_impl.cpp b/core/runtime/common/runtime_upgrade_tracker_impl.cpp index 1813df12f4..fdf3711ae8 100644 --- a/core/runtime/common/runtime_upgrade_tracker_impl.cpp +++ b/core/runtime/common/runtime_upgrade_tracker_impl.cpp @@ -183,7 +183,7 @@ namespace kagome::runtime { if (it != runtime_upgrades_.end()) { return it->block; } - return outcome::failure(RuntimeUpgradeTrackerError::NOT_FOUND); + return Q_ERROR(RuntimeUpgradeTrackerError::NOT_FOUND); } void RuntimeUpgradeTrackerImpl::subscribeToBlockchainEvents( diff --git a/core/runtime/common/trie_storage_provider_impl.cpp b/core/runtime/common/trie_storage_provider_impl.cpp index cd3415e526..7be9161308 100644 --- a/core/runtime/common/trie_storage_provider_impl.cpp +++ b/core/runtime/common/trie_storage_provider_impl.cpp @@ -157,13 +157,13 @@ namespace kagome::runtime { outcome::result TrieStorageProviderImpl::commit( StateVersion version) { if (!transaction_stack_.empty()) { - return Error::UNFINISHED_TRANSACTIONS_LEFT; + return Q_ERROR(Error::UNFINISHED_TRANSACTIONS_LEFT); } if (base_batch_ != nullptr) { OUTCOME_TRY(root, base_batch_->commit(version)); return root; } - return Error::NO_BATCH; + return Q_ERROR(Error::NO_BATCH); } outcome::result TrieStorageProviderImpl::startTransaction() { @@ -177,7 +177,7 @@ namespace kagome::runtime { outcome::result TrieStorageProviderImpl::rollbackTransaction() { if (transaction_stack_.empty()) { - return RuntimeTransactionError::NO_TRANSACTIONS_WERE_STARTED; + return Q_ERROR(RuntimeTransactionError::NO_TRANSACTIONS_WERE_STARTED); } SL_TRACE(logger_, @@ -189,7 +189,7 @@ namespace kagome::runtime { outcome::result TrieStorageProviderImpl::commitTransaction() { if (transaction_stack_.empty()) { - return RuntimeTransactionError::NO_TRANSACTIONS_WERE_STARTED; + return Q_ERROR(RuntimeTransactionError::NO_TRANSACTIONS_WERE_STARTED); } OUTCOME_TRY(transaction_stack_.back().main_batch->writeBack()); diff --git a/core/runtime/common/uncompress_code_if_needed.cpp b/core/runtime/common/uncompress_code_if_needed.cpp index c3c2e8b0bd..42cf1d6d8f 100644 --- a/core/runtime/common/uncompress_code_if_needed.cpp +++ b/core/runtime/common/uncompress_code_if_needed.cpp @@ -40,16 +40,16 @@ namespace kagome::runtime { // @see ZSTD_CONTENTSIZE_UNKNOWN auto check_size = ZSTD_getFrameContentSize(zstd.data(), zstd.size()); if (check_size == ZSTD_CONTENTSIZE_ERROR) { - return UncompressError::ZSTD_ERROR; + return Q_ERROR(UncompressError::ZSTD_ERROR); } res.resize(kCodeBlobBombLimit); auto size = ZSTD_decompress( res.data(), kCodeBlobBombLimit, zstd.data(), zstd.size()); if (ZSTD_isError(size)) { if (ZSTD_getErrorCode(size) == ZSTD_error_dstSize_tooSmall) { - return UncompressError::BOMB_SIZE_REACHED; + return Q_ERROR(UncompressError::BOMB_SIZE_REACHED); } - return UncompressError::ZSTD_ERROR; + return Q_ERROR(UncompressError::ZSTD_ERROR); } res.resize(size); res.shrink_to_fit(); diff --git a/core/runtime/executor.hpp b/core/runtime/executor.hpp index f288ca8ecc..e0966464be 100644 --- a/core/runtime/executor.hpp +++ b/core/runtime/executor.hpp @@ -131,25 +131,20 @@ namespace kagome::runtime { if constexpr (std::is_void_v) { return outcome::success(); } else { - Result t{}; scale::ScaleDecoderStream s(result); - try { - s >> t; - // Check whether the whole byte buffer was consumed - if (s.hasMore(1)) { - static auto logger = log::createLogger("Executor", "runtime"); - SL_ERROR(logger, - "Runtime API call result size exceeds the size of the " - "type to initialize {} (read {}, total size {})", - typeid(Result).name(), - s.currentIndex(), - s.span().size_bytes()); - return outcome::failure(std::errc::illegal_byte_sequence); - } - return outcome::success(std::move(t)); - } catch (std::system_error &e) { - return outcome::failure(e.code()); + OUTCOME_TRY(t, scale::decode(s)); + // Check whether the whole byte buffer was consumed + if (s.hasMore(1)) { + static auto logger = log::createLogger("Executor", "runtime"); + SL_ERROR(logger, + "Runtime API call result size exceeds the size of the " + "type to initialize {} (read {}, total size {})", + typeid(Result).name(), + s.currentIndex(), + s.span().size_bytes()); + return Q_ERROR(std::errc::illegal_byte_sequence); } + return outcome::success(std::move(t)); } } diff --git a/core/runtime/runtime_api/impl/beefy.cpp b/core/runtime/runtime_api/impl/beefy.cpp index f50b415d6c..bb164cdaa3 100644 --- a/core/runtime/runtime_api/impl/beefy.cpp +++ b/core/runtime/runtime_api/impl/beefy.cpp @@ -22,7 +22,7 @@ namespace kagome::runtime { if (r) { return std::move(r.value()); } - if (r.error() == RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND) { + if (r.error().ec(RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND)) { return std::nullopt; } return r.error(); diff --git a/core/runtime/runtime_api/impl/transaction_payment_api.cpp b/core/runtime/runtime_api/impl/transaction_payment_api.cpp index 3cd8f9d5ec..7a83edddd2 100644 --- a/core/runtime/runtime_api/impl/transaction_payment_api.cpp +++ b/core/runtime/runtime_api/impl/transaction_payment_api.cpp @@ -47,7 +47,7 @@ namespace kagome::runtime { return api_version.first == transaction_payment_api_hash; }); if (res == runtime_version.apis.end()) { - return Error::TRANSACTION_PAYMENT_API_NOT_FOUND; + return Q_ERROR(Error::TRANSACTION_PAYMENT_API_NOT_FOUND); } auto api_version = res->second; if (api_version < 2) { diff --git a/core/runtime/wavm/module_instance.cpp b/core/runtime/wavm/module_instance.cpp index 2e7c760ab0..4cbc758322 100644 --- a/core/runtime/wavm/module_instance.cpp +++ b/core/runtime/wavm/module_instance.cpp @@ -119,7 +119,7 @@ namespace kagome::runtime::wavm { WAVM::Runtime::getInstanceExport(instance_, name.data())); if (!function) { SL_DEBUG(logger_, "The requested function {} not found", name); - return RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND; + return Q_ERROR(RuntimeTransactionError::EXPORT_FUNCTION_NOT_FOUND); } const WAVM::IR::FunctionType functionType = WAVM::Runtime::getFunctionType(function); @@ -129,7 +129,7 @@ namespace kagome::runtime::wavm { "The provided function argument count should equal to 2, got {} " "instead", functionType.params().size()); - return Error::WRONG_ARG_COUNT; + return Q_ERROR(Error::WRONG_ARG_COUNT); } WAVM_ASSERT(function) @@ -167,7 +167,7 @@ namespace kagome::runtime::wavm { const auto desc = WAVM::Runtime::describeException(e); logger_->error(desc); WAVM::Runtime::destroyException(e); - return Error::EXECUTION_ERROR; + return Q_ERROR(Error::EXECUTION_ERROR); } }(); WAVM::Runtime::collectCompartmentGarbage(compartment_->getCompartment()); @@ -197,7 +197,7 @@ namespace kagome::runtime::wavm { SL_DEBUG(logger_, "Runtime function returned result of unsupported type: {}", asString(value)); - return Error::WRONG_RETURN_TYPE; + return Q_ERROR(Error::WRONG_RETURN_TYPE); } } diff --git a/core/scale/libp2p_types.cpp b/core/scale/libp2p_types.cpp index 57572b84d1..31fefd1e63 100644 --- a/core/scale/libp2p_types.cpp +++ b/core/scale/libp2p_types.cpp @@ -36,9 +36,6 @@ namespace scale { std::vector addresses; s >> peer_id_base58 >> addresses; auto peer_id_res = libp2p::peer::PeerId::fromBase58(peer_id_base58); - if (not peer_id_res) { - throw std::runtime_error(peer_id_res.error().message()); - } peer_info.id = std::move(peer_id_res.value()); std::vector multi_addrs; multi_addrs.reserve(addresses.size()); diff --git a/core/storage/database_error.hpp b/core/storage/database_error.hpp index db613c7b40..e011ff5064 100644 --- a/core/storage/database_error.hpp +++ b/core/storage/database_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::storage { diff --git a/core/storage/in_memory/in_memory_storage.cpp b/core/storage/in_memory/in_memory_storage.cpp index a51be9b0b3..4b99596b71 100644 --- a/core/storage/in_memory/in_memory_storage.cpp +++ b/core/storage/in_memory/in_memory_storage.cpp @@ -20,7 +20,7 @@ namespace kagome::storage { return BufferView{storage.at(key.toHex())}; } - return DatabaseError::NOT_FOUND; + return Q_ERROR(DatabaseError::NOT_FOUND); } outcome::result> InMemoryStorage::tryGet( diff --git a/core/storage/rocksdb/rocksdb.cpp b/core/storage/rocksdb/rocksdb.cpp index 3fe020c44a..23a347165a 100644 --- a/core/storage/rocksdb/rocksdb.cpp +++ b/core/storage/rocksdb/rocksdb.cpp @@ -37,7 +37,7 @@ namespace kagome::storage { uint32_t memory_budget_mib, bool prevent_destruction) { if (!filesystem::createDirectoryRecursive(path)) { - return DatabaseError::DB_PATH_NOT_CREATED; + return Q_ERROR(DatabaseError::DB_PATH_NOT_CREATED); } auto log = log::createLogger("RocksDB", "storage"); @@ -48,12 +48,12 @@ namespace kagome::storage { log->error("Can't create directory {} for database: {}", absolute_path.native(), ec); - return DatabaseError::IO_ERROR; + return Q_ERROR(DatabaseError::IO_ERROR); } if (not fs::is_directory(absolute_path.native())) { log->error("Can't open {} for database: is not a directory", absolute_path.native()); - return DatabaseError::IO_ERROR; + return Q_ERROR(DatabaseError::IO_ERROR); } // calculate state cache size per space @@ -77,7 +77,7 @@ namespace kagome::storage { "Can't open database in {}: {}", absolute_path.native(), res.ToString()); - return status_as_error(res); + return Q_ERROR(status_as_error(res)); } for (auto &family : existing_families) { if (std::find_if(column_family_descriptors.begin(), @@ -107,7 +107,7 @@ namespace kagome::storage { absolute_path.native(), status.ToString()); - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } std::shared_ptr RocksDb::getSpace(Space space) { @@ -230,7 +230,7 @@ namespace kagome::storage { return false; } - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } bool RocksDbSpace::empty() const { @@ -254,7 +254,7 @@ namespace kagome::storage { reinterpret_cast(value.data()), // NOLINT reinterpret_cast(value.data()) + value.size()); // NOLINT } - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } outcome::result> RocksDbSpace::tryGet( @@ -273,7 +273,7 @@ namespace kagome::storage { return std::nullopt; } - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } outcome::result RocksDbSpace::put(const BufferView &key, @@ -285,7 +285,7 @@ namespace kagome::storage { return outcome::success(); } - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } outcome::result RocksDbSpace::remove(const BufferView &key) { @@ -295,7 +295,7 @@ namespace kagome::storage { return outcome::success(); } - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } void RocksDbSpace::compact(const Buffer &first, const Buffer &last) { @@ -320,7 +320,7 @@ namespace kagome::storage { outcome::result> RocksDbSpace::use() const { auto rocks = storage_.lock(); if (!rocks) { - return DatabaseError::STORAGE_GONE; + return Q_ERROR(DatabaseError::STORAGE_GONE); } return rocks; } diff --git a/core/storage/rocksdb/rocksdb_batch.cpp b/core/storage/rocksdb/rocksdb_batch.cpp index 59867f4704..bf7580b4ea 100644 --- a/core/storage/rocksdb/rocksdb_batch.cpp +++ b/core/storage/rocksdb/rocksdb_batch.cpp @@ -27,14 +27,14 @@ namespace kagome::storage { outcome::result RocksDbBatch::commit() { auto rocks = db_.storage_.lock(); if (!rocks) { - return DatabaseError::STORAGE_GONE; + return Q_ERROR(DatabaseError::STORAGE_GONE); } auto status = rocks->db_->Write(rocks->wo_, &batch_); if (status.ok()) { return outcome::success(); } - return status_as_error(status); + return Q_ERROR(status_as_error(status)); } void RocksDbBatch::clear() { diff --git a/core/storage/trie/compact_decode.cpp b/core/storage/trie/compact_decode.cpp index c5cb7d6590..ad537c46d0 100644 --- a/core/storage/trie/compact_decode.cpp +++ b/core/storage/trie/compact_decode.cpp @@ -29,7 +29,7 @@ namespace kagome::storage::trie { RawCursor cursor; auto push = [&]() mutable -> outcome::result { if (proof_i >= proof.size()) { - return CompactDecodeError::INCOMPLETE_PROOF; + return Q_ERROR(CompactDecodeError::INCOMPLETE_PROOF); } common::BufferView raw{proof[proof_i]}; ++proof_i; @@ -37,7 +37,7 @@ namespace kagome::storage::trie { if (compact) { raw = raw.subspan(1); if (proof_i >= proof.size()) { - return CompactDecodeError::INCOMPLETE_PROOF; + return Q_ERROR(CompactDecodeError::INCOMPLETE_PROOF); } } OUTCOME_TRY(node, codec.decodeNode(raw)); diff --git a/core/storage/trie/compact_encode.cpp b/core/storage/trie/compact_encode.cpp index 582d9509bb..887c4da990 100644 --- a/core/storage/trie/compact_encode.cpp +++ b/core/storage/trie/compact_encode.cpp @@ -86,15 +86,12 @@ namespace kagome::storage::trie { // encode concatenated vectors scale::ScaleEncoderStream s; - try { - s << scale::CompactInteger{proofs[0].size() + proofs[1].size()}; - for (auto &proof : proofs) { - for (auto &x : proof) { - s << x; - } + auto n = proofs[0].size() + proofs[1].size(); + OUTCOME_TRY(scale::encode(s, scale::CompactInteger{n})) + for (auto &proof : proofs) { + for (auto &x : proof) { + OUTCOME_TRY(scale::encode(s, x)) } - } catch (std::system_error &e) { - return e.code(); } return common::Buffer{s.to_vector()}; } diff --git a/core/storage/trie/impl/topper_trie_batch_impl.cpp b/core/storage/trie/impl/topper_trie_batch_impl.cpp index 33440157a7..d50207f7d6 100644 --- a/core/storage/trie/impl/topper_trie_batch_impl.cpp +++ b/core/storage/trie/impl/topper_trie_batch_impl.cpp @@ -46,7 +46,7 @@ namespace kagome::storage::trie { if (opt_value) { return std::move(*opt_value); } - return TrieError::NO_VALUE; + return Q_ERROR(TrieError::NO_VALUE); } outcome::result> TopperTrieBatchImpl::tryGet( @@ -63,7 +63,7 @@ namespace kagome::storage::trie { if (auto p = parent_.lock(); p != nullptr) { return p->tryGet(key); } - return Error::PARENT_EXPIRED; + return Q_ERROR(Error::PARENT_EXPIRED); } std::unique_ptr TopperTrieBatchImpl::trieCursor() { @@ -127,7 +127,7 @@ namespace kagome::storage::trie { if (parent_.lock() != nullptr) { return outcome::success(std::make_tuple(true, 0ULL)); } - return Error::PARENT_EXPIRED; + return Q_ERROR(Error::PARENT_EXPIRED); } outcome::result TopperTrieBatchImpl::writeBack() { @@ -144,16 +144,16 @@ namespace kagome::storage::trie { } return outcome::success(); } - return Error::PARENT_EXPIRED; + return Q_ERROR(Error::PARENT_EXPIRED); } outcome::result TopperTrieBatchImpl::commit(StateVersion version) { - return Error::COMMIT_NOT_SUPPORTED; + return Q_ERROR(Error::COMMIT_NOT_SUPPORTED); } outcome::result>> TopperTrieBatchImpl::createChildBatch(common::BufferView path) { - return Error::CHILD_BATCH_NOT_SUPPORTED; + return Q_ERROR(Error::CHILD_BATCH_NOT_SUPPORTED); } bool TopperTrieBatchImpl::wasClearedByPrefix(const BufferView &key) const { @@ -186,7 +186,8 @@ namespace kagome::storage::trie { } outcome::result TopperTrieCursor::seekLast() { - return TopperTrieBatchImpl::Error::CURSOR_SEEK_LAST_NOT_IMPLEMENTED; + return Q_ERROR( + TopperTrieBatchImpl::Error::CURSOR_SEEK_LAST_NOT_IMPLEMENTED); } bool TopperTrieCursor::isValid() const { @@ -200,7 +201,7 @@ namespace kagome::storage::trie { } outcome::result TopperTrieCursor::prev() { - return TopperTrieBatchImpl::Error::CURSOR_PREV_NOT_IMPLEMENTED; + return Q_ERROR(TopperTrieBatchImpl::Error::CURSOR_PREV_NOT_IMPLEMENTED); } std::optional TopperTrieCursor::key() const { @@ -265,7 +266,7 @@ namespace kagome::storage::trie { outcome::result TopperTrieCursor::step() { if (not choice_) { - return TopperTrieBatchImpl::Error::CURSOR_NEXT_INVALID; + return Q_ERROR(TopperTrieBatchImpl::Error::CURSOR_NEXT_INVALID); } if (choice_.parent) { OUTCOME_TRY(parent_cursor_->next()); diff --git a/core/storage/trie/polkadot_trie/polkadot_trie.hpp b/core/storage/trie/polkadot_trie/polkadot_trie.hpp index b3fd40477d..36c996292b 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie.hpp @@ -53,7 +53,7 @@ namespace kagome::storage::trie { inline static outcome::result> defaultValueRetrieve(const common::Hash256 &) { - return TrieError::VALUE_RETRIEVE_NOT_PROVIDED; + return Q_ERROR(TrieError::VALUE_RETRIEVE_NOT_PROVIDED); } NodeRetrieveFunction retrieve_node; diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp index f47c4b1f81..2532bbb34c 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp @@ -36,7 +36,7 @@ namespace kagome::storage::trie { const TrieNode &child) { auto *current_as_branch = dynamic_cast(current_); if (current_as_branch == nullptr) { - return Error::INVALID_NODE_TYPE; + return Q_ERROR(Error::INVALID_NODE_TYPE); } path_.emplace_back(*current_as_branch, index); current_ = &child; @@ -78,7 +78,7 @@ namespace kagome::storage::trie { if (res.has_error()) { // if the given key is just not present in the trie, return false state_ = InvalidState{res.error()}; - if (res.error() == Error::KEY_NOT_FOUND) { + if (res.error().ec(Error::KEY_NOT_FOUND)) { return false; } // on other errors - propagate them @@ -234,7 +234,7 @@ namespace kagome::storage::trie { auto *current = &parent; while (not current->getValue()) { if (not current->isBranch()) { - return Error::INVALID_NODE_TYPE; + return Q_ERROR(Error::INVALID_NODE_TYPE); } SAFE_CALL(child, visitChildWithMinIdx(*current)) SL_TRACE(log_, @@ -279,7 +279,7 @@ namespace kagome::storage::trie { outcome::result PolkadotTrieCursorImpl::next() { if (std::holds_alternative(state_)) { - return Error::INVALID_CURSOR_ACCESS; + return Q_ERROR(Error::INVALID_CURSOR_ACCESS); } if (trie_->getRoot() == nullptr) { @@ -377,7 +377,7 @@ namespace kagome::storage::trie { auto PolkadotTrieCursorImpl::makeSearchStateAt(const common::BufferView &key) -> outcome::result { if (trie_->getRoot() == nullptr) { - return Error::KEY_NOT_FOUND; + return Q_ERROR(Error::KEY_NOT_FOUND); } SearchState search_state{*trie_->getRoot()}; @@ -392,8 +392,8 @@ namespace kagome::storage::trie { auto res = trie_->forNodeInPath( trie_->getRoot(), KeyNibbles::fromByteBuffer(key), add_visited_child); if (res.has_error()) { - if (res.error() == TrieError::NO_VALUE) { - return Error::KEY_NOT_FOUND; + if (res.error().ec(TrieError::NO_VALUE)) { + return Q_ERROR(Error::KEY_NOT_FOUND); } return res.error(); } diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp index e72b9c4838..f38e4cff4f 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp @@ -140,7 +140,7 @@ namespace kagome::storage::trie { // cursor state was invalidated and not restored struct InvalidState { - std::error_code code; + qtils::Errors code; }; // cursor was created but no seek was performed diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp index 6ab7f59bd8..6ab669fda8 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp @@ -478,7 +478,7 @@ namespace kagome::storage::trie { if (opt_value.has_value()) { return std::move(*opt_value); } - return TrieError::NO_VALUE; + return Q_ERROR(TrieError::NO_VALUE); } outcome::result> PolkadotTrieImpl::tryGet( @@ -537,7 +537,7 @@ namespace kagome::storage::trie { const NibblesView &path, const BranchVisitor &callback) const { if (parent == nullptr) { - return TrieError::NO_VALUE; + return Q_ERROR(TrieError::NO_VALUE); } if (parent->isBranch()) { @@ -562,7 +562,7 @@ namespace kagome::storage::trie { if (parent->getKeyNibbles() == path) { return outcome::success(); } - return TrieError::NO_VALUE; + return Q_ERROR(TrieError::NO_VALUE); } std::unique_ptr PolkadotTrieImpl::trieCursor() const { diff --git a/core/storage/trie/polkadot_trie/trie_error.hpp b/core/storage/trie/polkadot_trie/trie_error.hpp index 9a41bdf646..b7bce5b371 100644 --- a/core/storage/trie/polkadot_trie/trie_error.hpp +++ b/core/storage/trie/polkadot_trie/trie_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include "outcome/outcome.hpp" +#include namespace kagome::storage::trie { /** diff --git a/core/storage/trie/serialization/polkadot_codec.cpp b/core/storage/trie/serialization/polkadot_codec.cpp index 642a39d412..1cc7653322 100644 --- a/core/storage/trie/serialization/polkadot_codec.cpp +++ b/core/storage/trie/serialization/polkadot_codec.cpp @@ -133,7 +133,7 @@ namespace kagome::storage::trie { outcome::result PolkadotCodec::encodeHeader( const TrieNode &node, StateVersion version) const { if (node.getKeyNibbles().size() > 0xffffu) { - return Error::TOO_MANY_NIBBLES; + return Q_ERROR(Error::TOO_MANY_NIBBLES); } uint8_t head; @@ -175,7 +175,7 @@ namespace kagome::storage::trie { partial_length_mask = 0; break; default: - return Error::UNKNOWN_NODE_TYPE; + return Q_ERROR(Error::UNKNOWN_NODE_TYPE); } // set bits of partial key length @@ -276,7 +276,7 @@ namespace kagome::storage::trie { encoding += node.getKeyNibbles().toByteBuffer(); if (!node.getValue()) { - return Error::NO_NODE_VALUE; + return Q_ERROR(Error::NO_NODE_VALUE); } OUTCOME_TRY(encodeValue(encoding, node, version, child_visitor)); @@ -315,10 +315,10 @@ namespace kagome::storage::trie { return decodeBranch(type, partial_key, stream); case TrieNode::Type::Empty: - return Error::UNKNOWN_NODE_TYPE; + return Q_ERROR(Error::UNKNOWN_NODE_TYPE); default: - return Error::UNKNOWN_NODE_TYPE; + return Q_ERROR(Error::UNKNOWN_NODE_TYPE); } } @@ -326,7 +326,7 @@ namespace kagome::storage::trie { PolkadotCodec::decodeHeader(BufferStream &stream) const { TrieNode::Type type; if (not stream.hasMore(1)) { - return Error::INPUT_TOO_SMALL; + return Q_ERROR(Error::INPUT_TOO_SMALL); } auto first = stream.next(); @@ -362,7 +362,7 @@ namespace kagome::storage::trie { uint8_t read_length{}; do { if (not stream.hasMore(1)) { - return Error::INPUT_TOO_SMALL; + return Q_ERROR(Error::INPUT_TOO_SMALL); } read_length = stream.next(); pk_length += read_length; @@ -379,7 +379,7 @@ namespace kagome::storage::trie { partial_key.reserve(byte_length); while (byte_length-- != 0) { if (not stream.hasMore(1)) { - return Error::INPUT_TOO_SMALL; + return Q_ERROR(Error::INPUT_TOO_SMALL); } partial_key.putUint8(stream.next()); } @@ -399,7 +399,7 @@ namespace kagome::storage::trie { constexpr uint8_t kChildrenBitmapSize = 2; if (not stream.hasMore(kChildrenBitmapSize)) { - return Error::INPUT_TOO_SMALL; + return Q_ERROR(Error::INPUT_TOO_SMALL); } auto node = std::make_shared(partial_key); @@ -409,24 +409,14 @@ namespace kagome::storage::trie { scale::ScaleDecoderStream ss(stream.leftBytes()); // decode the branch value if needed - common::Buffer value; if (type == TrieNode::Type::BranchWithValue) { - try { - ss >> value; - } catch (std::system_error &e) { - return outcome::failure(e.code()); - } + OUTCOME_TRY(value, scale::decode(ss)); node->setValue({std::move(value), std::nullopt, false}); } else if (type == TrieNode::Type::BranchContainingHashes) { - common::Hash256 hash; - try { - ss >> hash; - } catch (std::system_error &e) { - return outcome::failure(e.code()); - } + OUTCOME_TRY(hash, scale::decode(ss)); node->setValue({std::nullopt, hash, false}); } else if (type != TrieNode::Type::BranchEmptyValue) { - return Error::UNKNOWN_NODE_TYPE; + return Q_ERROR(Error::UNKNOWN_NODE_TYPE); } uint8_t i = 0; @@ -437,12 +427,7 @@ namespace kagome::storage::trie { children_bitmap &= ~(1u << i); // read the hash of the child and make a dummy node from it for this // child in the processed branch - common::Buffer child_hash; - try { - ss >> child_hash; - } catch (std::system_error &e) { - return outcome::failure(e.code()); - } + OUTCOME_TRY(child_hash, scale::decode(ss)); // SAFETY: database cannot contain invalid merkle values node->children.at(i) = std::make_shared( MerkleValue::create(child_hash).value()); diff --git a/core/storage/trie_pruner/impl/trie_pruner_impl.cpp b/core/storage/trie_pruner/impl/trie_pruner_impl.cpp index e3302f8fe2..66c6ce947d 100644 --- a/core/storage/trie_pruner/impl/trie_pruner_impl.cpp +++ b/core/storage/trie_pruner/impl/trie_pruner_impl.cpp @@ -198,7 +198,7 @@ namespace kagome::storage::trie_pruner { const trie::RootHash &root_hash) { auto trie_res = serializer_->retrieveTrie(root_hash, nullptr); if (trie_res.has_error() - && trie_res.error() == storage::DatabaseError::NOT_FOUND) { + && trie_res.error().ec(storage::DatabaseError::NOT_FOUND)) { SL_TRACE(logger_, "Failed to obtain trie from storage, the state {} is probably " "already pruned or has never been executed.", @@ -466,7 +466,7 @@ namespace kagome::storage::trie_pruner { "Failed to restore trie pruner state starting from last " "finalized " "block: {}", - res.error().message()); + res.error()); return res.as_failure(); } } else { @@ -487,7 +487,7 @@ namespace kagome::storage::trie_pruner { "Failed to restore trie pruner state starting from base " "block {}: {}", last_pruned_block.value(), - res.error().message()); + res.error()); } } return outcome::success(); @@ -512,7 +512,7 @@ namespace kagome::storage::trie_pruner { OUTCOME_TRY(base_block, block_tree.getBlockHeader(base_block_hash)); auto base_tree_res = serializer_->retrieveTrie(base_block.state_root); if (base_tree_res.has_error() - && base_tree_res.error() == storage::DatabaseError::NOT_FOUND) { + && base_tree_res.error().ec(storage::DatabaseError::NOT_FOUND)) { SL_DEBUG( logger_, "Failed to restore pruner state, probably node is fast-syncing."); @@ -537,7 +537,7 @@ namespace kagome::storage::trie_pruner { block_hash); auto tree_res = serializer_->retrieveTrie(header.state_root); if (tree_res.has_error() - && tree_res.error() == DatabaseError::NOT_FOUND) { + && tree_res.error().ec(DatabaseError::NOT_FOUND)) { SL_WARN(logger_, "State for block #{} is not found in the database", header.number); diff --git a/core/telemetry/impl/connection_impl.cpp b/core/telemetry/impl/connection_impl.cpp index 4c7156fe78..c37166325c 100644 --- a/core/telemetry/impl/connection_impl.cpp +++ b/core/telemetry/impl/connection_impl.cpp @@ -10,6 +10,8 @@ #include +#include "log/formatters/boost_ec.hpp" + namespace kagome::telemetry { std::size_t TelemetryConnectionImpl::instance_ = 0; diff --git a/core/transaction_pool/impl/transaction_pool_impl.cpp b/core/transaction_pool/impl/transaction_pool_impl.cpp index 9cdab4a2c5..817a07a4ed 100644 --- a/core/transaction_pool/impl/transaction_pool_impl.cpp +++ b/core/transaction_pool/impl/transaction_pool_impl.cpp @@ -83,7 +83,7 @@ namespace kagome::transaction_pool { // return either invalid or unknown validity error [](const auto &validity_error) -> outcome::result { - return validity_error; + return Q_ERROR(validity_error); }); }, [&](primitives::ValidTransaction &&v) @@ -113,7 +113,7 @@ namespace kagome::transaction_pool { primitives::TransactionSource source, primitives::Extrinsic extrinsic) { auto hash = hasher_->blake2b_256(extrinsic.data); if (imported(hash)) { - return TransactionPoolError::TX_ALREADY_IMPORTED; + return Q_ERROR(TransactionPoolError::TX_ALREADY_IMPORTED); } OUTCOME_TRY(tx, constructTransaction(source, extrinsic, hash)); @@ -130,7 +130,7 @@ namespace kagome::transaction_pool { outcome::result TransactionPoolImpl::submitOne(Transaction &&tx) { if (imported(tx.hash)) { - return TransactionPoolError::TX_ALREADY_IMPORTED; + return Q_ERROR(TransactionPoolError::TX_ALREADY_IMPORTED); } return submitOneInternal(std::make_shared(std::move(tx))); } @@ -148,7 +148,7 @@ namespace kagome::transaction_pool { sub_engine_->notify(key.value(), ExtrinsicLifecycleEvent::Dropped(key.value())); } - return TransactionPoolError::POOL_IS_FULL; + return Q_ERROR(TransactionPoolError::POOL_IS_FULL); } SL_DEBUG(logger_, @@ -303,7 +303,7 @@ namespace kagome::transaction_pool { logger_, "Extrinsic with hash {} was not found in the pool during remove", tx_hash); - return TransactionPoolError::TX_NOT_FOUND; + return Q_ERROR(TransactionPoolError::TX_NOT_FOUND); }); } diff --git a/core/transaction_pool/transaction_pool_error.hpp b/core/transaction_pool/transaction_pool_error.hpp index 1230126d39..aa932c1a5d 100644 --- a/core/transaction_pool/transaction_pool_error.hpp +++ b/core/transaction_pool/transaction_pool_error.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include namespace kagome::transaction_pool { enum class TransactionPoolError { diff --git a/core/utils/benchmark_main.cpp b/core/utils/benchmark_main.cpp index 6643f88233..db5d25f88f 100644 --- a/core/utils/benchmark_main.cpp +++ b/core/utils/benchmark_main.cpp @@ -55,9 +55,8 @@ namespace kagome { }); if (res.has_error()) { - SL_ERROR( - config_logger, "Failed to run benchmark: {}", res.error().message()); - return res.error().value(); + SL_ERROR(config_logger, "Failed to run benchmark: {}", res.error()); + return EXIT_FAILURE; } return 0; diff --git a/core/utils/kagome_db_editor.cpp b/core/utils/kagome_db_editor.cpp index 46cd22f547..42dd8b08f0 100644 --- a/core/utils/kagome_db_editor.cpp +++ b/core/utils/kagome_db_editor.cpp @@ -106,7 +106,7 @@ inline auto check(T &&res) { if constexpr (is_optional::value) { throw std::runtime_error("No value"); } else { - kagome::common::raise(res.error()); + res.value(); } } return std::forward(res); diff --git a/test/core/api/client/http_client.cpp b/test/core/api/client/http_client.cpp index 5d139f45dc..d022646943 100644 --- a/test/core/api/client/http_client.cpp +++ b/test/core/api/client/http_client.cpp @@ -32,7 +32,7 @@ namespace test { // TODO (yuraz): ignore error code, log message boost::ignore_unused(ec); if (ec) { - return HttpClientError::CONNECTION_FAILED; + return Q_ERROR(HttpClientError::CONNECTION_FAILED); } return outcome::success(); } @@ -58,7 +58,7 @@ namespace test { // Send the HTTP request to the remote host boost::beast::http::write(stream_, req, ec); if (ec) { - return callback(HttpClientError::NETWORK_ERROR); + return callback(Q_ERROR(HttpClientError::NETWORK_ERROR)); } FlatBuffer buffer{}; @@ -67,11 +67,11 @@ namespace test { // receive response boost::beast::http::read(stream_, buffer, res, ec); if (ec) { - return callback(HttpClientError::NETWORK_ERROR); + return callback(Q_ERROR(HttpClientError::NETWORK_ERROR)); } if (res.result() != HttpStatus::ok) { - return callback(HttpClientError::HTTP_ERROR); + return callback(Q_ERROR(HttpClientError::HTTP_ERROR)); } return callback(res.body()); diff --git a/test/core/api/client/http_client.hpp b/test/core/api/client/http_client.hpp index 65b612039a..9c6b965171 100644 --- a/test/core/api/client/http_client.hpp +++ b/test/core/api/client/http_client.hpp @@ -8,6 +8,8 @@ #include #include +#include + #include "outcome/outcome.hpp" namespace test { diff --git a/test/core/api/client/ws_client.cpp b/test/core/api/client/ws_client.cpp index dd57f88642..47e08209af 100644 --- a/test/core/api/client/ws_client.cpp +++ b/test/core/api/client/ws_client.cpp @@ -33,12 +33,12 @@ namespace test { stream_.next_layer().connect(endpoint_, ec); if (ec) { - return WsClientError::CONNECTION_FAILED; + return Q_ERROR(WsClientError::CONNECTION_FAILED); } stream_.handshake(endpoint_.address().to_string(), "/", ec); if (ec) { - return WsClientError::WEBSOCKET_ERROR; + return Q_ERROR(WsClientError::WEBSOCKET_ERROR); } return outcome::success(); @@ -63,12 +63,12 @@ namespace test { stream_.write(buffer.data(), ec); buffer.consume(message.size()); if (ec) { - return callback(WsClientError::NETWORK_ERROR); + return callback(Q_ERROR(WsClientError::NETWORK_ERROR)); } stream_.read(buffer, ec); if (ec) { - return callback(WsClientError::NETWORK_ERROR); + return callback(Q_ERROR(WsClientError::NETWORK_ERROR)); } return callback(boost::beast::buffers_to_string(buffer.data())); diff --git a/test/core/api/client/ws_client.hpp b/test/core/api/client/ws_client.hpp index e2759e6e0c..7998a47cfd 100644 --- a/test/core/api/client/ws_client.hpp +++ b/test/core/api/client/ws_client.hpp @@ -8,6 +8,7 @@ #include #include +#include #include "outcome/outcome.hpp" diff --git a/test/core/api/service/author/author_api_test.cpp b/test/core/api/service/author/author_api_test.cpp index 7d0764ef76..652224e470 100644 --- a/test/core/api/service/author/author_api_test.cpp +++ b/test/core/api/service/author/author_api_test.cpp @@ -191,7 +191,7 @@ TEST_F(AuthorApiTest, SubmitExtrinsicSuccess) { */ TEST_F(AuthorApiTest, SubmitExtrinsicFail) { EXPECT_CALL(*transaction_pool, submitExtrinsic(_, _)) - .WillOnce(Return(outcome::failure(DummyError::ERROR))); + .WillOnce(Return(Q_ERROR(DummyError::ERROR))); EXPECT_OUTCOME_ERROR( res, author_api->submitExtrinsic(TransactionSource::External, *extrinsic), @@ -367,7 +367,8 @@ TEST_F(AuthorApiTest, HasSessionKeysFailureNotFound) { Buffer keys; keys.resize(32 * 6); outcome::result edOk = Ed25519Keypair{}; - outcome::result srErr = CryptoStoreError::KEY_NOT_FOUND; + outcome::result srErr = + Q_ERROR(CryptoStoreError::KEY_NOT_FOUND); EXPECT_CALL(*store, findEd25519Keypair(_, _)).Times(1).WillOnce(Return(edOk)); EXPECT_CALL(*store, findSr25519Keypair(_, _)) .Times(1) diff --git a/test/core/api/service/chain/chain_api_test.cpp b/test/core/api/service/chain/chain_api_test.cpp index bb080bc47d..d55c7959a2 100644 --- a/test/core/api/service/chain/chain_api_test.cpp +++ b/test/core/api/service/chain/chain_api_test.cpp @@ -278,8 +278,7 @@ TEST_F(ChainApiTest, UnsubscribeNewHeads) { auto expected_return = ChainApiImpl::Error::BLOCK_NOT_FOUND; EXPECT_CALL(*api_service, unsubscribeNewHeads(subscription_id)) - .WillOnce(Return(expected_return)); + .WillOnce(Return(Q_ERROR(expected_return))); - EXPECT_OUTCOME_ERROR( - result, api->unsubscribeNewHeads(subscription_id), expected_return); + EXPECT_EC(api->unsubscribeNewHeads(subscription_id), expected_return); } diff --git a/test/core/api/service/state/state_api_test.cpp b/test/core/api/service/state/state_api_test.cpp index 158331dc0d..6e91596b94 100644 --- a/test/core/api/service/state/state_api_test.cpp +++ b/test/core/api/service/state/state_api_test.cpp @@ -431,9 +431,8 @@ namespace kagome::api { .WillOnce(Return(42)); EXPECT_CALL(*block_header_repo_, getNumberByHash(to)) .WillOnce(Return(42 + StateApiImpl::kMaxBlockRange + 1)); - EXPECT_OUTCOME_FALSE( - error, api_->queryStorage(std::vector({"some_key"_buf}), from, to)); - ASSERT_EQ(error, StateApiImpl::Error::MAX_BLOCK_RANGE_EXCEEDED); + EXPECT_EC(api_->queryStorage(std::vector({"some_key"_buf}), from, to), + StateApiImpl::Error::MAX_BLOCK_RANGE_EXCEEDED); } /** @@ -444,8 +443,8 @@ namespace kagome::api { TEST_F(StateApiTest, HitsKeyRangeLimits) { std::vector keys(StateApiImpl::kMaxKeySetSize + 1); primitives::BlockHash from{"from"_hash256}, to{"to"_hash256}; - EXPECT_OUTCOME_FALSE(error, api_->queryStorage(keys, from, to)); - ASSERT_EQ(error, StateApiImpl::Error::MAX_KEY_SET_SIZE_EXCEEDED); + EXPECT_EC(api_->queryStorage(keys, from, to), + StateApiImpl::Error::MAX_KEY_SET_SIZE_EXCEEDED); } /** @@ -528,11 +527,10 @@ namespace kagome::api { auto expected_return = StateApiImpl::Error::MAX_BLOCK_RANGE_EXCEEDED; EXPECT_CALL(*api_service_, unsubscribeRuntimeVersion(subscription_id)) - .WillOnce(Return(expected_return)); + .WillOnce(Return(Q_ERROR(expected_return))); - EXPECT_OUTCOME_ERROR(result, - api_->unsubscribeRuntimeVersion(subscription_id), - expected_return); + EXPECT_EC(api_->unsubscribeRuntimeVersion(subscription_id), + expected_return); } } // namespace kagome::api diff --git a/test/core/authorship/block_builder_factory_test.cpp b/test/core/authorship/block_builder_factory_test.cpp index 786caf1d01..0171a505b3 100644 --- a/test/core/authorship/block_builder_factory_test.cpp +++ b/test/core/authorship/block_builder_factory_test.cpp @@ -91,7 +91,7 @@ TEST_F(BlockBuilderFactoryTest, CreateSuccessful) { TEST_F(BlockBuilderFactoryTest, CreateFailed) { // given EXPECT_CALL(*core_, initialize_block(expected_header_, _)).WillOnce([] { - return boost::system::error_code{}; + return Q_ERROR(nullptr); }); BlockBuilderFactoryImpl factory(core_, block_builder_api_, header_backend_); diff --git a/test/core/authorship/block_builder_test.cpp b/test/core/authorship/block_builder_test.cpp index 183ebbae11..e51cd1fe84 100644 --- a/test/core/authorship/block_builder_test.cpp +++ b/test/core/authorship/block_builder_test.cpp @@ -71,7 +71,7 @@ TEST_F(BlockBuilderTest, PushWhenApplyFails) { // given Extrinsic xt{}; EXPECT_CALL(*block_builder_api_, apply_extrinsic(_, xt)) - .WillOnce(Return(outcome::failure(boost::system::error_code{}))); + .WillOnce(Return(Q_ERROR(boost::system::error_code{}))); EXPECT_CALL(*block_builder_api_, finalize_block(_)) .WillOnce(Return(expected_header_)); diff --git a/test/core/authorship/proposer_test.cpp b/test/core/authorship/proposer_test.cpp index 29286eda24..23a0ad9f32 100644 --- a/test/core/authorship/proposer_test.cpp +++ b/test/core/authorship/proposer_test.cpp @@ -164,7 +164,7 @@ TEST_F(ProposerTest, CreateBlockFailsWhenXtNotPushed) { EXPECT_CALL(*block_builder_, getInherentExtrinsics(inherent_data_)) .WillOnce(Return(inherent_xts)); EXPECT_CALL(*block_builder_, pushExtrinsic(inherent_xts[0])) - .WillOnce(Return(outcome::failure(BlockBuilderError::BAD_MANDATORY))); + .WillOnce(Return(Q_ERROR(BlockBuilderError::BAD_MANDATORY))); // when auto block_res = proposer_.propose(expected_block_, @@ -186,7 +186,7 @@ TEST_F(ProposerTest, CreateBlockFailsWhenXtNotPushed) { TEST_F(ProposerTest, CreateBlockFailsToGetInhetentExtr) { // given EXPECT_CALL(*block_builder_, getInherentExtrinsics(inherent_data_)) - .WillOnce(Return(outcome::failure(boost::system::error_code{}))); + .WillOnce(Return(Q_ERROR(boost::system::error_code{}))); // when auto block_res = proposer_.propose(expected_block_, @@ -216,9 +216,9 @@ TEST_F(ProposerTest, PushFailed) { .WillOnce(Return(inherent_xts)); EXPECT_CALL(*block_builder_, pushExtrinsic(_)) .WillOnce(Return(outcome::success())) // for inherent xt - .WillOnce(Return(outcome::failure( - boost::system::error_code{}))); // for xt from tx pool, will emit - // Error: Success though + .WillOnce(Return( + Q_ERROR(boost::system::error_code{}))); // for xt from tx pool, will + // emit Error: Success though EXPECT_CALL(*block_builder_, estimateBlockSize()).WillOnce(Return(1)); EXPECT_CALL(*block_builder_, bake()).WillOnce(Return(expected_block)); @@ -274,8 +274,7 @@ TEST_F(ProposerTest, TrxSkippedDueToOverflow) { }); EXPECT_CALL(*transaction_pool_, removeOne(_)) - .WillRepeatedly( - Return(outcome::failure(TransactionPoolError::TX_NOT_FOUND))); + .WillRepeatedly(Return(Q_ERROR(TransactionPoolError::TX_NOT_FOUND))); EXPECT_CALL(*transaction_pool_, getReadyTransactions()) .WillOnce(Return(ready_transactions)); ; @@ -306,8 +305,7 @@ TEST_F(ProposerTest, TrxSkippedDueToResourceExhausted) { .WillOnce(Return(inherent_xts)); // BlockBuilderApi roports to be full for all trxs EXPECT_CALL(*block_builder_, pushExtrinsic(_)) - .WillRepeatedly( - Return(outcome::failure(BlockBuilderError::EXHAUSTS_RESOURCES))); + .WillRepeatedly(Return(Q_ERROR(BlockBuilderError::EXHAUSTS_RESOURCES))); EXPECT_CALL(*block_builder_, estimateBlockSize()).WillRepeatedly(Return(1)); EXPECT_CALL(*block_builder_, bake()).WillOnce(Return(expected_block)); @@ -325,8 +323,7 @@ TEST_F(ProposerTest, TrxSkippedDueToResourceExhausted) { }); EXPECT_CALL(*transaction_pool_, removeOne(_)) - .WillRepeatedly( - Return(outcome::failure(TransactionPoolError::TX_NOT_FOUND))); + .WillRepeatedly(Return(Q_ERROR(TransactionPoolError::TX_NOT_FOUND))); EXPECT_CALL(*transaction_pool_, getReadyTransactions()) .WillOnce(Return(ready_transactions)); ; diff --git a/test/core/blockchain/block_storage_test.cpp b/test/core/blockchain/block_storage_test.cpp index 3587759345..e15f109ced 100644 --- a/test/core/blockchain/block_storage_test.cpp +++ b/test/core/blockchain/block_storage_test.cpp @@ -30,6 +30,7 @@ using kagome::primitives::BlockHash; using kagome::primitives::BlockHeader; using kagome::primitives::BlockNumber; using kagome::storage::BufferStorageMock; +using kagome::storage::DatabaseError; using kagome::storage::Space; using kagome::storage::SpacedStorageMock; using kagome::storage::trie::RootHash; @@ -149,12 +150,10 @@ TEST_F(BlockStorageTest, CreateWithExistingGenesis) { TEST_F(BlockStorageTest, CreateWithStorageError) { // check if storage contained genesis block EXPECT_CALL(*(spaces[Space::kLookupKey]), tryGetMock(_)) - .WillOnce(Return(kagome::storage::DatabaseError::IO_ERROR)); + .WillOnce(Return(Q_ERROR(DatabaseError::IO_ERROR))); - EXPECT_OUTCOME_ERROR( - res, - BlockStorageImpl::create(root_hash, spaced_storage, hasher), - kagome::storage::DatabaseError::IO_ERROR); + EXPECT_EC(BlockStorageImpl::create(root_hash, spaced_storage, hasher), + DatabaseError::IO_ERROR); } /** @@ -190,10 +189,9 @@ TEST_F(BlockStorageTest, PutWithStorageError) { Buffer key{regular_block_hash}; EXPECT_CALL(*(spaces[Space::kBlockBody]), put(key.view(), _)) - .WillOnce(Return(kagome::storage::DatabaseError::IO_ERROR)); + .WillOnce(Return(Q_ERROR(DatabaseError::IO_ERROR))); - ASSERT_OUTCOME_ERROR(block_storage->putBlock(block), - kagome::storage::DatabaseError::IO_ERROR); + EXPECT_EC(block_storage->putBlock(block), DatabaseError::IO_ERROR); } /** diff --git a/test/core/blockchain/block_tree_test.cpp b/test/core/blockchain/block_tree_test.cpp index fe4f549c20..2676bc0a71 100644 --- a/test/core/blockchain/block_tree_test.cpp +++ b/test/core/blockchain/block_tree_test.cpp @@ -121,14 +121,14 @@ struct BlockTreeTest : public testing::Test { Invoke([&](const BlockNumber &n) -> outcome::result { auto it = num_to_hash_.find(n); if (it == num_to_hash_.end()) { - return BlockTreeError::HEADER_NOT_FOUND; + return Q_ERROR(BlockTreeError::HEADER_NOT_FOUND); } return it->second; })); EXPECT_CALL(*header_repo_, getBlockHeader({finalized_block_header_.parent_hash})) - .WillRepeatedly(Return(BlockTreeError::HEADER_NOT_FOUND)); + .WillRepeatedly(Return(Q_ERROR(BlockTreeError::HEADER_NOT_FOUND))); EXPECT_CALL(*header_repo_, getBlockHeader(kFinalizedBlockInfo.hash)) .WillRepeatedly(Return(finalized_block_header_)); @@ -459,7 +459,7 @@ TEST_F(BlockTreeTest, Finalize) { EXPECT_CALL(*storage_, getJustification(kFinalizedBlockInfo.hash)) .WillRepeatedly(Return(outcome::success(justification))); EXPECT_CALL(*storage_, getJustification(hash)) - .WillRepeatedly(Return(outcome::failure(boost::system::error_code{}))); + .WillRepeatedly(Return(Q_ERROR(boost::system::error_code{}))); EXPECT_CALL(*storage_, putJustification(justification, hash)) .WillRepeatedly(Return(outcome::success())); EXPECT_CALL(*storage_, removeJustification(kFinalizedBlockInfo.hash)) @@ -517,7 +517,7 @@ TEST_F(BlockTreeTest, FinalizeWithPruning) { Justification justification{{0x45, 0xF4}}; auto encoded_justification = scale::encode(justification).value(); EXPECT_CALL(*storage_, getJustification(B1_hash)) - .WillRepeatedly(Return(outcome::failure(boost::system::error_code{}))); + .WillRepeatedly(Return(Q_ERROR(boost::system::error_code{}))); EXPECT_CALL(*storage_, putJustification(justification, B1_hash)) .WillRepeatedly(Return(outcome::success())); EXPECT_CALL(*storage_, getBlockHeader(B1_hash)) @@ -691,7 +691,7 @@ TEST_F(BlockTreeTest, GetChainByBlockDescending) { .WillRepeatedly(Return(0)); EXPECT_CALL(*header_repo_, getNumberByHash(hash2)).WillRepeatedly(Return(2)); EXPECT_CALL(*header_repo_, getBlockHeader({kFinalizedBlockInfo.hash})) - .WillOnce(Return(BlockTreeError::HEADER_NOT_FOUND)); + .WillOnce(Return(Q_ERROR(BlockTreeError::HEADER_NOT_FOUND))); std::vector expected_chain{hash2, hash1}; @@ -712,10 +712,11 @@ TEST_F(BlockTreeTest, GetChainByBlockDescending) { TEST_F(BlockTreeTest, GetBestChain_BlockNotFound) { BlockInfo target(1337, "TargetBlock#1337"_hash256); EXPECT_CALL(*header_repo_, getNumberByHash(target.hash)) - .WillRepeatedly(Return(BlockTreeError::EXISTING_BLOCK_NOT_FOUND)); + .WillRepeatedly( + Return(Q_ERROR(BlockTreeError::EXISTING_BLOCK_NOT_FOUND))); - ASSERT_OUTCOME_ERROR(block_tree_->getBestContaining(target.hash), - BlockTreeError::EXISTING_BLOCK_NOT_FOUND); + EXPECT_EC(block_tree_->getBestContaining(target.hash), + BlockTreeError::EXISTING_BLOCK_NOT_FOUND); } /** @@ -732,8 +733,8 @@ TEST_F(BlockTreeTest, GetBestChain_DiscardedBlock) { EXPECT_CALL(*header_repo_, getHashByNumber(target.number)) .WillRepeatedly(Return(other.hash)); - ASSERT_OUTCOME_ERROR(block_tree_->getBestContaining(target.hash), - BlockTreeError::BLOCK_ON_DEAD_END); + EXPECT_EC(block_tree_->getBestContaining(target.hash), + BlockTreeError::BLOCK_ON_DEAD_END); } /** diff --git a/test/core/consensus/grandpa/authority_manager_test.cpp b/test/core/consensus/grandpa/authority_manager_test.cpp index 4a827e6740..50fd9a3093 100644 --- a/test/core/consensus/grandpa/authority_manager_test.cpp +++ b/test/core/consensus/grandpa/authority_manager_test.cpp @@ -96,7 +96,7 @@ class AuthorityManagerTest : public testing::Test { // EXPECT_CALL(*block_tree, getBlockJustification(_)) // .Times(testing::AnyNumber()); EXPECT_CALL(*block_tree, getBlockJustification(_)) - .WillRepeatedly(Return(std::error_code{})); + .WillRepeatedly(Return(Q_ERROR(nullptr))); EXPECT_CALL(*grandpa_api, authorities(mockHash(0))) .WillRepeatedly(Return(voters(0).authorities)); diff --git a/test/core/consensus/timeline/block_executor_test.cpp b/test/core/consensus/timeline/block_executor_test.cpp index 9627a6d1b8..947bdba2e5 100644 --- a/test/core/consensus/timeline/block_executor_test.cpp +++ b/test/core/consensus/timeline/block_executor_test.cpp @@ -214,8 +214,8 @@ TEST_F(BlockExecutorTest, JustificationFollowDigests) { .body = kagome::primitives::BlockBody{}, .justification = justification}; EXPECT_CALL(*block_tree_, getBlockBody(some_hash)) - .WillOnce( - testing::Return(kagome::blockchain::BlockTreeError::BODY_NOT_FOUND)); + .WillOnce(testing::Return( + Q_ERROR(kagome::blockchain::BlockTreeError::BODY_NOT_FOUND))); babe_config_->leadership_rate.second = 42; EXPECT_CALL(*block_validator_, diff --git a/test/core/consensus/timeline/timeline_test.cpp b/test/core/consensus/timeline/timeline_test.cpp index e3203c8672..82bb01e072 100644 --- a/test/core/consensus/timeline/timeline_test.cpp +++ b/test/core/consensus/timeline/timeline_test.cpp @@ -375,7 +375,7 @@ TEST_F(TimelineTest, Validator) { .WillRepeatedly(Return(0)); // - process slot (not slot leader for this case) EXPECT_CALL(*production_consensus, processSlot(current_slot, best_block)) - .WillOnce(Return(BlockProductionError::NO_SLOT_LEADER)); + .WillOnce(Return(Q_ERROR(BlockProductionError::NO_SLOT_LEADER))); // - start to wait for end of current slot EXPECT_CALL(*scheduler, scheduleImplMockCall(_, _, false)) .WillOnce(WithArg<0>(Invoke([&](auto cb) { diff --git a/test/core/consensus/validation/block_validator_test.cpp b/test/core/consensus/validation/block_validator_test.cpp index 78a387515f..93cb63909c 100644 --- a/test/core/consensus/validation/block_validator_test.cpp +++ b/test/core/consensus/validation/block_validator_test.cpp @@ -165,7 +165,7 @@ TEST_F(BlockValidatorTest, Success) { auto validate_res = validator_.validateHeader( valid_block_.header, 0ull, authority.id, threshold_, config_); - ASSERT_TRUE(validate_res) << validate_res.error().message(); + EXPECT_OUTCOME_TRUE_1(validate_res); } /** @@ -178,11 +178,9 @@ TEST_F(BlockValidatorTest, LessDigestsThanNeeded) { authorities_.emplace_back(authority); // for this test we can just not seal the block - it's the second digest - EXPECT_OUTCOME_FALSE( - err, - validator_.validateHeader( - valid_block_.header, 0ull, authority.id, threshold_, config_)); - ASSERT_EQ(err, consensus::babe::DigestError::REQUIRED_DIGESTS_NOT_FOUND); + EXPECT_EC(validator_.validateHeader( + valid_block_.header, 0ull, authority.id, threshold_, config_), + consensus::babe::DigestError::REQUIRED_DIGESTS_NOT_FOUND); } /** @@ -209,11 +207,9 @@ TEST_F(BlockValidatorTest, NoBabeHeader) { authorities_.emplace_back(); authorities_.emplace_back(authority); - EXPECT_OUTCOME_FALSE( - err, - validator_.validateHeader( - valid_block_.header, 0ull, authority.id, threshold_, config_)); - ASSERT_EQ(err, consensus::babe::DigestError::REQUIRED_DIGESTS_NOT_FOUND); + EXPECT_EC(validator_.validateHeader( + valid_block_.header, 0ull, authority.id, threshold_, config_), + consensus::babe::DigestError::REQUIRED_DIGESTS_NOT_FOUND); } /** @@ -289,11 +285,9 @@ TEST_F(BlockValidatorTest, SignatureVerificationFail) { .data[10]++; // THEN - EXPECT_OUTCOME_FALSE( - err, - validator_.validateHeader( - valid_block_.header, 0ull, authority.id, threshold_, config_)); - ASSERT_EQ(err, BabeBlockValidator::ValidationError::INVALID_SIGNATURE); + EXPECT_EC(validator_.validateHeader( + valid_block_.header, 0ull, authority.id, threshold_, config_), + BabeBlockValidator::ValidationError::INVALID_SIGNATURE); } /** @@ -328,11 +322,9 @@ TEST_F(BlockValidatorTest, VRFFail) { .WillOnce(Return(VRFVerifyOutput{.is_valid = false, .is_less = true})); // THEN - EXPECT_OUTCOME_FALSE( - err, - validator_.validateHeader( - valid_block_.header, 0ull, authority.id, threshold_, config_)); - ASSERT_EQ(err, BabeBlockValidator::ValidationError::INVALID_VRF); + EXPECT_EC(validator_.validateHeader( + valid_block_.header, 0ull, authority.id, threshold_, config_), + BabeBlockValidator::ValidationError::INVALID_VRF); } /** @@ -369,9 +361,7 @@ TEST_F(BlockValidatorTest, ThresholdGreater) { .WillOnce(Return(VRFVerifyOutput{.is_valid = true, .is_less = false})); // THEN - EXPECT_OUTCOME_FALSE( - err, - validator_.validateHeader( - valid_block_.header, 0ull, authority.id, threshold_, config_)); - ASSERT_EQ(err, BabeBlockValidator::ValidationError::INVALID_VRF); + EXPECT_EC(validator_.validateHeader( + valid_block_.header, 0ull, authority.id, threshold_, config_), + BabeBlockValidator::ValidationError::INVALID_VRF); } diff --git a/test/core/crypto/crypto_store/crypto_store_test.cpp b/test/core/crypto/crypto_store/crypto_store_test.cpp index 0c1cd65a4d..9fc4720d0e 100644 --- a/test/core/crypto/crypto_store/crypto_store_test.cpp +++ b/test/core/crypto/crypto_store/crypto_store_test.cpp @@ -140,9 +140,8 @@ struct CryptoStoreTest : public test::BaseFS_Test { * @and generated key pair is stored in memory */ TEST_F(CryptoStoreTest, generateEd25519KeypairMnemonicSuccess) { - EXPECT_OUTCOME_FALSE( - err, crypto_store->findEd25519Keypair(key_type, ed_pair.public_key)); - ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND); + EXPECT_EC(crypto_store->findEd25519Keypair(key_type, ed_pair.public_key), + CryptoStoreError::KEY_NOT_FOUND); EXPECT_OUTCOME_TRUE(pair, crypto_store->generateEd25519Keypair(key_type, mnemonic)); @@ -183,9 +182,8 @@ TEST_F(CryptoStoreTest, generateSr25519KeypairMnemonicSuccess) { * @and generated key pair is stored in memory */ TEST_F(CryptoStoreTest, generateEd25519KeypairSeedSuccess) { - EXPECT_OUTCOME_FALSE( - err, crypto_store->findEd25519Keypair(key_type, ed_pair.public_key)); - ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND); + EXPECT_EC(crypto_store->findEd25519Keypair(key_type, ed_pair.public_key), + CryptoStoreError::KEY_NOT_FOUND); EXPECT_OUTCOME_TRUE( pair, crypto_store->generateEd25519Keypair(key_type, Ed25519Seed{seed})); @@ -206,9 +204,8 @@ TEST_F(CryptoStoreTest, generateEd25519KeypairSeedSuccess) { * @and key generated pair is stored in memory */ TEST_F(CryptoStoreTest, generateSr25519KeypairSeedSuccess) { - EXPECT_OUTCOME_FALSE( - err, crypto_store->findSr25519Keypair(key_type, sr_pair.public_key)); - ASSERT_EQ(err, CryptoStoreError::KEY_NOT_FOUND); + EXPECT_EC(crypto_store->findSr25519Keypair(key_type, sr_pair.public_key), + CryptoStoreError::KEY_NOT_FOUND); EXPECT_OUTCOME_TRUE( pair, crypto_store->generateSr25519Keypair(key_type, Sr25519Seed{seed})); diff --git a/test/core/host_api/CMakeLists.txt b/test/core/host_api/CMakeLists.txt index ada2280b68..6bf62974a0 100644 --- a/test/core/host_api/CMakeLists.txt +++ b/test/core/host_api/CMakeLists.txt @@ -60,8 +60,8 @@ addtest(offchain_extension_test ) target_link_libraries(offchain_extension_test Boost::boost - scale::scale_encode_append offchain_extension + scale::scale dummy_error logger_for_tests ) diff --git a/test/core/host_api/child_storage_extension_test.cpp b/test/core/host_api/child_storage_extension_test.cpp index f354e67159..4a3ab11926 100644 --- a/test/core/host_api/child_storage_extension_test.cpp +++ b/test/core/host_api/child_storage_extension_test.cpp @@ -142,7 +142,7 @@ TEST_P(ReadOutcomeParameterizedTest, GetTest) { child_storage_extension_->ext_default_child_storage_get_version_1( child_storage_key_span, key_span); }, - std::runtime_error); + qtils::Errors); } else { EXPECT_CALL(*memory_, storeBuffer(BufferView(encoded_opt_value))) .WillOnce(Return(value_span)); @@ -217,7 +217,7 @@ TEST_P(ReadOutcomeParameterizedTest, ReadTest) { child_storage_extension_->ext_default_child_storage_read_version_1( child_storage_key_span, key_span, value_span, offset); }, - std::runtime_error); + qtils::Errors); } else { WasmSpan res_wasm_span = 1337; EXPECT_CALL(*memory_, storeBuffer(BufferView(encoded_result))) @@ -469,7 +469,7 @@ INSTANTIATE_TEST_SUITE_P(Instance, /// success case outcome::success(), /// failure with arbitrary error code - outcome::failure(testutil::DummyError::ERROR)) + Q_ERROR(testutil::DummyError::ERROR)) // empty argument for the macro ); @@ -482,7 +482,7 @@ INSTANTIATE_TEST_SUITE_P( /// not found outcome::success(std::nullopt), /// failure with arbitrary error code - outcome::failure(testutil::DummyError::ERROR)) + Q_ERROR(testutil::DummyError::ERROR)) // empty argument for the macro ); @@ -494,6 +494,6 @@ INSTANTIATE_TEST_SUITE_P(Instance, /// not found outcome::success(false), /// failure with arbitrary error code - outcome::failure(testutil::DummyError::ERROR)) + Q_ERROR(testutil::DummyError::ERROR)) // empty argument for the macro ); diff --git a/test/core/host_api/crypto_extension_test.cpp b/test/core/host_api/crypto_extension_test.cpp index 50b3c7dd88..cc88511a23 100644 --- a/test/core/host_api/crypto_extension_test.cpp +++ b/test/core/host_api/crypto_extension_test.cpp @@ -760,8 +760,8 @@ TEST_F(CryptoExtensionTest, Ed25519SignFailure) { EXPECT_CALL(*crypto_store_, findEd25519Keypair(key_type, ed25519_keypair.public_key)) - .WillOnce(Return( - outcome::failure(kagome::crypto::CryptoStoreError::KEY_NOT_FOUND))); + .WillOnce( + Return(Q_ERROR(kagome::crypto::CryptoStoreError::KEY_NOT_FOUND))); EXPECT_CALL(*memory_, storeBuffer(BufferView(ed_sr_signature_failure_result_buffer))) @@ -827,8 +827,8 @@ TEST_F(CryptoExtensionTest, Sr25519SignFailure) { EXPECT_CALL(*crypto_store_, findSr25519Keypair(key_type, sr25519_keypair.public_key)) - .WillOnce(Return( - outcome::failure(kagome::crypto::CryptoStoreError::KEY_NOT_FOUND))); + .WillOnce( + Return(Q_ERROR(kagome::crypto::CryptoStoreError::KEY_NOT_FOUND))); EXPECT_CALL(*memory_, storeBuffer(BufferView(ed_sr_signature_failure_result_buffer))) diff --git a/test/core/host_api/offchain_extension_test.cpp b/test/core/host_api/offchain_extension_test.cpp index 58203d0a3a..0487154d55 100644 --- a/test/core/host_api/offchain_extension_test.cpp +++ b/test/core/host_api/offchain_extension_test.cpp @@ -690,6 +690,6 @@ INSTANTIATE_TEST_SUITE_P(Instance, /// success case outcome::success(), /// failure with arbitrary error code - outcome::failure(testutil::DummyError::ERROR)) + Q_ERROR(testutil::DummyError::ERROR)) // empty argument for the macro ); diff --git a/test/core/host_api/storage_extension_test.cpp b/test/core/host_api/storage_extension_test.cpp index 3ae2fe8463..4e8e1d8484 100644 --- a/test/core/host_api/storage_extension_test.cpp +++ b/test/core/host_api/storage_extension_test.cpp @@ -328,7 +328,7 @@ INSTANTIATE_TEST_SUITE_P(Instance, /// success case outcome::success(), /// failure with arbitrary error code - outcome::failure(testutil::DummyError::ERROR)) + Q_ERROR(testutil::DummyError::ERROR)) // empty argument for the macro ); diff --git a/test/core/network/rpc_libp2p_test.cpp b/test/core/network/rpc_libp2p_test.cpp index b8ef129ccb..86f0095427 100644 --- a/test/core/network/rpc_libp2p_test.cpp +++ b/test/core/network/rpc_libp2p_test.cpp @@ -84,7 +84,7 @@ TEST_F(RpcLibp2pTest, ReadWithResponse) { finished = true; return response_; }, - [](auto &&err) { FAIL() << err.error().message(); }); + [](auto &&err) { FAIL(); }); ASSERT_TRUE(finished); } @@ -101,7 +101,7 @@ TEST_F(RpcLibp2pTest, ReadWithResponseErroredResponse) { ScaleRPC::read( read_writer_, [](auto &&received_request) { - return ::outcome::failure(boost::system::error_code{}); + return Q_ERROR(boost::system::error_code{}); }, [&finished](auto &&err) mutable { finished = true; }); @@ -167,8 +167,8 @@ TEST_F(RpcLibp2pTest, WriteWithResponseErroredResponse) { setWriteExpectations(stream_, encoded_request_.asVector()); EXPECT_CALL(*stream_, read(_, _, _)) - .WillOnce(testing::InvokeArgument<2>( - ::outcome::failure(boost::system::error_code{}))); + .WillOnce( + testing::InvokeArgument<2>(Q_ERROR(boost::system::error_code{}))); auto finished = false; ScaleRPC::write( diff --git a/test/core/network/sync_protocol_observer_test.cpp b/test/core/network/sync_protocol_observer_test.cpp index c9be1f6f34..b526f8974e 100644 --- a/test/core/network/sync_protocol_observer_test.cpp +++ b/test/core/network/sync_protocol_observer_test.cpp @@ -98,9 +98,9 @@ TEST_F(SynchronizerTest, ProcessRequest) { .WillOnce(Return(block4_.body)); EXPECT_CALL(*tree_, getBlockJustification(block3_hash_)) - .WillOnce(Return(::outcome::failure(boost::system::error_code{}))); + .WillOnce(Return(Q_ERROR(boost::system::error_code{}))); EXPECT_CALL(*tree_, getBlockJustification(block4_hash_)) - .WillOnce(Return(::outcome::failure(boost::system::error_code{}))); + .WillOnce(Return(Q_ERROR(boost::system::error_code{}))); EXPECT_CALL(*peer_manager_mock_, reserveStatusStreams(peer_info_.id)); EXPECT_CALL(*beefy_, getJustification(_)).WillRepeatedly([] { diff --git a/test/core/network/synchronizer_test.cpp b/test/core/network/synchronizer_test.cpp index d3e5304002..de7a10c571 100644 --- a/test/core/network/synchronizer_test.cpp +++ b/test/core/network/synchronizer_test.cpp @@ -151,7 +151,7 @@ ACTION_P(blockTree_getBlockHeader, local_blocks) { } } std::cout << "Result: not found" << std::endl; - return boost::system::error_code{}; + return Q_ERROR(nullptr); } // Imitates response for block request based on generated local blockchain @@ -291,7 +291,7 @@ TEST_P(SynchronizerTest, findCommonBlock) { auto &bi = res.value(); std::cout << "Success: " << bi.hash.data() << std::endl; } else { - std::cout << "Fail: " << res.error() << std::endl; + fmt::println("Fail: {}", res.error()); } std::cout << std::endl; mock(res); diff --git a/test/core/network/types/block_attributes_test.cpp b/test/core/network/types/block_attributes_test.cpp index 18e4aad10b..8c51a1324b 100644 --- a/test/core/network/types/block_attributes_test.cpp +++ b/test/core/network/types/block_attributes_test.cpp @@ -34,13 +34,11 @@ struct BlockAttributesTest */ TEST_P(BlockAttributesTest, DecodeBlockAttributes) { auto [encoded_value, should_fail, value] = GetParam(); + auto r = decode(encoded_value); if (should_fail) { - EXPECT_OUTCOME_FALSE(err, decode(encoded_value)); - ASSERT_EQ(err.value(), - static_cast(scale::DecodeError::UNEXPECTED_VALUE)); + EXPECT_EC(r, scale::DecodeError::UNEXPECTED_VALUE); } else { - EXPECT_OUTCOME_TRUE(val, decode(encoded_value)); - ASSERT_EQ(val, value); + ASSERT_EQ(r.value(), value); } } diff --git a/test/core/network/types/block_direction_test.cpp b/test/core/network/types/block_direction_test.cpp index 1bbe84d929..d7ae3fb39d 100644 --- a/test/core/network/types/block_direction_test.cpp +++ b/test/core/network/types/block_direction_test.cpp @@ -31,13 +31,11 @@ struct DirectionTest : public ::testing::TestWithParam {}; */ TEST_P(DirectionTest, DecodeDirection) { auto [encoded_value, should_fail, value] = GetParam(); + auto r = decode(encoded_value); if (should_fail) { - EXPECT_OUTCOME_FALSE(err, decode(encoded_value)); - ASSERT_EQ(err.value(), - static_cast(scale::DecodeError::INVALID_ENUM_VALUE)); + EXPECT_EC(r, scale::DecodeError::INVALID_ENUM_VALUE); } else { - EXPECT_OUTCOME_TRUE(val, decode(encoded_value)); - ASSERT_EQ(val, value); + ASSERT_EQ(r.value(), value); } } diff --git a/test/core/network/types/message_read_writer_test.cpp b/test/core/network/types/message_read_writer_test.cpp index 03a0861db9..81d7fc2116 100644 --- a/test/core/network/types/message_read_writer_test.cpp +++ b/test/core/network/types/message_read_writer_test.cpp @@ -30,7 +30,7 @@ struct AdapterWrapper { } template - static libp2p::outcome::result::const_iterator> read( + static outcome::result::const_iterator> read( T &out, const std::vector &src, std::vector::const_iterator from) { diff --git a/test/core/network/types/protobuf_block_request_test.cpp b/test/core/network/types/protobuf_block_request_test.cpp index 3564f7b467..385f035728 100644 --- a/test/core/network/types/protobuf_block_request_test.cpp +++ b/test/core/network/types/protobuf_block_request_test.cpp @@ -14,6 +14,7 @@ using kagome::network::BlockAttributes; using kagome::network::BlocksRequest; using kagome::network::Direction; using kagome::network::ProtobufMessageAdapter; +using kagome::network::toBlockAttributes; using kagome::primitives::BlockHash; @@ -23,7 +24,7 @@ struct ProtobufBlockRequestAdapterTest : public ::testing::Test { void SetUp() { request.max = 10; request.direction = Direction::DESCENDING; - request.fields.load(0x19); + request.fields = toBlockAttributes(0x19); EXPECT_OUTCOME_TRUE( hash_from, diff --git a/test/core/storage/rocksdb/rocksdb_fs_test.cpp b/test/core/storage/rocksdb/rocksdb_fs_test.cpp index 09930b928c..c899765c45 100644 --- a/test/core/storage/rocksdb/rocksdb_fs_test.cpp +++ b/test/core/storage/rocksdb/rocksdb_fs_test.cpp @@ -33,9 +33,8 @@ TEST_F(RocksDb_Open, OpenNonExistingDB) { rocksdb::Options options; options.create_if_missing = false; // intentionally - auto r = RocksDb::create(getPathString(), options); - EXPECT_FALSE(r); - EXPECT_EQ(r.error(), DatabaseError::INVALID_ARGUMENT); + EXPECT_EC(RocksDb::create(getPathString(), options), + DatabaseError::INVALID_ARGUMENT); } /** @@ -47,7 +46,7 @@ TEST_F(RocksDb_Open, OpenExistingDB) { rocksdb::Options options; options.create_if_missing = true; // intentionally - EXPECT_OUTCOME_TRUE_2(db, RocksDb::create(getPathString(), options)); + EXPECT_OUTCOME_TRUE(db, RocksDb::create(getPathString(), options)); EXPECT_TRUE(db) << "db is nullptr"; kagome::filesystem::path p(getPathString()); diff --git a/test/core/storage/rocksdb/rocksdb_integration_test.cpp b/test/core/storage/rocksdb/rocksdb_integration_test.cpp index a59cbf3148..365a64fb87 100644 --- a/test/core/storage/rocksdb/rocksdb_integration_test.cpp +++ b/test/core/storage/rocksdb/rocksdb_integration_test.cpp @@ -41,7 +41,7 @@ TEST_F(RocksDb_Integration_Test, Put_Get) { ASSERT_OUTCOME_SUCCESS_TRY(db_->put(key_, BufferView{value_})); ASSERT_OUTCOME_SUCCESS(contains, db_->contains(key_)); EXPECT_TRUE(contains); - EXPECT_OUTCOME_TRUE_2(val, db_->get(key_)); + EXPECT_OUTCOME_TRUE(val, db_->get(key_)); EXPECT_EQ(val, value_); } @@ -54,9 +54,7 @@ TEST_F(RocksDb_Integration_Test, Get_NonExistent) { ASSERT_OUTCOME_SUCCESS(contains, db_->contains(key_)); EXPECT_FALSE(contains); ASSERT_OUTCOME_SUCCESS_TRY(db_->remove(key_)); - auto r = db_->get(key_); - EXPECT_FALSE(r); - EXPECT_EQ(r.error().value(), (int)DatabaseError::NOT_FOUND); + EXPECT_EC(db_->get(key_), DatabaseError::NOT_FOUND); } /** diff --git a/test/core/storage/trie/polkadot_trie/polkadot_trie_test.cpp b/test/core/storage/trie/polkadot_trie/polkadot_trie_test.cpp index 04fac4d641..d9bd837fdd 100644 --- a/test/core/storage/trie/polkadot_trie/polkadot_trie_test.cpp +++ b/test/core/storage/trie/polkadot_trie/polkadot_trie_test.cpp @@ -91,10 +91,8 @@ TEST_P(TrieTest, RunCommand) { ASSERT_OUTCOME_SUCCESS(val, trie->get(command.key)); ASSERT_EQ(val, command.value.value()); } else { - EXPECT_OUTCOME_FALSE(err, trie->get(command.key)); - ASSERT_EQ( - err.value(), - static_cast(kagome::storage::trie::TrieError::NO_VALUE)); + EXPECT_EC(trie->get(command.key), + kagome::storage::trie::TrieError::NO_VALUE); } break; } @@ -576,8 +574,7 @@ TEST_F(TrieTest, GetPathToInvalid) { ASSERT_OUTCOME_SUCCESS_TRY( trie->put(entry.first, BufferView{entry.second})); } - EXPECT_OUTCOME_SOME_ERROR( - _, + EXPECT_OUTCOME_FALSE_1( trie->forNodeInPath(trie->getRoot(), KeyNibbles{"0a0b0c0d0e0f"_hex2buf}, [](auto &node, auto idx, auto &child) mutable { diff --git a/test/core/storage/trie/trie_storage/polkadot_codec_node_encoding_test.cpp b/test/core/storage/trie/trie_storage/polkadot_codec_node_encoding_test.cpp index 7123b943e3..a0d7df47cd 100644 --- a/test/core/storage/trie/trie_storage/polkadot_codec_node_encoding_test.cpp +++ b/test/core/storage/trie/trie_storage/polkadot_codec_node_encoding_test.cpp @@ -29,7 +29,7 @@ struct NodeEncodingTest : public ::testing::TestWithParam { TEST_P(NodeEncodingTest, GetHeader) { auto [node, expected] = GetParam(); - EXPECT_OUTCOME_TRUE_2( + EXPECT_OUTCOME_TRUE( actual, codec->encodeHeader(*node, storage::trie::StateVersion::V0)); EXPECT_EQ(actual.toHex(), expected.toHex()); } diff --git a/test/core/storage/trie/trie_storage/trie_batch_test.cpp b/test/core/storage/trie/trie_storage/trie_batch_test.cpp index 7c84ed6726..d5bc34be26 100644 --- a/test/core/storage/trie/trie_storage/trie_batch_test.cpp +++ b/test/core/storage/trie/trie_storage/trie_batch_test.cpp @@ -200,7 +200,7 @@ TEST_F(TrieBatchTest, ConsistentOnFailure) { EXPECT_CALL(*db, put(_, _)) .After(expectation) - .WillOnce(Return(PolkadotCodec::Error::UNKNOWN_NODE_TYPE)); + .WillOnce(Return(Q_ERROR(PolkadotCodec::Error::UNKNOWN_NODE_TYPE))); auto factory = std::make_shared(); auto codec = std::make_shared(); diff --git a/test/core/storage/trie_pruner/trie_pruner_test.cpp b/test/core/storage/trie_pruner/trie_pruner_test.cpp index 2d9821d267..90552a4c1f 100644 --- a/test/core/storage/trie_pruner/trie_pruner_test.cpp +++ b/test/core/storage/trie_pruner/trie_pruner_test.cpp @@ -478,7 +478,7 @@ TEST_F(TriePrunerTest, RandomTree) { Invoke([&node_storage](auto &k) -> outcome::result { auto it = node_storage.find(k); if (it == node_storage.end()) { - return DatabaseError::NOT_FOUND; + return Q_ERROR(DatabaseError::NOT_FOUND); } return BufferOrView{it->second.view()}; })); @@ -708,7 +708,7 @@ TEST_F(TriePrunerTest, FastSyncScenario) { .WillByDefault(Invoke( [&](auto &key) -> outcome::result { if (node_storage.count(key) == 0) { - return DatabaseError::NOT_FOUND; + return Q_ERROR(DatabaseError::NOT_FOUND); } return kagome::common::BufferOrView{node_storage.at(key).view()}; })); @@ -819,7 +819,7 @@ TEST_F(TriePrunerTest, FastSyncScenario) { for (BlockNumber n = 30; n < 80; n++) { mock_header_only(n); EXPECT_CALL(*serializer_mock, retrieveTrie(headers[n].state_root, _)) - .WillRepeatedly(Return(DatabaseError::NOT_FOUND)); + .WillRepeatedly(Return(Q_ERROR(DatabaseError::NOT_FOUND))); } EXPECT_CALL(*block_tree, bestBlock()).WillOnce(Return(BlockInfo{1, {}})); diff --git a/test/core/transaction_pool/transaction_pool_test.cpp b/test/core/transaction_pool/transaction_pool_test.cpp index 2b9f7a19f4..2213b42333 100644 --- a/test/core/transaction_pool/transaction_pool_test.cpp +++ b/test/core/transaction_pool/transaction_pool_test.cpp @@ -117,16 +117,14 @@ TEST_F(TransactionPoolTest, CorrectImportToReady) { // already imported { - auto outcome = submit(*pool_.get(), {txs[0]}); - ASSERT_TRUE(outcome.has_error()); - EXPECT_EQ(outcome.error(), TransactionPoolError::TX_ALREADY_IMPORTED); + EXPECT_EC(submit(*pool_.get(), {txs[0]}), + TransactionPoolError::TX_ALREADY_IMPORTED); } // pool is full { - auto outcome = submit(*pool_.get(), {txs[4]}); - ASSERT_TRUE(outcome.has_error()); - EXPECT_EQ(outcome.error(), TransactionPoolError::POOL_IS_FULL); + EXPECT_EC(submit(*pool_.get(), {txs[4]}), + TransactionPoolError::POOL_IS_FULL); } } @@ -157,8 +155,7 @@ TEST_F(TransactionPoolTest, CorrectRemoveTx) { // tx does not exist in pool { - auto outcome = pool_->removeOne("02"_hash256); - ASSERT_TRUE(outcome.has_error()); - EXPECT_EQ(outcome.error(), TransactionPoolError::TX_NOT_FOUND); + EXPECT_EC(pool_->removeOne("02"_hash256), + TransactionPoolError::TX_NOT_FOUND); } } diff --git a/test/deps/CMakeLists.txt b/test/deps/CMakeLists.txt index 86e9430d13..84a2f680af 100644 --- a/test/deps/CMakeLists.txt +++ b/test/deps/CMakeLists.txt @@ -4,14 +4,6 @@ # SPDX-License-Identifier: Apache-2.0 # -addtest(outcome_test - outcome_test.cpp - ) -target_link_libraries(outcome_test - outcome - dummy_error - ) - addtest(formatters_test formatters_test.cpp ) diff --git a/test/deps/outcome_test.cpp b/test/deps/outcome_test.cpp deleted file mode 100644 index ff5046c285..0000000000 --- a/test/deps/outcome_test.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "outcome/outcome.hpp" - -#include -#include -#include - -#include "testutil/outcome/dummy_error.hpp" - -using std::string_literals::operator""s; - -#define ILLEGAL_CHAR_MSG "illegal char"s -#define DIV_0_MSG "division by 0"s - -enum class ConversionErrc { - SUCCESS = 0, // 0 should not represent an error - EMPTY_STRING = 1, // (for rationale, see tutorial on error codes) - ILLEGAL_CHAR = 2, - TOO_LONG = 3, -}; - -namespace sooper::loong::ns { - enum class DivisionErrc { - DIVISION_BY_ZERO = 1, - }; -} - -OUTCOME_HPP_DECLARE_ERROR(ConversionErrc) -OUTCOME_CPP_DEFINE_CATEGORY(ConversionErrc, e) { - switch (e) { - case ConversionErrc::SUCCESS: - return "success"; - case ConversionErrc::EMPTY_STRING: - return "empty string"; - case ConversionErrc::ILLEGAL_CHAR: - return ILLEGAL_CHAR_MSG; - case ConversionErrc::TOO_LONG: - return "too long"; - default: - return "unknown"; - } -} - -OUTCOME_HPP_DECLARE_ERROR(sooper::loong::ns, DivisionErrc) -OUTCOME_CPP_DEFINE_CATEGORY(sooper::loong::ns, DivisionErrc, e) { - using sooper::loong::ns::DivisionErrc; - switch (e) { - case DivisionErrc::DIVISION_BY_ZERO: - return "division by 0"; - default: - return "unknown"; - } -} - -outcome::result convert(const std::string &str) { - if (str.empty()) { - return ConversionErrc::EMPTY_STRING; - } - - if (!std::all_of(str.begin(), str.end(), ::isdigit)) { - return ConversionErrc::ILLEGAL_CHAR; - } - - if (str.length() > 9) { - return ConversionErrc::TOO_LONG; - } - - return atoi(str.c_str()); -} - -outcome::result divide(int a, int b) { - using sooper::loong::ns::DivisionErrc; - if (b == 0) { - return DivisionErrc::DIVISION_BY_ZERO; - } - - return a / b; -} - -outcome::result convert_and_divide(const std::string &a, - const std::string &b) { - OUTCOME_TRY(valA, convert(a)); - OUTCOME_TRY(valB, convert(b)); - OUTCOME_TRY(valDiv, divide(valA, valB)); - return valDiv; -} - -/** - * @given valid arguments for convert_and_divide - * @when execute method which returns result - * @then returns value - */ -TEST(Outcome, CorrectCase) { - auto r = convert_and_divide("500", "2"); - ASSERT_TRUE(r); - auto &&val = r.value(); - ASSERT_EQ(val, 250); -} - -/** - * @given arguments to cause conversion error for convert_and_divide - * @when execute method which returns result - * @then returns error - */ -TEST(Outcome, ConversionError) { - auto r = convert_and_divide("500", "a"); - ASSERT_FALSE(r); - auto &&err = r.error(); - ASSERT_EQ(err.message(), ILLEGAL_CHAR_MSG); -} - -/** - * @given arguments to cause division error for convert_and_divide - * @when execute method which returns result - * @then returns error - */ -TEST(Outcome, DivisionError) { - auto r = convert_and_divide("500", "0"); - ASSERT_FALSE(r); - auto &&err = r.error(); - ASSERT_EQ(err.message(), DIV_0_MSG); // name of the enum - using sooper::loong::ns::DivisionErrc; - ASSERT_EQ(err.category().name(), typeid(DivisionErrc).name()); -} - -TEST(Outcome, FormatterStdErrorCore) { - auto error = make_error_code(testutil::DummyError::ERROR); - - auto expected = error.message(); - - auto actual = fmt::format("{}", error); - EXPECT_EQ(actual, expected); -} - -TEST(Outcome, FormatterBoostSystemErrorCode) { - boost::system::error_code ec; - - auto expected = ec.message(); - - auto actual = fmt::format("{}", ec); - EXPECT_EQ(actual, expected); -} - -TEST(Outcome, FormatterVoidSuccess) { - auto success = outcome::success(); - - auto expected = ""; - - auto actual = fmt::format("{}", success); - EXPECT_EQ(actual, expected); -} - -TEST(Outcome, FormatterNonVoidSuccess) { - std::string data("Yahoo!"); - auto success = outcome::success(data); - - auto expected = data; - - auto actual = fmt::format("{}", success); - EXPECT_EQ(actual, expected); -} - -TEST(Outcome, FormatterResultSuccess) { - auto outcome = outcome::result("Yahoo!"); - - auto expected = outcome.value(); - - auto actual = fmt::format("{}", outcome); - EXPECT_EQ(actual, expected); -} - -TEST(Outcome, FormatterResultFailure) { - auto outcome = outcome::result(testutil::DummyError::ERROR); - - auto expected = outcome.error().message(); - - auto actual = fmt::format("{}", outcome); - EXPECT_EQ(actual, expected); -} diff --git a/test/mock/core/api/transport/jrpc_processor_stub.hpp b/test/mock/core/api/transport/jrpc_processor_stub.hpp index b11b96eaad..dc29b62f14 100644 --- a/test/mock/core/api/transport/jrpc_processor_stub.hpp +++ b/test/mock/core/api/transport/jrpc_processor_stub.hpp @@ -37,7 +37,7 @@ namespace kagome::api { auto &&nonce = parseParams(params); auto &&res = api_->echo(nonce); if (!res) { - throw jsonrpc::Fault(res.error().message()); + throw jsonrpc::Fault(fmt::to_string(res.error())); } return jsonrpc::Value(res.value()); }); diff --git a/test/testutil/outcome.hpp b/test/testutil/outcome.hpp index 351ac9cd60..fba2ba7df6 100644 --- a/test/testutil/outcome.hpp +++ b/test/testutil/outcome.hpp @@ -10,19 +10,13 @@ #include "common/visitor.hpp" #include "outcome/outcome.hpp" -#define PP_CAT(a, b) PP_CAT_I(a, b) -#define PP_CAT_I(a, b) PP_CAT_II(~, a##b) -#define PP_CAT_II(p, res) res - -#define UNIQUE_NAME(base) PP_CAT(base, __LINE__) - -#define EXPECT_OUTCOME_TRUE_void(var, expr) \ - auto &&var = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << var.error().message(); +#define EXPECT_OUTCOME_TRUE_void(var, expr) \ + auto &&var = expr; \ + EXPECT_TRUE(var) << "Line " << __LINE__ << ": " \ + << fmt::to_string(var.error()); -#define EXPECT_OUTCOME_TRUE_name(var, val, expr) \ - auto &&var = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << var.error().message(); \ +#define EXPECT_OUTCOME_TRUE_name(var, val, expr) \ + EXPECT_OUTCOME_TRUE_void(var, expr); \ auto &&val = var.value(); #define EXPECT_OUTCOME_FALSE_void(var, expr) \ @@ -34,23 +28,11 @@ EXPECT_FALSE(var); \ auto &&val = var.error(); -#define EXPECT_OUTCOME_TRUE_3(var, val, expr) \ - EXPECT_OUTCOME_TRUE_name(var, val, expr) - -#define EXPECT_OUTCOME_TRUE_2(val, expr) \ - EXPECT_OUTCOME_TRUE_3(UNIQUE_NAME(_r), val, expr) - #define EXPECT_OUTCOME_TRUE_1(expr) \ - EXPECT_OUTCOME_TRUE_void(UNIQUE_NAME(_v), expr) - -#define EXPECT_OUTCOME_FALSE_3(var, val, expr) \ - EXPECT_OUTCOME_FALSE_name(var, val, expr) - -#define EXPECT_OUTCOME_FALSE_2(val, expr) \ - EXPECT_OUTCOME_FALSE_3(UNIQUE_NAME(_r), val, expr) + EXPECT_OUTCOME_TRUE_void(OUTCOME_UNIQUE, expr) #define EXPECT_OUTCOME_FALSE_1(expr) \ - EXPECT_OUTCOME_FALSE_void(UNIQUE_NAME(_v), expr) + EXPECT_OUTCOME_FALSE_void(OUTCOME_UNIQUE, expr) /** * Use this macro in GTEST with 2 arguments to assert that getResult() @@ -58,146 +40,20 @@ * EXPECT_OUTCOME_TRUE(val, getResult()); */ #define EXPECT_OUTCOME_TRUE(val, expr) \ - EXPECT_OUTCOME_TRUE_name(UNIQUE_NAME(_r), val, expr) + EXPECT_OUTCOME_TRUE_name(OUTCOME_UNIQUE, val, expr) #define EXPECT_OUTCOME_FALSE(val, expr) \ - EXPECT_OUTCOME_FALSE_name(UNIQUE_NAME(_f), val, expr) - -#define EXPECT_OUTCOME_TRUE_MSG_void(var, expr, msg) \ - auto &&var = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << var.error().message() \ - << "\t" << (msg); - -#define EXPECT_OUTCOME_TRUE_MSG_name(var, val, expr, msg) \ - auto &&var = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << var.error().message() \ - << "\t" << (msg); \ - auto &&val = var.value(); - -/** - * Use this macro in GTEST with 2 arguments to assert that - * result of expression as outcome::result is value and, - * but the value itself is not necessary. - * If result is error, macro prints corresponding error message - * and appends custom error message specified in msg. - */ -#define EXPECT_OUTCOME_TRUE_MSG_1(expr, msg) \ - EXPECT_OUTCOME_TRUE_MSG_void(UNIQUE_NAME(_v), expr, msg) - -/** - * Use this macro in GTEST with 3 arguments to assert that - * result of expression as outcome::result is value and - * immediately get access to this value. - * If result is error, macro prints corresponding error message - * and appends custom error message specified in msg. - */ -#define EXPECT_OUTCOME_TRUE_MSG(val, expr, msg) \ - EXPECT_OUTCOME_TRUE_MSG_name(UNIQUE_NAME(_r), val, expr, msg) - -#define EXPECT_OUTCOME_RAISE_3(var, ecode, statement) \ - try { \ - statement; \ - FAIL() << "Line " << __LINE__ << ": " << #ecode << " not raised"; \ - } catch (std::system_error & var) { \ - EXPECT_EQ(var.code(), ecode); \ - } - -#define EXPECT_OUTCOME_RAISE(ecode, statement) \ - EXPECT_OUTCOME_RAISE_3(UNIQUE_NAME(_e), ecode, statement) - -#define EXPECT_OUTCOME_ERROR_3(var, ecode, expr) \ - { \ - EXPECT_OUTCOME_FALSE_2(var, expr); \ - EXPECT_EQ(var, ecode); \ - } - -#define EXPECT_OUTCOME_EQ_3(var, expr, value) \ - { \ - EXPECT_OUTCOME_TRUE_2(var, expr); \ - EXPECT_EQ(var, value); \ - } - -#define EXPECT_OUTCOME_EQ(expr, value) \ - EXPECT_OUTCOME_EQ_3(UNIQUE_NAME(_v), expr, value) - -#define _OUTCOME_UNIQUE_NAME_GLUE2(x, y) x##y -#define _OUTCOME_UNIQUE_NAME_GLUE(x, y) _OUTCOME_UNIQUE_NAME_GLUE2(x, y) -#define _OUTCOME_UNIQUE_NAME \ - _OUTCOME_UNIQUE_NAME_GLUE(__outcome_result, __COUNTER__) - -#define _ASSERT_OUTCOME_SUCCESS_TRY(_result_, _expression_) \ - auto &&_result_ = (_expression_); \ - if (not(_result_).has_value()) { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << _result_.error().message() << "'\n" \ - << "Expected: Success"; \ - } - -#define _ASSERT_OUTCOME_SUCCESS(_result_, _variable_, _expression_) \ - _ASSERT_OUTCOME_SUCCESS_TRY(_result_, _expression_); \ - auto &&_variable_ = std::move(_result_.value()); - -#define ASSERT_OUTCOME_SUCCESS(_variable_, _expression_) \ - _ASSERT_OUTCOME_SUCCESS(_OUTCOME_UNIQUE_NAME, _variable_, _expression_) - -#define ASSERT_OUTCOME_SUCCESS_TRY(_expression_) \ - { _ASSERT_OUTCOME_SUCCESS_TRY(_OUTCOME_UNIQUE_NAME, _expression_); } - -#define ASSERT_OUTCOME_SOME_ERROR(_expression_) \ - { \ - auto &&result = (_expression_); \ - if (not result.has_error()) { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Some error"; \ - } \ - } - -#define ASSERT_OUTCOME_ERROR(_expression_, _error_) \ - { \ - auto &&result = (_expression_); \ - if (result.has_error()) { \ - if (result != outcome::failure(_error_)) { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << result.error().message() << "'\n" \ - << "Expected: Error '" << make_error_code(_error_).message() \ - << "'"; \ - } \ - } else { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Error '" << make_error_code(_error_).message() \ - << "'"; \ - } \ - } - -#define EXPECT_OUTCOME_SUCCESS(_result_, _expression_) \ - [[maybe_unused]] auto &&_result_ = (_expression_); \ - if (_result_.has_error()) { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << _result_.error().message() << "'\n" \ - << "Expected: Success"; \ - } - -#define EXPECT_OUTCOME_SOME_ERROR(_result_, _expression_) \ - [[maybe_unused]] auto &&_result_ = (_expression_); \ - if (not _result_.has_error()) { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Some error"; \ - } - -#define EXPECT_OUTCOME_ERROR(_result_, _expression_, _error_) \ - [[maybe_unused]] auto &&_result_ = (_expression_); \ - if (_result_.has_error()) { \ - if (_result_ != outcome::failure(_error_)) { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << _result_.error().message() << "'\n" \ - << "Expected: Error '" << make_error_code(_error_).message() \ - << "'"; \ - } \ - } else { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Error '" << make_error_code(_error_).message() << "'"; \ - } + EXPECT_OUTCOME_FALSE_name(OUTCOME_UNIQUE, val, expr) + +// TODO: ambigous duplicates +#define ASSERT_OUTCOME_ERROR EXPECT_EC +#define ASSERT_OUTCOME_SUCCESS EXPECT_OUTCOME_TRUE +#define ASSERT_OUTCOME_SUCCESS_TRY EXPECT_OUTCOME_TRUE_1 +#define EXPECT_OUTCOME_ERROR(unused, expr, expected) EXPECT_EC(expr, expected) +#define EXPECT_OUTCOME_SUCCESS(tmp, expr) EXPECT_OUTCOME_TRUE_void(tmp, expr) + +#define _EXPECT_EC(tmp, expr, expected) \ + auto &&tmp = expr; \ + EXPECT_TRUE(tmp.has_error()); \ + EXPECT_TRUE(tmp.error().ec(expected)); +#define EXPECT_EC(expr, expected) _EXPECT_EC(OUTCOME_UNIQUE, expr, expected) diff --git a/test/testutil/outcome/dummy_error.hpp b/test/testutil/outcome/dummy_error.hpp index a6435e91f4..b04f2b277c 100644 --- a/test/testutil/outcome/dummy_error.hpp +++ b/test/testutil/outcome/dummy_error.hpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "outcome/outcome.hpp" +#include namespace testutil { /** diff --git a/test/testutil/storage/base_rocksdb_test.cpp b/test/testutil/storage/base_rocksdb_test.cpp index 85e768317f..497151ea5c 100644 --- a/test/testutil/storage/base_rocksdb_test.cpp +++ b/test/testutil/storage/base_rocksdb_test.cpp @@ -13,10 +13,6 @@ namespace test { options.create_if_missing = true; auto r = RocksDB::create(getPathString(), options); - if (!r) { - throw std::invalid_argument(r.error().message()); - } - rocks_ = std::move(r.value()); db_ = rocks_->getSpace(kagome::storage::Space::kDefault); ASSERT_TRUE(rocks_) << "BaseRocksDB_Test: db is nullptr"; From 5f754ec1609aebf14ab9a03359b5a03b38fabb1f Mon Sep 17 00:00:00 2001 From: turuslan Date: Mon, 13 Nov 2023 11:33:32 +0300 Subject: [PATCH 2/2] qtils hex Signed-off-by: turuslan --- cmake/Hunter/hunter-gate-url.cmake | 2 +- core/api/jrpc/decode_args.hpp | 16 +--- core/api/jrpc/value_converter.hpp | 6 +- core/authority_discovery/query/query_impl.cpp | 5 +- core/common/buffer_or_view.hpp | 9 --- core/common/buffer_view.hpp | 41 +--------- core/common/bytestr.hpp | 33 -------- core/common/hexutil.cpp | 80 +++---------------- core/common/hexutil.hpp | 27 +------ .../lexicographical_compare_three_way.hpp | 71 ---------------- core/common/size_limited_containers.hpp | 7 -- core/common/unused.hpp | 12 +++ .../crypto/crypto_store/crypto_store_impl.cpp | 5 +- core/crypto/crypto_store/key_type.cpp | 9 ++- core/host_api/impl/misc_extension.cpp | 4 +- core/host_api/impl/offchain_extension.cpp | 28 +++---- core/injector/get_peer_keypair.hpp | 4 +- core/network/adapters/light.hpp | 13 +-- .../adapters/protobuf_block_response.hpp | 11 +-- core/storage/map_prefix/prefix.cpp | 4 +- core/storage/trie/polkadot_trie/trie_node.hpp | 1 - .../trie/serialization/buffer_stream.hpp | 2 +- core/utils/storage_explorer.cpp | 7 +- .../core/api/service/state/state_api_test.cpp | 12 +-- test/core/common/buffer_test.cpp | 2 + test/core/common/hexutil_test.cpp | 52 +----------- test/core/crypto/blake2/blake2_test.cpp | 4 +- test/core/crypto/hasher/hasher_test.cpp | 2 + test/core/crypto/twox/twox_test.cpp | 2 + test/core/host_api/crypto_extension_test.cpp | 3 +- test/core/host_api/io_extension_test.cpp | 2 + test/testutil/literals.hpp | 25 ------ .../storage/polkadot_trie_printer.hpp | 2 +- 33 files changed, 104 insertions(+), 399 deletions(-) delete mode 100644 core/common/bytestr.hpp delete mode 100644 core/common/lexicographical_compare_three_way.hpp diff --git a/cmake/Hunter/hunter-gate-url.cmake b/cmake/Hunter/hunter-gate-url.cmake index 14b32649dc..940061362c 100644 --- a/cmake/Hunter/hunter-gate-url.cmake +++ b/cmake/Hunter/hunter-gate-url.cmake @@ -1,5 +1,5 @@ HunterGate( URL https://github.com/qdrvm/hunter/archive/refs/heads/turuslan/qtils.zip - SHA1 219b754308ac6bab96ece8b560cd84c5a10323db + SHA1 dd50fb297ba2d57bee6cb047beb81d433550da52 LOCAL ) diff --git a/core/api/jrpc/decode_args.hpp b/core/api/jrpc/decode_args.hpp index 79c8de4929..b333ad3c16 100644 --- a/core/api/jrpc/decode_args.hpp +++ b/core/api/jrpc/decode_args.hpp @@ -7,6 +7,7 @@ #pragma once #include +#include #include "primitives/mmr.hpp" @@ -99,21 +100,12 @@ namespace kagome::api::details { template static void loadValue(common::Blob &out, const jsonrpc::Value &j) { - auto &s = j.AsString(); - if (s.starts_with("0x")) { - out = unwrap(out.fromHexWithPrefix(s)); - } else { - out = unwrap(out.fromHex(s)); - } + out = unwrap( + qtils::unhex>(j.AsString(), qtils::Unhex0x::Yes)); } static void loadValue(common::Buffer &out, const jsonrpc::Value &j) { - auto &s = j.AsString(); - if (s.starts_with("0x")) { - out = unwrap(common::unhexWith0x(s)); - } else { - out = unwrap(common::unhex(s)); - } + out = unwrap(qtils::unhex(j.AsString(), qtils::Unhex0x::Yes)); } static void loadValue(primitives::MmrLeavesProof &out, diff --git a/core/api/jrpc/value_converter.hpp b/core/api/jrpc/value_converter.hpp index 3d6fe1eca8..d74c96b9b6 100644 --- a/core/api/jrpc/value_converter.hpp +++ b/core/api/jrpc/value_converter.hpp @@ -153,15 +153,15 @@ namespace kagome::api { template inline jsonrpc::Value makeValue(const common::Blob &val) { - return common::hex_lower_0x(val.data(), val.size()); + return common::hex_lower_0x(val); } inline jsonrpc::Value makeValue(const common::Buffer &val) { - return common::hex_lower_0x(val.asVector().data(), val.asVector().size()); + return common::hex_lower_0x(val); } inline jsonrpc::Value makeValue(common::BufferView val) { - return common::hex_lower_0x(val.data(), val.size()); + return common::hex_lower_0x(val); } inline jsonrpc::Value makeValue(const primitives::DigestItem &val) { diff --git a/core/authority_discovery/query/query_impl.cpp b/core/authority_discovery/query/query_impl.cpp index 0cd2eb741d..eb01a5004d 100644 --- a/core/authority_discovery/query/query_impl.cpp +++ b/core/authority_discovery/query/query_impl.cpp @@ -6,9 +6,10 @@ #include "authority_discovery/query/query_impl.hpp" +#include + #include "authority_discovery/protobuf/authority_discovery.v2.pb.h" #include "common/buffer_view.hpp" -#include "common/bytestr.hpp" #include "crypto/sha/sha256.hpp" OUTCOME_CPP_DEFINE_CATEGORY(kagome::authority_discovery, QueryImpl::Error, e) { @@ -27,6 +28,8 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::authority_discovery, QueryImpl::Error, e) { } namespace kagome::authority_discovery { + using qtils::str2byte; + constexpr size_t kMaxActiveRequests = 8; constexpr std::chrono::seconds kIntervalInitial{2}; constexpr std::chrono::minutes kIntervalMax{10}; diff --git a/core/common/buffer_or_view.hpp b/core/common/buffer_or_view.hpp index b8d1b71f0e..f745432731 100644 --- a/core/common/buffer_or_view.hpp +++ b/core/common/buffer_or_view.hpp @@ -100,15 +100,6 @@ namespace kagome::common { private: boost::variant variant; - - template > - friend bool operator==(const BufferOrView &l, const T &r) { - return l.view() == Span{r}; - } - template > - friend bool operator==(const T &l, const BufferOrView &r) { - return Span{l} == r.view(); - } }; } // namespace kagome::common diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index 37943d813d..4ab0e9c50a 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -6,15 +6,11 @@ #pragma once -#include +#include #include "common/hexutil.hpp" -#include "common/lexicographical_compare_three_way.hpp" #include "macro/endianness_utils.hpp" -#include -#include - inline auto operator""_bytes(const char *s, std::size_t size) { return std::span(reinterpret_cast(s), size); } @@ -42,43 +38,14 @@ namespace kagome::common { return span::operator=(std::forward(t)); } - template - void dropFirst() { - *this = subspan(); - } - - void dropFirst(size_t count) { - *this = subspan(count); - } - - template - void dropLast() { - *this = first(size() - count); - } - - void dropLast(size_t count) { - *this = first(size() - count); - } - std::string toHex() const { return hex_lower(*this); } - - std::string_view toStringView() const { - // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) - return {reinterpret_cast(data()), size()}; - } - - auto operator<=>(const BufferView &other) const noexcept { - return cxx20::lexicographical_compare_three_way( - span::begin(), span::end(), other.begin(), other.end()); - } - - auto operator==(const BufferView &other) const noexcept { - return (*this <=> other) == std::strong_ordering::equal; - } }; + using qtils::operator<=>; + using qtils::operator==; + inline std::ostream &operator<<(std::ostream &os, BufferView view) { return os << view.toHex(); } diff --git a/core/common/bytestr.hpp b/core/common/bytestr.hpp deleted file mode 100644 index 30be0639d1..0000000000 --- a/core/common/bytestr.hpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include -#include - -#include "common/buffer.hpp" -#include "common/buffer_view.hpp" - -namespace kagome { - - inline common::BufferView str2byte(std::span s) { - // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) - return {reinterpret_cast(s.data()), s.size()}; - } - - inline std::string_view byte2str(const common::BufferView &s) { - // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) - return {reinterpret_cast(s.data()), s.size()}; - } - - inline common::Buffer bytestr_copy(std::string_view s) { - // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) - return common::BufferView{reinterpret_cast(s.data()), - s.size()}; - } - -} // namespace kagome diff --git a/core/common/hexutil.cpp b/core/common/hexutil.cpp index 27222aa40f..f35bf0d454 100644 --- a/core/common/hexutil.cpp +++ b/core/common/hexutil.cpp @@ -6,9 +6,8 @@ #include "common/hexutil.hpp" -#include - -#include "common/buffer_view.hpp" +#include +#include OUTCOME_CPP_DEFINE_CATEGORY(kagome::common, UnhexError, e) { using kagome::common::UnhexError; @@ -28,80 +27,19 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::common, UnhexError, e) { } namespace kagome::common { - - std::string int_to_hex(uint64_t n, size_t fixed_width) noexcept { - std::stringstream result; - result.width(fixed_width); - result.fill('0'); - result << std::hex << std::uppercase << n; - auto str = result.str(); - if (str.length() % 2 != 0) { - str.push_back('\0'); - for (int64_t i = str.length() - 2; i >= 0; --i) { - str[i + 1] = str[i]; - } - str[0] = '0'; - } - return str; + std::string hex_lower(qtils::BytesIn bytes) noexcept { + return fmt::format("{:x}", bytes); } - std::string hex_upper(BufferView bytes) noexcept { - std::string res(bytes.size() * 2, '\x00'); - boost::algorithm::hex(bytes.begin(), bytes.end(), res.begin()); - return res; - } - - std::string hex_lower(BufferView bytes) noexcept { - std::string res(bytes.size() * 2, '\x00'); - boost::algorithm::hex_lower(bytes.begin(), bytes.end(), res.begin()); - return res; - } - - std::string hex_lower_0x(BufferView bytes) noexcept { - constexpr char prefix[] = {'0', 'x'}; - constexpr size_t prefix_len = sizeof(prefix); - - std::string res(bytes.size() * 2 + prefix_len, '\x00'); - res.replace(0, prefix_len, prefix, prefix_len); - - boost::algorithm::hex_lower( - bytes.begin(), bytes.end(), res.begin() + prefix_len); - return res; - } - - std::string hex_lower_0x(const uint8_t *data, size_t size) noexcept { - return hex_lower_0x(BufferView(data, size)); + std::string hex_lower_0x(qtils::BytesIn bytes) noexcept { + return fmt::format("{:0x}", bytes); } outcome::result> unhex(std::string_view hex) { - std::vector blob; - blob.reserve((hex.size() + 1) / 2); - - try { - boost::algorithm::unhex(hex.begin(), hex.end(), std::back_inserter(blob)); - return blob; - - } catch (const boost::algorithm::not_enough_input &e) { - return Q_ERROR(UnhexError::NOT_ENOUGH_INPUT); - - } catch (const boost::algorithm::non_hex_input &e) { - return Q_ERROR(UnhexError::NON_HEX_INPUT); - - } catch (const std::exception &e) { - return Q_ERROR(UnhexError::UNKNOWN); - } + return qtils::unhex(hex, qtils::Unhex0x::No); } - outcome::result> unhexWith0x( - std::string_view hex_with_prefix) { - static const std::string leading_chrs = "0x"; - - if (hex_with_prefix.substr(0, leading_chrs.size()) != leading_chrs) { - return Q_ERROR(UnhexError::MISSING_0X_PREFIX); - } - - auto without_prefix = hex_with_prefix.substr(leading_chrs.size()); - - return common::unhex(without_prefix); + outcome::result> unhexWith0x(std::string_view hex) { + return qtils::unhex(hex, qtils::Unhex0x::Yes); } } // namespace kagome::common diff --git a/core/common/hexutil.hpp b/core/common/hexutil.hpp index f261b91be1..d6d4017839 100644 --- a/core/common/hexutil.hpp +++ b/core/common/hexutil.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include #include @@ -13,9 +14,6 @@ #include "outcome/outcome.hpp" namespace kagome::common { - - class BufferView; - /** * @brief error codes for exceptions that may occur during unhexing */ @@ -31,39 +29,20 @@ namespace kagome::common { OUTCOME_HPP_DECLARE_ERROR(kagome::common, UnhexError); namespace kagome::common { - - /** - * @brief Converts an integer to an uppercase hex representation - */ - std::string int_to_hex(uint64_t n, size_t fixed_width = 2) noexcept; - - /** - * @brief Converts bytes to uppercase hex representation - * @param array bytes - * @param len length of bytes - * @return hexstring - */ - std::string hex_upper(BufferView bytes) noexcept; - /** * @brief Converts bytes to hex representation * @param array bytes * @param len length of bytes * @return hexstring */ - std::string hex_lower(BufferView bytes) noexcept; + std::string hex_lower(qtils::BytesIn bytes) noexcept; /** * @brief Converts bytes to hex representation with prefix 0x * @param array bytes * @return hexstring */ - std::string hex_lower_0x(BufferView bytes) noexcept; - - /** - * @brief Adapter for ptr+size - */ - std::string hex_lower_0x(const uint8_t *data, size_t size) noexcept; + std::string hex_lower_0x(qtils::BytesIn bytes) noexcept; /** * @brief Converts hex representation to bytes diff --git a/core/common/lexicographical_compare_three_way.hpp b/core/common/lexicographical_compare_three_way.hpp deleted file mode 100644 index 35a2689d71..0000000000 --- a/core/common/lexicographical_compare_three_way.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#ifdef __APPLE__ -#include -#include -#else -#include -#endif - -namespace cxx20 { -#ifdef __APPLE__ - /// https://en.cppreference.com/w/cpp/algorithm/lexicographical_compare_three_way - template - constexpr auto lexicographical_compare_three_way( - I1 f1, I1 l1, I2 f2, I2 l2, Cmp comp) -> decltype(comp(*f1, *f2)) { - using ret_t = decltype(comp(*f1, *f2)); - static_assert( - std::disjunction_v, - std::is_same, - std::is_same>, - "The return type must be a comparison category type."); - - bool exhaust1 = (f1 == l1); - bool exhaust2 = (f2 == l2); - for (; !exhaust1 && !exhaust2; - exhaust1 = (++f1 == l1), exhaust2 = (++f2 == l2)) { - if (auto c = comp(*f1, *f2); c != 0) { - return c; - } - } - - return !exhaust1 ? std::strong_ordering::greater - : !exhaust2 ? std::strong_ordering::less - : std::strong_ordering::equal; - } - -#if !defined(__cpp_lib_three_way_comparison) - // primarily fix for AppleClang < 15 - - // clang-format off - // https://github.com/llvm/llvm-project/blob/main/libcxx/include/__compare/compare_three_way.h - struct _LIBCPP_TEMPLATE_VIS compare_three_way - { - template - constexpr _LIBCPP_HIDE_FROM_ABI - auto operator()(_T1&& __t, _T2&& __u) const - noexcept(noexcept(_VSTD::forward<_T1>(__t) <=> _VSTD::forward<_T2>(__u))) - { return _VSTD::forward<_T1>(__t) <=> _VSTD::forward<_T2>(__u); } - - using is_transparent = void; - }; - // clang-format on -#else - using compare_three_way = std::compare_three_way; -#endif - - template - constexpr auto lexicographical_compare_three_way(I1 f1, I1 l1, I2 f2, I2 l2) { - return ::cxx20::lexicographical_compare_three_way( - f1, l1, f2, l2, compare_three_way{}); - } -#else - using std::lexicographical_compare_three_way; -#endif -} // namespace cxx20 diff --git a/core/common/size_limited_containers.hpp b/core/common/size_limited_containers.hpp index e62a014626..f8724c2639 100644 --- a/core/common/size_limited_containers.hpp +++ b/core/common/size_limited_containers.hpp @@ -13,8 +13,6 @@ #include #include -#include "common/lexicographical_compare_three_way.hpp" - namespace kagome::common { class MaxSizeException : public std::length_error { @@ -361,11 +359,6 @@ namespace kagome::common { } return Base::resize(size, value); } - - auto operator<=>(const SizeLimitedContainer &other) const { - return cxx20::lexicographical_compare_three_way( - Base::begin(), Base::end(), other.begin(), other.end()); - } }; template diff --git a/core/common/unused.hpp b/core/common/unused.hpp index 5343797573..761b7e6687 100644 --- a/core/common/unused.hpp +++ b/core/common/unused.hpp @@ -6,6 +6,8 @@ #pragma once +#include + #include "common/empty.hpp" #include "common/tagged.hpp" @@ -15,6 +17,16 @@ namespace kagome { AttemptToEncodeUnused = 1, AttemptToDecodeUnused, }; + Q_ENUM_ERROR_CODE(UnusedError) { + using E = decltype(e); + switch (e) { + case E::AttemptToEncodeUnused: + return "UnusedError::AttemptToEncodeUnused"; + case E::AttemptToDecodeUnused: + return "UnusedError::AttemptToDecodeUnused"; + } + abort(); + } /// Number-based marker-type for using as tag template diff --git a/core/crypto/crypto_store/crypto_store_impl.cpp b/core/crypto/crypto_store/crypto_store_impl.cpp index 18dd146391..5a18ad39fe 100644 --- a/core/crypto/crypto_store/crypto_store_impl.cpp +++ b/core/crypto/crypto_store/crypto_store_impl.cpp @@ -6,9 +6,8 @@ #include "crypto/crypto_store/crypto_store_impl.hpp" -#include +#include -#include "common/bytestr.hpp" #include "common/visitor.hpp" #include "utils/read_file.hpp" @@ -193,7 +192,7 @@ namespace kagome::crypto { or 2 * ED25519_SEED_LENGTH == contents.size()); // hex Ed25519Seed seed; if (ED25519_SEED_LENGTH == contents.size()) { - OUTCOME_TRY(_seed, Ed25519Seed::fromSpan(str2byte(contents))); + OUTCOME_TRY(_seed, Ed25519Seed::fromSpan(qtils::str2byte(contents))); seed = _seed; } else if (2 * ED25519_SEED_LENGTH == contents.size()) { // hex-encoded OUTCOME_TRY(_seed, Ed25519Seed::fromHex(contents)); diff --git a/core/crypto/crypto_store/key_type.cpp b/core/crypto/crypto_store/key_type.cpp index d31cfd1cc1..d7a5042299 100644 --- a/core/crypto/crypto_store/key_type.cpp +++ b/core/crypto/crypto_store/key_type.cpp @@ -6,10 +6,11 @@ #include "crypto/crypto_store/key_type.hpp" +#include +#include #include #include "common/blob.hpp" -#include "common/bytestr.hpp" namespace kagome::crypto { @@ -40,7 +41,9 @@ namespace kagome::crypto { } std::string encodeKeyFileName(const KeyType &type, common::BufferView key) { - return common::hex_lower(str2byte(encodeKeyTypeToStr(type))) + key.toHex(); + return fmt::format("{:x}{:x}", + qtils::str2byte(encodeKeyTypeToStr(type)), + qtils::BytesIn{key}); } outcome::result> decodeKeyFileName( @@ -53,7 +56,7 @@ namespace kagome::crypto { } OUTCOME_TRY(type_raw, common::Blob<4>::fromHex(type_str)); OUTCOME_TRY(key, common::Buffer::fromHex(key_str)); - return std::make_pair(decodeKeyTypeFromStr(byte2str(type_raw)), + return std::make_pair(decodeKeyTypeFromStr(qtils::byte2str(type_raw)), std::move(key)); } } // namespace kagome::crypto diff --git a/core/host_api/impl/misc_extension.cpp b/core/host_api/impl/misc_extension.cpp index d2d5633f2c..d9f6a9a6a1 100644 --- a/core/host_api/impl/misc_extension.cpp +++ b/core/host_api/impl/misc_extension.cpp @@ -6,6 +6,8 @@ #include "host_api/impl/misc_extension.hpp" +#include + #include "log/trace_macros.hpp" #include "primitives/version.hpp" #include "runtime/common/uncompress_code_if_needed.hpp" @@ -84,7 +86,7 @@ namespace kagome::host_api { runtime::WasmSpan data) const { auto [ptr, len] = runtime::splitSpan(data); auto buf = memory_provider_->getCurrentMemory()->get().loadN(ptr, len); - logger_->info("utf8: {}", buf.toStringView()); + logger_->info("utf8: {}", qtils::byte2str(buf)); } } // namespace kagome::host_api diff --git a/core/host_api/impl/offchain_extension.cpp b/core/host_api/impl/offchain_extension.cpp index 01922368b4..daa82836e0 100644 --- a/core/host_api/impl/offchain_extension.cpp +++ b/core/host_api/impl/offchain_extension.cpp @@ -6,8 +6,8 @@ #include "host_api/impl/offchain_extension.hpp" +#include #include -#include #include "log/trace_macros.hpp" #include "offchain/offchain_worker.hpp" @@ -238,44 +238,42 @@ namespace kagome::host_api { auto &memory = memory_provider_->getCurrentMemory()->get(); auto [method_ptr, method_size] = runtime::PtrSize(method_pos); - auto method_buffer = memory.loadN(method_ptr, method_size); + auto method_str = qtils::byte2str(memory.loadN(method_ptr, method_size)); auto [uri_ptr, uri_size] = runtime::PtrSize(uri_pos); - auto uri_buffer = memory.loadN(uri_ptr, uri_size); - auto uri = uri_buffer.toStringView(); + auto uri = qtils::byte2str(memory.loadN(uri_ptr, uri_size)); auto [meta_ptr, meta_size] = runtime::PtrSize(meta_pos); [[maybe_unused]] // It is future-reserved field, is not used now auto meta_buffer = memory.loadN(meta_ptr, meta_size); HttpMethod method = HttpMethod::Undefined; - if (method_buffer.toStringView() == "Get") { + if (method_str == "Get") { method = HttpMethod::Get; - } else if (method_buffer.toStringView() == "Post") { + } else if (method_str == "Post") { method = HttpMethod::Post; } else { SL_TRACE( log_, "ext_offchain_http_request_start_version_1( {}, {}, {} ) failed: " "Reason: unknown method", - method_buffer.toStringView(), + method_str, uri, - meta_buffer.toStringView()); + qtils::byte2str(meta_buffer)); } auto result = worker->httpRequestStart(method, uri, meta_buffer); if (result.isSuccess()) { - SL_TRACE_FUNC_CALL( - log_, result.value(), method_buffer.toStringView(), uri, meta_buffer); + SL_TRACE_FUNC_CALL(log_, result.value(), method_str, uri, meta_buffer); } else { SL_TRACE(log_, "ext_offchain_http_request_start_version_1( {}, {}, {} ) failed " "during execution", - method_buffer.toStringView(), + method_str, uri, - meta_buffer.toStringView()); + qtils::byte2str(meta_buffer)); } return memory.storeBuffer(scale::encode(result).value()); @@ -291,12 +289,10 @@ namespace kagome::host_api { auto &memory = memory_provider_->getCurrentMemory()->get(); auto [name_ptr, name_size] = runtime::PtrSize(name_pos); - auto name_buffer = memory.loadN(name_ptr, name_size); - auto name = name_buffer.toStringView(); + auto name = qtils::byte2str(memory.loadN(name_ptr, name_size)); auto [value_ptr, value_size] = runtime::PtrSize(value_pos); - auto value_buffer = memory.loadN(value_ptr, value_size); - auto value = value_buffer.toStringView(); + auto value = qtils::byte2str(memory.loadN(value_ptr, value_size)); auto result = worker->httpRequestAddHeader(request_id, name, value); diff --git a/core/injector/get_peer_keypair.hpp b/core/injector/get_peer_keypair.hpp index a59816bd52..2af577120f 100644 --- a/core/injector/get_peer_keypair.hpp +++ b/core/injector/get_peer_keypair.hpp @@ -7,9 +7,9 @@ #pragma once #include +#include #include "application/app_configuration.hpp" -#include "common/bytestr.hpp" #include "common/outcome_throw.hpp" #include "crypto/crypto_store/crypto_store_impl.hpp" #include "crypto/ed25519_provider.hpp" @@ -73,7 +73,7 @@ namespace kagome::injector { auto save = app_config.shouldSaveNodeKey(); if (save) { std::ofstream file{path.c_str()}; - file.write(byte2str(seed).data(), seed.size()); + file.write(qtils::byte2str(seed).data(), seed.size()); } auto key_pair = std::make_shared( diff --git a/core/network/adapters/light.hpp b/core/network/adapters/light.hpp index fd240d1d2d..9c265cfdee 100644 --- a/core/network/adapters/light.hpp +++ b/core/network/adapters/light.hpp @@ -6,7 +6,8 @@ #pragma once -#include "common/bytestr.hpp" +#include + #include "network/adapters/protobuf.hpp" #include "network/protobuf/light.v1.pb.h" #include "primitives/common.hpp" @@ -42,6 +43,7 @@ namespace kagome::network { std::vector &out, std::vector::iterator loaded) { ::protobuf_generated::api::v1::light::Request msg; + using qtils::byte2str; if (auto call = boost::get(&t.op)) { auto &pb = *msg.mutable_remote_call_request(); pb.set_block(std::string{byte2str(t.block)}); @@ -73,6 +75,7 @@ namespace kagome::network { std::vector::const_iterator from) { const auto remains = src.size() - std::distance(src.begin(), from); BOOST_ASSERT(remains >= size(out)); + using qtils::str2byte; ::protobuf_generated::api::v1::light::Request msg; if (not msg.ParseFromArray(from.base(), remains)) { @@ -130,7 +133,7 @@ namespace kagome::network { auto &proof = t.call ? *msg.mutable_remote_call_response()->mutable_proof() : *msg.mutable_remote_read_response()->mutable_proof(); - proof = byte2str(scale::encode(t.proof).value()); + proof = qtils::byte2str(scale::encode(t.proof).value()); return appendToVec(msg, out, loaded); } @@ -148,9 +151,9 @@ namespace kagome::network { out.call = msg.has_remote_call_response(); OUTCOME_TRY(proof, - scale::decode>( - str2byte(out.call ? msg.remote_call_response().proof() - : msg.remote_read_response().proof()))); + scale::decode>(qtils::str2byte( + out.call ? msg.remote_call_response().proof() + : msg.remote_read_response().proof()))); out.proof = std::move(proof); std::advance(from, msg.ByteSizeLong()); diff --git a/core/network/adapters/protobuf_block_response.hpp b/core/network/adapters/protobuf_block_response.hpp index 95229e76b4..6f4ad5ebda 100644 --- a/core/network/adapters/protobuf_block_response.hpp +++ b/core/network/adapters/protobuf_block_response.hpp @@ -8,7 +8,8 @@ #include "network/adapters/protobuf.hpp" -#include "common/bytestr.hpp" +#include + #include "network/protobuf/api.v1.pb.h" #include "network/types/blocks_response.hpp" #include "scale/scale.hpp" @@ -118,9 +119,9 @@ namespace kagome::network { if (not src_block_data.justifications().empty()) { using Vec = std::vector< std::pair>; - OUTCOME_TRY( - vec, - scale::decode(str2byte(src_block_data.justifications()))); + OUTCOME_TRY(vec, + scale::decode( + qtils::str2byte(src_block_data.justifications()))); for (auto &[engine, raw] : vec) { if (engine == primitives::kGrandpaEngineId) { justification = primitives::Justification{std::move(raw)}; @@ -156,7 +157,7 @@ namespace kagome::network { template static outcome::result extract_value(F &&f) { if (const auto &buffer = std::forward(f)(); !buffer.empty()) { - OUTCOME_TRY(decoded, scale::decode(str2byte(buffer))); + OUTCOME_TRY(decoded, scale::decode(qtils::str2byte(buffer))); return decoded; } return Q_ERROR(AdaptersError::EMPTY_DATA); diff --git a/core/storage/map_prefix/prefix.cpp b/core/storage/map_prefix/prefix.cpp index 2482edf97e..35f56af0cc 100644 --- a/core/storage/map_prefix/prefix.cpp +++ b/core/storage/map_prefix/prefix.cpp @@ -7,7 +7,7 @@ #include "storage/map_prefix/prefix.hpp" #include -#include +#include namespace kagome::storage { inline std::optional afterPrefix(Buffer key) { @@ -107,7 +107,7 @@ namespace kagome::storage { MapPrefix::MapPrefix(std::string_view prefix, std::shared_ptr map) - : MapPrefix{libp2p::bytestr(prefix), std::move(map)} {} + : MapPrefix{qtils::str2byte(prefix), std::move(map)} {} Buffer MapPrefix::_key(BufferView key) const { return Buffer{prefix}.put(key); diff --git a/core/storage/trie/polkadot_trie/trie_node.hpp b/core/storage/trie/polkadot_trie/trie_node.hpp index 39d1a863f2..2593562ce3 100644 --- a/core/storage/trie/polkadot_trie/trie_node.hpp +++ b/core/storage/trie/polkadot_trie/trie_node.hpp @@ -21,7 +21,6 @@ namespace kagome::storage::trie { using Buffer = common::Buffer; using Buffer::Buffer; - using Buffer::operator<=>; KeyNibbles(common::Buffer b) : Buffer{std::move(b)} {} diff --git a/core/storage/trie/serialization/buffer_stream.hpp b/core/storage/trie/serialization/buffer_stream.hpp index 5d1d8a09dc..266bc88277 100644 --- a/core/storage/trie/serialization/buffer_stream.hpp +++ b/core/storage/trie/serialization/buffer_stream.hpp @@ -29,7 +29,7 @@ namespace kagome::storage::trie { throw std::out_of_range("Data is out"); } auto byte = data_[0]; - data_.dropFirst(1); + data_ = data_.subspan(1); return byte; } diff --git a/core/utils/storage_explorer.cpp b/core/utils/storage_explorer.cpp index 9dd65f53bf..aa569d3603 100644 --- a/core/utils/storage_explorer.cpp +++ b/core/utils/storage_explorer.cpp @@ -5,6 +5,7 @@ */ #include +#include #include "application/impl/app_configuration_impl.hpp" #include "blockchain/block_storage.hpp" @@ -141,7 +142,7 @@ std::optional parseBlockId(const char *string) { kagome::primitives::BlockId id; if (strlen(string) == 2 * kagome::primitives::BlockHash::size()) { kagome::primitives::BlockHash id_hash{}; - if (auto id_bytes = kagome::common::unhex(string); id_bytes) { + if (auto id_bytes = qtils::unhex(string)) { std::copy_n(id_bytes.value().begin(), kagome::primitives::BlockHash::size(), id_hash.begin()); @@ -271,7 +272,7 @@ class QueryStateCommand : public Command { assertArgumentCount(args, 3, 3); kagome::storage::trie::RootHash state_root{}; - if (auto id_bytes = kagome::common::unhex(args[1]); id_bytes) { + if (auto id_bytes = qtils::unhex(args[1]); id_bytes) { std::copy_n(id_bytes.value().begin(), kagome::primitives::BlockHash::size(), state_root.begin()); @@ -283,7 +284,7 @@ class QueryStateCommand : public Command { throwError("Failed getting trie batch: {}", batch.error()); } kagome::common::Buffer key{}; - if (auto key_bytes = kagome::common::unhex(args[2]); key_bytes) { + if (auto key_bytes = qtils::unhex(args[2]); key_bytes) { key = kagome::common::Buffer{std::move(key_bytes.value())}; } else { throwError("Invalid key!"); diff --git a/test/core/api/service/state/state_api_test.cpp b/test/core/api/service/state/state_api_test.cpp index 6e91596b94..62fbb6e54a 100644 --- a/test/core/api/service/state/state_api_test.cpp +++ b/test/core/api/service/state/state_api_test.cpp @@ -303,9 +303,7 @@ namespace kagome::api { jsonrpc::Request::Parameters params; params.push_back(jsonrpc::Value::Array{std::string("test_data")}); - EXPECT_OUTCOME_ERROR(result, - subscribe_storage->init(params), - common::UnhexError::MISSING_0X_PREFIX); + EXPECT_OUTCOME_FALSE_1(subscribe_storage->init(params)); } /** @@ -321,9 +319,7 @@ namespace kagome::api { jsonrpc::Request::Parameters params; params.push_back(jsonrpc::Value::Array{std::string("aa1122334455")}); - EXPECT_OUTCOME_ERROR(result, - subscribe_storage->init(params), - common::UnhexError::MISSING_0X_PREFIX); + EXPECT_OUTCOME_FALSE_1(subscribe_storage->init(params)); } /** @@ -339,9 +335,7 @@ namespace kagome::api { jsonrpc::Request::Parameters params; params.push_back(jsonrpc::Value::Array{std::string("0xtest_data")}); - EXPECT_OUTCOME_ERROR(result, - subscribe_storage->init(params), - common::UnhexError::NON_HEX_INPUT); + EXPECT_OUTCOME_FALSE_1(subscribe_storage->init(params)); } /** diff --git a/test/core/common/buffer_test.cpp b/test/core/common/buffer_test.cpp index 5c7f0dcefb..5cc2d1f6b1 100644 --- a/test/core/common/buffer_test.cpp +++ b/test/core/common/buffer_test.cpp @@ -7,10 +7,12 @@ #include "common/buffer.hpp" #include +#include #include using namespace kagome::common; using namespace std::string_literals; +using qtils::operator""_unhex; /** * @given empty buffer diff --git a/test/core/common/hexutil_test.cpp b/test/core/common/hexutil_test.cpp index 8e0305bbfa..208fe6cf67 100644 --- a/test/core/common/hexutil_test.cpp +++ b/test/core/common/hexutil_test.cpp @@ -13,54 +13,6 @@ using namespace kagome::common; using namespace std::string_literals; -/** - * @given Array of bytes - * @when hex it - * @then hex matches expected encoding - */ -TEST(Common, Hexutil_Hex) { - auto bin = "00010204081020FF"_unhex; - auto hexed = hex_upper(bin); - ASSERT_EQ(hexed, "00010204081020FF"s); -} - -/** - * @given Hexencoded string of even length - * @when unhex - * @then no exception, result matches expected value - */ -TEST(Common, Hexutil_UnhexEven) { - auto s = "00010204081020ff"s; - - std::vector actual; - ASSERT_NO_THROW(actual = unhex(s).value()) - << "unhex result does not contain expected std::vector"; - - auto expected = "00010204081020ff"_unhex; - - ASSERT_EQ(actual, expected); -} - -/** - * @given Hexencoded string of odd length - * @when unhex - * @then unhex result contains error - */ -TEST(Common, Hexutil_UnhexOdd) { - ASSERT_NO_THROW({ unhex("0").error(); }) - << "unhex did not return an error as expected"; -} - -/** - * @given Hexencoded string with non-hex letter - * @when unhex - * @then unhex result contains error - */ -TEST(Common, Hexutil_UnhexInvalid) { - ASSERT_NO_THROW({ unhex("keks").error(); }) - << "unhex did not return an error as expected"; -} - struct UnhexNumber32Test : public ::testing::TestWithParam> {}; @@ -90,7 +42,5 @@ TEST(UnhexNumberTest, Overflow) { TEST(UnhexNumberTest, WrongFormat) { std::string encoded = "64"; - EXPECT_OUTCOME_ERROR(res, - unhexNumber(encoded), - kagome::common::UnhexError::MISSING_0X_PREFIX); + EXPECT_OUTCOME_FALSE_1(unhexNumber(encoded)); } diff --git a/test/core/crypto/blake2/blake2_test.cpp b/test/core/crypto/blake2/blake2_test.cpp index 9ec6de015d..1f1a1d6ca9 100644 --- a/test/core/crypto/blake2/blake2_test.cpp +++ b/test/core/crypto/blake2/blake2_test.cpp @@ -5,12 +5,14 @@ */ #include -#include +#include #include "crypto/blake2/blake2b.h" #include "crypto/blake2/blake2s.h" #include "testutil/literals.hpp" +using qtils::operator""_unhex; + // Deterministic sequences (Fibonacci generator). static void selftest_seq(uint8_t *out, size_t len, size_t seed) { diff --git a/test/core/crypto/hasher/hasher_test.cpp b/test/core/crypto/hasher/hasher_test.cpp index c560abef2e..ccc8ed32c8 100644 --- a/test/core/crypto/hasher/hasher_test.cpp +++ b/test/core/crypto/hasher/hasher_test.cpp @@ -5,11 +5,13 @@ */ #include +#include #include "common/blob.hpp" #include "crypto/hasher/hasher_impl.hpp" #include "testutil/literals.hpp" +using qtils::operator""_unhex; using kagome::common::Buffer; /** diff --git a/test/core/crypto/twox/twox_test.cpp b/test/core/crypto/twox/twox_test.cpp index 3dd138bd48..79e6bc41de 100644 --- a/test/core/crypto/twox/twox_test.cpp +++ b/test/core/crypto/twox/twox_test.cpp @@ -8,8 +8,10 @@ #include #include +#include #include "testutil/literals.hpp" +using qtils::operator""_unhex; using kagome::common::Buffer; using namespace kagome::crypto; diff --git a/test/core/host_api/crypto_extension_test.cpp b/test/core/host_api/crypto_extension_test.cpp index cc88511a23..1de77a7ccf 100644 --- a/test/core/host_api/crypto_extension_test.cpp +++ b/test/core/host_api/crypto_extension_test.cpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include "crypto/crypto_store/crypto_store_impl.hpp" #include "crypto/ecdsa/ecdsa_provider_impl.hpp" @@ -28,6 +28,7 @@ #include "testutil/prepare_loggers.hpp" using namespace kagome::host_api; +using qtils::operator""_unhex; using kagome::common::Blob; using kagome::common::Buffer; using kagome::common::BufferView; diff --git a/test/core/host_api/io_extension_test.cpp b/test/core/host_api/io_extension_test.cpp index 877d697e26..a987c4e9af 100644 --- a/test/core/host_api/io_extension_test.cpp +++ b/test/core/host_api/io_extension_test.cpp @@ -9,6 +9,7 @@ #include #include +#include #include "mock/core/runtime/memory_mock.hpp" #include "mock/core/runtime/memory_provider_mock.hpp" @@ -19,6 +20,7 @@ using namespace kagome::host_api; using ::testing::Return; +using qtils::operator""_unhex; using kagome::common::Buffer; using kagome::runtime::Memory; using kagome::runtime::MemoryMock; diff --git a/test/testutil/literals.hpp b/test/testutil/literals.hpp index 7027eb4e00..067a4669d4 100644 --- a/test/testutil/literals.hpp +++ b/test/testutil/literals.hpp @@ -10,8 +10,6 @@ #include #include #include "common/blob.hpp" -#include "common/buffer.hpp" -#include "common/hexutil.hpp" using namespace kagome::common::literals; @@ -21,29 +19,6 @@ inline kagome::common::Hash256 operator"" _hash256(const char *c, size_t s) { return hash; } -inline std::vector operator"" _v(const char *c, size_t s) { - std::vector chars(c, c + s); - return chars; -} - -inline std::vector operator""_unhex(const char *c, size_t s) { - if (s > 2 and c[0] == '0' and c[1] == 'x') { - return kagome::common::unhexWith0x(std::string_view(c, s)).value(); - } - return kagome::common::unhex(std::string_view(c, s)).value(); -} - -inline libp2p::multi::Multiaddress operator""_multiaddr(const char *c, - size_t s) { - return libp2p::multi::Multiaddress::create(std::string_view(c, s)).value(); -} - -/// creates a multihash instance from a hex string -inline libp2p::multi::Multihash operator""_multihash(const char *c, size_t s) { - return libp2p::multi::Multihash::createFromHex(std::string_view(c, s)) - .value(); -} - inline libp2p::peer::PeerId operator""_peerid(const char *c, size_t s) { // libp2p::crypto::PublicKey p; auto data = std::vector(c, c + s); diff --git a/test/testutil/storage/polkadot_trie_printer.hpp b/test/testutil/storage/polkadot_trie_printer.hpp index ae3d36df37..6f3616e45c 100644 --- a/test/testutil/storage/polkadot_trie_printer.hpp +++ b/test/testutil/storage/polkadot_trie_printer.hpp @@ -91,7 +91,7 @@ namespace kagome::storage::trie { if (print_hash_) { stream_ << std::setfill('-') << std::setw(nest_level) << "" << std::setw(0) << "hash: " - << common::hex_upper(codec_.merkleValue(enc).asBuffer()) + << common::hex_lower(codec_.merkleValue(enc).asBuffer()) << "\n"; } }