From 2c3a1c91e94b6eca256f981d54b60df710dbec1a Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Wed, 25 Oct 2023 11:05:53 +0300 Subject: [PATCH 01/12] refactor: gst to std Signed-off-by: Dmitriy Khaustov aka xDimon --- cmake/Hunter/config.cmake | 15 +- core/api/jrpc/value_converter.hpp | 4 +- core/api/service/author/author_api.hpp | 8 +- .../service/author/impl/author_api_impl.cpp | 11 +- .../service/author/impl/author_api_impl.hpp | 8 +- core/api/service/author/requests/has_key.hpp | 2 +- .../author/requests/has_session_keys.hpp | 2 +- .../service/author/requests/insert_key.hpp | 4 +- .../requests/submit_and_watch_extrinsic.hpp | 3 +- .../author/requests/submit_extrinsic.hpp | 3 +- core/api/service/chain/chain_api.hpp | 2 +- .../api/service/chain/impl/chain_api_impl.cpp | 2 +- .../api/service/chain/impl/chain_api_impl.hpp | 2 +- .../service/chain/requests/get_block_hash.cpp | 2 +- .../child_state/impl/child_state_api_impl.cpp | 4 +- core/api/service/mmr/rpc.cpp | 18 +- .../service/payment/requests/query_info.hpp | 3 +- .../api/service/state/impl/state_api_impl.cpp | 19 +- .../api/service/state/impl/state_api_impl.hpp | 11 +- core/api/service/state/state_api.hpp | 11 +- .../impl/app_configuration_impl.cpp | 2 +- .../publisher/address_publisher.cpp | 2 +- core/benchmark/block_execution_benchmark.cpp | 2 +- core/blockchain/impl/digest_tracker_impl.cpp | 8 +- core/common/blob.hpp | 4 +- core/common/buffer.hpp | 8 +- core/common/buffer_back_insert_iterator.hpp | 2 +- core/common/buffer_or_view.hpp | 25 +- core/common/buffer_view.hpp | 54 +- core/common/bytestr.hpp | 11 +- core/common/hexutil.cpp | 13 +- core/common/hexutil.hpp | 13 +- core/common/int_serialization.cpp | 30 +- core/common/int_serialization.hpp | 14 +- core/common/size_limited_containers.hpp | 6 +- .../consensus/babe/impl/babe_digests_util.cpp | 6 +- .../grandpa/impl/authority_manager_impl.cpp | 21 +- core/consensus/grandpa/voter_set.cpp | 2 +- core/consensus/sassafras/impl/sassafras.cpp | 547 ++++++++++++++++++ core/crypto/bip39/bip39_provider.hpp | 2 +- core/crypto/bip39/bip39_types.hpp | 2 +- .../crypto/bip39/impl/bip39_provider_impl.cpp | 2 +- .../crypto/bip39/impl/bip39_provider_impl.hpp | 2 +- core/crypto/bip39/mnemonic.cpp | 2 +- .../crypto/crypto_store/crypto_store_impl.cpp | 8 +- core/crypto/crypto_store/crypto_suites.hpp | 18 +- core/crypto/crypto_store/key_file_storage.cpp | 10 +- core/crypto/crypto_store/key_file_storage.hpp | 10 +- core/crypto/ecdsa/ecdsa_provider_impl.cpp | 6 +- core/crypto/ecdsa/ecdsa_provider_impl.hpp | 4 +- core/crypto/ecdsa_provider.hpp | 6 +- core/crypto/ed25519/ed25519_provider_impl.cpp | 6 +- core/crypto/ed25519/ed25519_provider_impl.hpp | 4 +- core/crypto/ed25519_provider.hpp | 6 +- core/crypto/hasher.hpp | 42 +- core/crypto/hasher/hasher_impl.cpp | 44 +- core/crypto/hasher/hasher_impl.hpp | 20 +- .../pbkdf2/impl/pbkdf2_provider_impl.cpp | 4 +- .../pbkdf2/impl/pbkdf2_provider_impl.hpp | 4 +- core/crypto/pbkdf2/pbkdf2_provider.hpp | 6 +- core/crypto/sha/sha256.cpp | 4 +- core/crypto/sha/sha256.hpp | 4 +- core/crypto/sr25519/sr25519_provider_impl.cpp | 6 +- core/crypto/sr25519/sr25519_provider_impl.hpp | 6 +- core/crypto/sr25519_provider.hpp | 8 +- core/crypto/sr25519_types.hpp | 2 +- core/crypto/twox/twox.cpp | 6 +- core/crypto/twox/twox.hpp | 6 +- core/crypto/vrf/vrf_provider_impl.cpp | 2 +- .../impl/prioritized_selection.cpp | 2 +- .../host_api/impl/child_storage_extension.cpp | 1 + core/host_api/impl/crypto_extension.cpp | 4 +- core/injector/application_injector.cpp | 2 +- core/network/adapters/protobuf.hpp | 2 +- .../adapters/protobuf_block_request.hpp | 2 +- .../adapters/protobuf_block_response.hpp | 2 +- .../adapters/protobuf_state_request.hpp | 2 +- core/network/adapters/uvar.hpp | 2 +- core/network/helpers/message_read_writer.hpp | 2 +- .../helpers/protobuf_message_read_writer.hpp | 2 +- core/network/helpers/stream_proxy_base.hpp | 8 +- core/network/helpers/stream_read_buffer.hpp | 6 +- .../propagate_transactions_protocol.cpp | 2 +- .../propagate_transactions_protocol.hpp | 2 +- .../impl/state_protocol_observer_impl.cpp | 7 +- .../impl/transactions_transmitter_impl.cpp | 2 +- .../impl/transactions_transmitter_impl.hpp | 2 +- core/network/notifications/handshake.hpp | 2 +- core/network/transactions_transmitter.hpp | 2 +- core/network/types/own_peer_info.hpp | 2 +- core/parachain/pvf/pvf_impl.cpp | 2 +- .../impl/parachain_observer_impl.cpp | 4 +- .../validator/impl/parachain_processor.cpp | 2 +- core/primitives/authority.hpp | 16 - core/primitives/block_header.hpp | 2 +- core/primitives/event_types.hpp | 6 +- core/primitives/ss58_codec.cpp | 12 +- core/primitives/ss58_codec.hpp | 2 +- core/primitives/strobe.hpp | 8 +- core/runtime/binaryen/memory_impl.cpp | 12 +- core/runtime/binaryen/memory_impl.hpp | 4 +- .../binaryen/module/module_factory_impl.cpp | 2 +- .../binaryen/module/module_factory_impl.hpp | 2 +- .../binaryen/module/module_instance_impl.cpp | 2 +- .../binaryen/runtime_external_interface.hpp | 14 +- .../runtime/common/constant_code_provider.cpp | 2 +- .../runtime/common/constant_code_provider.hpp | 2 +- core/runtime/common/module_instance.cpp | 2 +- core/runtime/common/storage_code_provider.cpp | 2 +- core/runtime/common/storage_code_provider.hpp | 2 +- core/runtime/memory.hpp | 7 +- core/runtime/module_factory.hpp | 4 +- core/runtime/module_instance.hpp | 2 +- core/runtime/module_repository.hpp | 2 +- core/runtime/runtime_code_provider.hpp | 5 +- core/runtime/wavm/core_api_factory_impl.cpp | 22 +- core/runtime/wavm/memory_impl.cpp | 4 +- core/runtime/wavm/memory_impl.hpp | 12 +- core/runtime/wavm/module.cpp | 2 +- core/runtime/wavm/module.hpp | 2 +- core/runtime/wavm/module_cache.cpp | 2 +- core/runtime/wavm/module_factory_impl.cpp | 2 +- core/runtime/wavm/module_factory_impl.hpp | 2 +- core/storage/map_prefix/prefix.cpp | 2 +- core/storage/rocksdb/rocksdb_util.hpp | 4 +- .../trie/impl/topper_trie_batch_impl.cpp | 4 +- .../polkadot_trie_cursor_impl.cpp | 2 +- .../polkadot_trie_cursor_impl.hpp | 2 +- .../trie/polkadot_trie/polkadot_trie_impl.cpp | 10 +- core/storage/trie/polkadot_trie/trie_node.hpp | 2 +- .../trie/serialization/buffer_stream.hpp | 15 +- .../impl/transaction_pool_impl.cpp | 3 +- core/utils/block_info_key.hpp | 6 +- core/utils/block_number_key.hpp | 8 +- core/utils/kagome_db_editor.cpp | 3 +- core/utils/storage_explorer.cpp | 8 +- .../api/service/author/author_api_test.cpp | 27 +- .../child_state/child_state_api_test.cpp | 15 +- .../api/service/payment/payment_api_test.cpp | 2 +- .../state/state_jrpc_processor_test.cpp | 71 ++- .../api/service/system/system_api_test.cpp | 4 +- test/core/common/buffer_view_test.cpp | 2 +- test/core/consensus/babe/babe_test.cpp | 6 +- .../grandpa/authority_manager_test.cpp | 6 +- .../core/crypto/ecdsa/ecdsa_provider_test.cpp | 2 +- .../crypto/ed25519/ed25519_provider_test.cpp | 4 +- test/core/crypto/hasher/hasher_test.cpp | 2 +- .../crypto/sr25519/sr25519_provider_test.cpp | 4 +- test/core/host_api/CMakeLists.txt | 1 + .../host_api/child_storage_extension_test.cpp | 21 +- test/core/host_api/crypto_extension_test.cpp | 87 ++- test/core/host_api/misc_extension_test.cpp | 5 +- .../core/host_api/offchain_extension_test.cpp | 31 +- test/core/host_api/storage_extension_test.cpp | 23 +- .../network/types/block_announce_test.cpp | 4 +- test/core/parachain/pvf_test.cpp | 2 +- test/core/runtime/binaryen/CMakeLists.txt | 1 + .../runtime/storage_code_provider_test.cpp | 6 +- .../api/service/author/author_api_mock.hpp | 8 +- .../core/api/service/chain/chain_api_mock.hpp | 2 +- .../core/api/service/state/state_api_mock.hpp | 13 +- test/mock/core/crypto/ecdsa_provider_mock.hpp | 4 +- .../core/crypto/ed25519_provider_mock.hpp | 4 +- test/mock/core/crypto/hasher_mock.hpp | 47 +- .../core/crypto/sr25519_provider_mock.hpp | 6 +- .../network/transactions_transmitter_mock.hpp | 2 +- test/mock/core/runtime/memory_mock.hpp | 4 +- .../mock/core/runtime/module_factory_mock.hpp | 2 +- test/mock/libp2p/basic/read_writer_mock.hpp | 8 +- .../runtime/common/basic_code_provider.cpp | 3 +- .../runtime/common/basic_code_provider.hpp | 2 +- 171 files changed, 1205 insertions(+), 677 deletions(-) create mode 100644 core/consensus/sassafras/impl/sassafras.cpp diff --git a/cmake/Hunter/config.cmake b/cmake/Hunter/config.cmake index 094cc28060..e9dd52012e 100644 --- a/cmake/Hunter/config.cmake +++ b/cmake/Hunter/config.cmake @@ -38,10 +38,15 @@ hunter_config( KEEP_PACKAGE_SOURCES ) +#hunter_config( +# libp2p +# VERSION 0.1.16 +# KEEP_PACKAGE_SOURCES +#) hunter_config( libp2p - VERSION 0.1.16 - KEEP_PACKAGE_SOURCES + URL https://github.com/libp2p/cpp-libp2p/archive/a688ddfcf2a2a3a069e7cc7a74e9f07b900bc095.tar.gz + SHA1 8e0aeb3d54c4be3b1fb834c4be387645bbd4aecb ) hunter_config( @@ -64,6 +69,12 @@ hunter_config( KEEP_PACKAGE_SOURCES ) +hunter_config( + scale + URL https://github.com/qdrvm/scale-codec-cpp/archive/fc06c2f1c8f56ced279134703ced187da645f737.tar.gz + SHA1 9c0362aa6a5f1dcc9ff5e56c4220f4aef15e2eb9 +) + # Fix for Apple clang (or clang from brew) of versions 15 and higher if(APPLE AND (CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") AND CMAKE_CXX_COMPILER_VERSION GREATER_EQUAL "15.0.0") hunter_config( diff --git a/core/api/jrpc/value_converter.hpp b/core/api/jrpc/value_converter.hpp index 5f009aeb40..3d6fe1eca8 100644 --- a/core/api/jrpc/value_converter.hpp +++ b/core/api/jrpc/value_converter.hpp @@ -293,8 +293,8 @@ namespace kagome::api { jArray peers; peers.resize(params.peers.size()); std::transform( - params.peers.cbegin(), - params.peers.cend(), + params.peers.begin(), + params.peers.end(), peers.begin(), [](const auto &peer_id) { return makeValue(peer_id.toHex()); }); return jStruct{std::pair{"broadcast", std::move(peers)}}; diff --git a/core/api/service/author/author_api.hpp b/core/api/service/author/author_api.hpp index 3b1abf2e06..6fdfd8e4c9 100644 --- a/core/api/service/author/author_api.hpp +++ b/core/api/service/author/author_api.hpp @@ -52,8 +52,8 @@ namespace kagome::api { */ virtual outcome::result insertKey( crypto::KeyType key_type, - const gsl::span &seed, - const gsl::span &public_key) = 0; + const std::span &seed, + const std::span &public_key) = 0; /** * @brief Generate new session keys and @@ -70,7 +70,7 @@ namespace kagome::api { * otherwise */ virtual outcome::result hasSessionKeys( - const gsl::span &keys) = 0; + const std::span &keys) = 0; /** * @brief checks if the keystore has private keys for the given public @@ -79,7 +79,7 @@ namespace kagome::api { * @param key_type The key type */ virtual outcome::result hasKey( - const gsl::span &public_key, + const std::span &public_key, crypto::KeyType key_type) = 0; /** diff --git a/core/api/service/author/impl/author_api_impl.cpp b/core/api/service/author/impl/author_api_impl.cpp index 4478140d1e..fa7b2a9188 100644 --- a/core/api/service/author/impl/author_api_impl.cpp +++ b/core/api/service/author/impl/author_api_impl.cpp @@ -63,8 +63,8 @@ namespace kagome::api { outcome::result AuthorApiImpl::insertKey( crypto::KeyType key_type_id, - const gsl::span &seed, - const gsl::span &public_key) { + const std::span &seed, + const std::span &public_key) { if (std::find(kKeyTypes.begin(), kKeyTypes.end(), key_type_id) == kKeyTypes.end()) { std::string types; @@ -113,7 +113,7 @@ namespace kagome::api { // it could be extended by reading config from chainspec palletSession/keys // value outcome::result AuthorApiImpl::hasSessionKeys( - const gsl::span &keys) { + const std::span &keys) { scale::ScaleDecoderStream stream(keys); std::array key; if (keys.size() < 32 || keys.size() > 32 * 6 || (keys.size() % 32) != 0) { @@ -128,7 +128,8 @@ namespace kagome::api { crypto::KeyTypes::GRANDPA, crypto::Ed25519PublicKey(common::Blob<32>(key)))) { unsigned count = 1; - while (stream.currentIndex() < keys.size()) { + while (stream.currentIndex() + < static_cast(keys.size())) { stream >> key; if (not store_->findSr25519Keypair( crypto::polkadot_key_order[count++], @@ -142,7 +143,7 @@ namespace kagome::api { } outcome::result AuthorApiImpl::hasKey( - const gsl::span &public_key, crypto::KeyType key_type) { + const std::span &public_key, crypto::KeyType key_type) { auto res = key_store_->searchForPhrase(key_type, public_key); if (not res) { return res.error(); diff --git a/core/api/service/author/impl/author_api_impl.hpp b/core/api/service/author/impl/author_api_impl.hpp index 4b711bb6e4..9607f0675c 100644 --- a/core/api/service/author/impl/author_api_impl.hpp +++ b/core/api/service/author/impl/author_api_impl.hpp @@ -84,15 +84,15 @@ namespace kagome::api { outcome::result insertKey( crypto::KeyType key_type, - const gsl::span &seed, - const gsl::span &public_key) override; + const std::span &seed, + const std::span &public_key) override; outcome::result rotateKeys() override; outcome::result hasSessionKeys( - const gsl::span &keys) override; + const std::span &keys) override; - outcome::result hasKey(const gsl::span &public_key, + outcome::result hasKey(const std::span &public_key, crypto::KeyType key_type) override; outcome::result> pendingExtrinsics() diff --git a/core/api/service/author/requests/has_key.hpp b/core/api/service/author/requests/has_key.hpp index bfb2801970..57b47d30bc 100644 --- a/core/api/service/author/requests/has_key.hpp +++ b/core/api/service/author/requests/has_key.hpp @@ -23,7 +23,7 @@ namespace kagome::api::author::request { outcome::result execute() override { OUTCOME_TRY(public_key, common::unhexWith0x(getParam<0>())); - return api_->hasKey(gsl::span(public_key.data(), public_key.size()), + return api_->hasKey(std::span(public_key.data(), public_key.size()), crypto::decodeKeyTypeFromStr(getParam<1>())); } diff --git a/core/api/service/author/requests/has_session_keys.hpp b/core/api/service/author/requests/has_session_keys.hpp index b3da2fafd3..6af9318d1f 100644 --- a/core/api/service/author/requests/has_session_keys.hpp +++ b/core/api/service/author/requests/has_session_keys.hpp @@ -23,7 +23,7 @@ namespace kagome::api::author::request { outcome::result execute() override { OUTCOME_TRY(keys, common::unhexWith0x(getParam<0>())); - return api_->hasSessionKeys(gsl::span(keys.data(), keys.size())); + return api_->hasSessionKeys(std::span(keys.data(), keys.size())); } private: diff --git a/core/api/service/author/requests/insert_key.hpp b/core/api/service/author/requests/insert_key.hpp index ef590e069d..0298d196fb 100644 --- a/core/api/service/author/requests/insert_key.hpp +++ b/core/api/service/author/requests/insert_key.hpp @@ -26,8 +26,8 @@ namespace kagome::api::author::request { OUTCOME_TRY(seed, common::unhexWith0x(getParam<1>())); OUTCOME_TRY(public_key, common::unhexWith0x(getParam<2>())); return api_->insertKey(crypto::decodeKeyTypeFromStr(getParam<0>()), - gsl::span(seed.data(), seed.size()), - gsl::span(public_key.data(), public_key.size())); + std::span(seed.data(), seed.size()), + std::span(public_key.data(), public_key.size())); } private: diff --git a/core/api/service/author/requests/submit_and_watch_extrinsic.hpp b/core/api/service/author/requests/submit_and_watch_extrinsic.hpp index 24df06372b..257c7d182b 100644 --- a/core/api/service/author/requests/submit_and_watch_extrinsic.hpp +++ b/core/api/service/author/requests/submit_and_watch_extrinsic.hpp @@ -24,7 +24,8 @@ namespace kagome::api::author::request { outcome::result execute() override { auto ext_hex = getParam<0>(); OUTCOME_TRY(buffer, common::unhexWith0x(ext_hex)); - OUTCOME_TRY(extrinsic, scale::decode(buffer)); + OUTCOME_TRY(extrinsic, + scale::decode(std::span(buffer))); return api_->submitAndWatchExtrinsic(extrinsic); } diff --git a/core/api/service/author/requests/submit_extrinsic.hpp b/core/api/service/author/requests/submit_extrinsic.hpp index d2f9429d98..baeb1ba3fc 100644 --- a/core/api/service/author/requests/submit_extrinsic.hpp +++ b/core/api/service/author/requests/submit_extrinsic.hpp @@ -24,7 +24,8 @@ namespace kagome::api::author::request { outcome::result execute() override { auto ext_hex = getParam<0>(); OUTCOME_TRY(buffer, common::unhexWith0x(ext_hex)); - OUTCOME_TRY(extrinsic, scale::decode(buffer)); + OUTCOME_TRY(extrinsic, + scale::decode(std::span(buffer))); return api_->submitExtrinsic(primitives::TransactionSource::External, extrinsic); } diff --git a/core/api/service/chain/chain_api.hpp b/core/api/service/chain/chain_api.hpp index e1caeae130..6a639915f5 100644 --- a/core/api/service/chain/chain_api.hpp +++ b/core/api/service/chain/chain_api.hpp @@ -52,7 +52,7 @@ namespace kagome::api { * @return array of block hashes for numbers */ virtual outcome::result> getBlockHash( - gsl::span values) const = 0; + std::span values) const = 0; /** * @param hash hex-string of a block to retrieve diff --git a/core/api/service/chain/impl/chain_api_impl.cpp b/core/api/service/chain/impl/chain_api_impl.cpp index 0f4c046db6..8c3aa99531 100644 --- a/core/api/service/chain/impl/chain_api_impl.cpp +++ b/core/api/service/chain/impl/chain_api_impl.cpp @@ -62,7 +62,7 @@ namespace kagome::api { } outcome::result> ChainApiImpl::getBlockHash( - gsl::span values) const { + std::span values) const { std::vector results; results.reserve(values.size()); diff --git a/core/api/service/chain/impl/chain_api_impl.hpp b/core/api/service/chain/impl/chain_api_impl.hpp index 8741b8a06a..e6128e7c7c 100644 --- a/core/api/service/chain/impl/chain_api_impl.hpp +++ b/core/api/service/chain/impl/chain_api_impl.hpp @@ -39,7 +39,7 @@ namespace kagome::api { std::string_view value) const override; outcome::result> getBlockHash( - gsl::span values) const override; + std::span values) const override; outcome::result getHeader( std::string_view hash) override { diff --git a/core/api/service/chain/requests/get_block_hash.cpp b/core/api/service/chain/requests/get_block_hash.cpp index 8453f9251b..f88e93d60e 100644 --- a/core/api/service/chain/requests/get_block_hash.cpp +++ b/core/api/service/chain/requests/get_block_hash.cpp @@ -80,7 +80,7 @@ namespace kagome::api::chain::request { }, [this]( const std::vector &v) -> outcome::result { - OUTCOME_TRY(rr, api_->getBlockHash(gsl::make_span(v))); + OUTCOME_TRY(rr, api_->getBlockHash(std::span(v))); std::vector results{}; results.reserve(v.size()); for (const auto &it : rr) { diff --git a/core/api/service/child_state/impl/child_state_api_impl.cpp b/core/api/service/child_state/impl/child_state_api_impl.cpp index 2c99407015..845df37953 100644 --- a/core/api/service/child_state/impl/child_state_api_impl.cpp +++ b/core/api/service/child_state/impl/child_state_api_impl.cpp @@ -59,7 +59,7 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!boost::starts_with(key.value(), prefix)) { + if (!key->startsWith(prefix)) { break; } result.push_back(cursor->key().value()); @@ -106,7 +106,7 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!boost::starts_with(key.value(), prefix)) { + if (!key->startsWith(prefix)) { break; } result.push_back(cursor->key().value()); diff --git a/core/api/service/mmr/rpc.cpp b/core/api/service/mmr/rpc.cpp index ef7f56b800..84db25d223 100644 --- a/core/api/service/mmr/rpc.cpp +++ b/core/api/service/mmr/rpc.cpp @@ -119,11 +119,12 @@ namespace kagome::api { [](std::shared_ptr self, primitives::MmrLeavesProof proof_raw) -> outcome::result { auto &at = proof_raw.block_hash; + OUTCOME_TRY(leaves, + scale::decode( + proof_raw.leaves.view())); OUTCOME_TRY( - leaves, - scale::decode(proof_raw.leaves)); - OUTCOME_TRY(proof, - scale::decode(proof_raw.proof)); + proof, + scale::decode(proof_raw.proof.view())); auto offchain = self->withOffchain(at); OUTCOME_TRY(r, self->mmr_api_.get()->verifyProof(at, leaves, proof)); @@ -139,11 +140,12 @@ namespace kagome::api { primitives::BlockHash mmr_root, primitives::MmrLeavesProof proof_raw) -> outcome::result { auto &at = proof_raw.block_hash; + OUTCOME_TRY(leaves, + scale::decode( + proof_raw.leaves.view())); OUTCOME_TRY( - leaves, - scale::decode(proof_raw.leaves)); - OUTCOME_TRY(proof, - scale::decode(proof_raw.proof)); + proof, + scale::decode(proof_raw.proof.view())); OUTCOME_TRY(r, self->mmr_api_.get()->verifyProofStateless( at, mmr_root, leaves, proof)); diff --git a/core/api/service/payment/requests/query_info.hpp b/core/api/service/payment/requests/query_info.hpp index b1489c1a41..d796879b1f 100644 --- a/core/api/service/payment/requests/query_info.hpp +++ b/core/api/service/payment/requests/query_info.hpp @@ -30,7 +30,8 @@ namespace kagome::api::payment::request { auto ext_hex = getParam<0>(); OUTCOME_TRY(ext_bytes, common::unhexWith0x(ext_hex)); - OUTCOME_TRY(extrinsic, scale::decode(ext_bytes)); + OUTCOME_TRY(extrinsic, + scale::decode(std::span(ext_bytes))); auto at_hex = getParam<1>(); if (at_hex.empty()) { diff --git a/core/api/service/state/impl/state_api_impl.cpp b/core/api/service/state/impl/state_api_impl.cpp index b45134d416..ed3cee9171 100644 --- a/core/api/service/state/impl/state_api_impl.cpp +++ b/core/api/service/state/impl/state_api_impl.cpp @@ -102,7 +102,11 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!boost::starts_with(key.value(), prefix)) { + if (!std::equal( + key.value().begin(), + key.value().begin() + std::min(key.value().size(), prefix.size()), + prefix.begin(), + prefix.end())) { break; } result.push_back(cursor->key().value()); @@ -113,13 +117,13 @@ namespace kagome::api { } outcome::result> StateApiImpl::getStorage( - const common::BufferView &key) const { + common::BufferView key) const { auto last_finalized = block_tree_->getLastFinalized(); return getStorageAt(key, last_finalized.hash); } outcome::result> StateApiImpl::getStorageAt( - const common::BufferView &key, const primitives::BlockHash &at) const { + common::BufferView key, const primitives::BlockHash &at) const { OUTCOME_TRY(header, header_repo_->getBlockHeader(at)); OUTCOME_TRY(trie_reader, storage_->getEphemeralBatchAt(header.state_root)); auto res = trie_reader->tryGet(key); @@ -130,7 +134,7 @@ namespace kagome::api { outcome::result> StateApiImpl::queryStorage( - gsl::span keys, + std::span keys, const primitives::BlockHash &from, std::optional opt_to) const { // TODO(Harrm): Optimize once changes trie is enabled (and a warning/assert @@ -153,8 +157,7 @@ namespace kagome::api { } std::vector changes; - std::map, std::optional> - last_values; + std::map> last_values; // TODO(Harrm): optimize it to use a lazy generator instead of returning the // whole vector with block ids @@ -183,7 +186,7 @@ namespace kagome::api { outcome::result> StateApiImpl::queryStorageAt( - gsl::span keys, + std::span keys, std::optional opt_at) const { auto at = opt_at.has_value() ? opt_at.value() : block_tree_->bestBlock().hash; @@ -191,7 +194,7 @@ namespace kagome::api { } outcome::result StateApiImpl::getReadProof( - gsl::span keys, + std::span keys, std::optional opt_at) const { auto at = opt_at.has_value() ? opt_at.value() : block_tree_->bestBlock().hash; diff --git a/core/api/service/state/impl/state_api_impl.hpp b/core/api/service/state/impl/state_api_impl.hpp index f7a73bcac9..198e3ca9e3 100644 --- a/core/api/service/state/impl/state_api_impl.hpp +++ b/core/api/service/state/impl/state_api_impl.hpp @@ -53,23 +53,22 @@ namespace kagome::api { const override; outcome::result> getStorage( - const common::BufferView &key) const override; + common::BufferView key) const override; outcome::result> getStorageAt( - const common::BufferView &key, - const primitives::BlockHash &at) const override; + common::BufferView key, const primitives::BlockHash &at) const override; outcome::result> queryStorage( - gsl::span keys, + std::span keys, const primitives::BlockHash &from, std::optional to) const override; outcome::result> queryStorageAt( - gsl::span keys, + std::span keys, std::optional at) const override; outcome::result getReadProof( - gsl::span keys, + std::span keys, std::optional at) const override; outcome::result subscribeStorage( diff --git a/core/api/service/state/state_api.hpp b/core/api/service/state/state_api.hpp index 224764e6e5..ac00032699 100644 --- a/core/api/service/state/state_api.hpp +++ b/core/api/service/state/state_api.hpp @@ -34,10 +34,9 @@ namespace kagome::api { const std::optional &block_hash_opt) const = 0; virtual outcome::result> getStorage( - const common::BufferView &key) const = 0; + common::BufferView key) const = 0; virtual outcome::result> getStorageAt( - const common::BufferView &key, - const primitives::BlockHash &at) const = 0; + common::BufferView key, const primitives::BlockHash &at) const = 0; struct StorageChangeSet { primitives::BlockHash block; @@ -54,16 +53,16 @@ namespace kagome::api { }; virtual outcome::result> queryStorage( - gsl::span keys, + std::span keys, const primitives::BlockHash &from, std::optional to) const = 0; virtual outcome::result> queryStorageAt( - gsl::span keys, + std::span keys, std::optional at) const = 0; virtual outcome::result getReadProof( - gsl::span keys, + std::span keys, std::optional at) const = 0; virtual outcome::result subscribeStorage( diff --git a/core/application/impl/app_configuration_impl.cpp b/core/application/impl/app_configuration_impl.cpp index 362116cf5a..c07d1c7554 100644 --- a/core/application/impl/app_configuration_impl.cpp +++ b/core/application/impl/app_configuration_impl.cpp @@ -1165,7 +1165,7 @@ namespace kagome::application { auto replace = [&](std::string_view prefix, std::string_view replacement, std::string_view str) { - if (boost::starts_with(str, prefix)) { + if (str.substr(0, prefix.size()) == prefix) { std::string replaced{replacement}; replaced += str.substr(prefix.size()); public_addresses_.emplace_back( diff --git a/core/authority_discovery/publisher/address_publisher.cpp b/core/authority_discovery/publisher/address_publisher.cpp index d18624cbdb..65ccb7a55b 100644 --- a/core/authority_discovery/publisher/address_publisher.cpp +++ b/core/authority_discovery/publisher/address_publisher.cpp @@ -10,7 +10,7 @@ #include "crypto/sha/sha256.hpp" -#define _PB_SPAN(f) [&](gsl::span a) { (f)(a.data(), a.size()); } +#define _PB_SPAN(f) [&](std::span a) { (f)(a.data(), a.size()); } #define PB_SPAN_SET(a, b, c) _PB_SPAN((a).set_##b)(c) #define PB_SPAN_ADD(a, b, c) _PB_SPAN((a).add_##b)(c) diff --git a/core/benchmark/block_execution_benchmark.cpp b/core/benchmark/block_execution_benchmark.cpp index b1003f6a1b..89b8db4aa1 100644 --- a/core/benchmark/block_execution_benchmark.cpp +++ b/core/benchmark/block_execution_benchmark.cpp @@ -204,7 +204,7 @@ namespace kagome::benchmark { OUTCOME_TRY(batch, storage.getEphemeralBatchAt(state)); OUTCOME_TRY(enc_block_weight, batch->get(BLOCK_WEIGHT_KEY)); - scale::ScaleDecoderStream stream{enc_block_weight}; + scale::ScaleDecoderStream stream{enc_block_weight.view()}; ConsumedWeight block_weight; try { stream >> block_weight; diff --git a/core/blockchain/impl/digest_tracker_impl.cpp b/core/blockchain/impl/digest_tracker_impl.cpp index b1f03f46e4..7f921b2ac5 100644 --- a/core/blockchain/impl/digest_tracker_impl.cpp +++ b/core/blockchain/impl/digest_tracker_impl.cpp @@ -71,13 +71,15 @@ namespace kagome::blockchain { const primitives::BlockContext &context, const primitives::Consensus &message) { if (message.consensus_engine_id == primitives::kBabeEngineId) { - OUTCOME_TRY(digest, scale::decode(message.data)); + OUTCOME_TRY(digest, + scale::decode(message.data.view())); return outcome::success(); } else if (message.consensus_engine_id == primitives::kGrandpaEngineId) { - OUTCOME_TRY(digest, - scale::decode(message.data)); + OUTCOME_TRY( + digest, + scale::decode(message.data.view())); return grandpa_digest_observer_->onDigest(context, digest); diff --git a/core/common/blob.hpp b/core/common/blob.hpp index 732673092f..069e707ca8 100644 --- a/core/common/blob.hpp +++ b/core/common/blob.hpp @@ -59,7 +59,7 @@ } \ \ static ::outcome::result fromSpan( \ - const gsl::span &span) { \ + const std::span &span) { \ OUTCOME_TRY(blob, Base::fromSpan(span)); \ return class_name{std::move(blob)}; \ } \ @@ -203,7 +203,7 @@ namespace kagome::common { * @return */ static outcome::result> fromSpan( - const gsl::span &span) { + const std::span &span) { if (span.size() != size_) { return BlobError::INCORRECT_LENGTH; } diff --git a/core/common/buffer.hpp b/core/common/buffer.hpp index 015c1bf4ef..bf2fe86ad5 100644 --- a/core/common/buffer.hpp +++ b/core/common/buffer.hpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include "common/buffer_view.hpp" #include "common/size_limited_containers.hpp" @@ -150,14 +150,14 @@ namespace kagome::common { /** * Returns a copy of a part of the buffer - * Works alike subspan() of gsl::span + * Works alike subspan() of std::span */ SLBuffer subbuffer(size_t offset = 0, size_t length = -1) const { return SLBuffer(view(offset, length)); } BufferView view(size_t offset = 0, size_t length = -1) const { - return BufferView{gsl::make_span(*this).subspan(offset, length)}; + return BufferView{std::span(*this).subspan(offset, length)}; } /** @@ -209,7 +209,7 @@ namespace kagome::common { template bool startsWith(const Prefix &prefix) const { if (this->size() >= prefix.size()) { - auto this_view = view().subspan(prefix.size()); + auto this_view = view().subspan(0, prefix.size()); return std::equal(this_view.begin(), this_view.end(), std::cbegin(prefix), diff --git a/core/common/buffer_back_insert_iterator.hpp b/core/common/buffer_back_insert_iterator.hpp index 3d87bfae21..06c845b5b8 100644 --- a/core/common/buffer_back_insert_iterator.hpp +++ b/core/common/buffer_back_insert_iterator.hpp @@ -43,7 +43,7 @@ class std::back_insert_iterator> { return *this; } - back_insert_iterator &operator=(gsl::span s) { + back_insert_iterator &operator=(std::span s) { buf_.put(s); return *this; } diff --git a/core/common/buffer_or_view.hpp b/core/common/buffer_or_view.hpp index 22adde63eb..0180c84792 100644 --- a/core/common/buffer_or_view.hpp +++ b/core/common/buffer_or_view.hpp @@ -15,7 +15,7 @@ namespace kagome::common { /// Moved owned buffer or readonly view. class BufferOrView { - using Span = gsl::span; + using Span = std::span; template using AsSpan = std::enable_if_t>; @@ -29,7 +29,7 @@ namespace kagome::common { template BufferOrView(const std::array &array) - : variant{gsl::make_span(array)} {} + : variant{std::span(array)} {} BufferOrView(const std::vector &vector) = delete; BufferOrView(std::vector &&vector) @@ -62,11 +62,26 @@ namespace kagome::common { return view(); } - /// Byte size. + /// Data ptr for contiguous_range + auto data() const { + return view().data(); + } + + /// Size for sized_range size_t size() const { return view().size(); } + /// Iteratior begin for range + auto begin() const { + return view().begin(); + } + + /// Iteratior end for range + auto end() const { + return view().end(); + } + /// Get mutable buffer reference. Copy once if view. Buffer &mut() { if (!isOwned()) { @@ -88,11 +103,11 @@ namespace kagome::common { template > friend bool operator==(const BufferOrView &l, const T &r) { - return l.view() == Span{r}; + return std::equal(l.view().begin(), l.view().end(), Span{r}.begin()); } template > friend bool operator==(const T &l, const BufferOrView &r) { - return Span{l} == r.view(); + return std::equal(r.view().begin(), r.view().end(), Span{l}.begin()); } }; } // namespace kagome::common diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index 92aef94490..e1b555ed07 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -6,13 +6,25 @@ #pragma once -#include +#include #include "common/bytestr.hpp" #include "common/hexutil.hpp" #include "common/lexicographical_compare_three_way.hpp" #include "macro/endianness_utils.hpp" +#include +#include + +template +concept RangeOfBytes = + std::ranges::sized_range and std::ranges::contiguous_range + and std::is_same_v, uint8_t>; + +inline auto operator""_bytes(const char *s, std::size_t size) { + return std::span(reinterpret_cast(s), size); +} + namespace kagome::common { template class SLBuffer; @@ -20,7 +32,7 @@ namespace kagome::common { namespace kagome::common { - class BufferView : public gsl::span { + class BufferView : public std::span { public: using span::span; @@ -38,26 +50,28 @@ namespace kagome::common { std::string_view toStringView() const { return byte2str(*this); } - }; - template - requires(std::is_base_of_v - or std::is_base_of_v) - and std::is_same_v - auto operator<=>(const L &lhs, const R &rhs) noexcept { - return cxx20::lexicographical_compare_three_way( - std::cbegin(lhs), std::cend(lhs), std::cbegin(rhs), std::cend(rhs)); - } + template + bool startsWith(const Prefix &prefix) const { + if (this->size() >= prefix.size()) { + auto this_view = subspan(0, prefix.size()); + return std::equal(this_view.begin(), + this_view.end(), + std::cbegin(prefix), + std::cend(prefix)); + } + return false; + } - template - requires(std::is_base_of_v - or std::is_base_of_v) - and std::is_same_v - auto operator==(const L &lhs, const R &rhs) noexcept { - return (lhs <=> rhs) == std::strong_ordering::equal; - } + 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; + } + }; 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 index 1075a45d00..38d8e50b19 100644 --- a/core/common/bytestr.hpp +++ b/core/common/bytestr.hpp @@ -7,21 +7,20 @@ #pragma once #include -#include #include #include namespace kagome { - inline gsl::span str2byte(const gsl::span &s) { - return libp2p::bytestr(s); + inline std::span str2byte(const std::span &s) { + return {reinterpret_cast(s.data()), s.size()}; } - inline std::string_view byte2str(const gsl::span &s) { + inline std::string_view byte2str(const std::span &s) { // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) - return {reinterpret_cast(s.data()), libp2p::spanSize(s)}; + return {reinterpret_cast(s.data()), s.size()}; } - inline std::vector bytestr_copy(gsl::span s) { + inline std::vector bytestr_copy(std::span s) { return {s.begin(), s.end()}; } } // namespace kagome diff --git a/core/common/hexutil.cpp b/core/common/hexutil.cpp index c71a6045dd..31baeb537e 100644 --- a/core/common/hexutil.cpp +++ b/core/common/hexutil.cpp @@ -7,7 +7,8 @@ #include "common/hexutil.hpp" #include -#include + +#include "common/buffer_view.hpp" OUTCOME_CPP_DEFINE_CATEGORY(kagome::common, UnhexError, e) { using kagome::common::UnhexError; @@ -44,19 +45,19 @@ namespace kagome::common { return str; } - std::string hex_upper(const gsl::span bytes) noexcept { + 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(const gsl::span bytes) noexcept { + 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(gsl::span bytes) noexcept { + std::string hex_lower_0x(BufferView bytes) noexcept { constexpr char prefix[] = {'0', 'x'}; constexpr size_t prefix_len = sizeof(prefix); @@ -68,6 +69,10 @@ namespace kagome::common { return res; } + std::string hex_lower_0x(const uint8_t *data, size_t size) noexcept { + return hex_lower_0x(BufferView(data, size)); + } + outcome::result> unhex(std::string_view hex) { std::vector blob; blob.reserve((hex.size() + 1) / 2); diff --git a/core/common/hexutil.hpp b/core/common/hexutil.hpp index e4482f497c..19ca6738bc 100644 --- a/core/common/hexutil.hpp +++ b/core/common/hexutil.hpp @@ -9,11 +9,12 @@ #include #include -#include #include "outcome/outcome.hpp" namespace kagome::common { + class BufferView; + /** * @brief error codes for exceptions that may occur during unhexing */ @@ -36,7 +37,7 @@ namespace kagome::common { * @param len length of bytes * @return hexstring */ - std::string hex_upper(gsl::span bytes) noexcept; + std::string hex_upper(BufferView bytes) noexcept; /** * @brief Converts bytes to hex representation @@ -44,21 +45,19 @@ namespace kagome::common { * @param len length of bytes * @return hexstring */ - std::string hex_lower(gsl::span bytes) noexcept; + std::string hex_lower(BufferView bytes) noexcept; /** * @brief Converts bytes to hex representation with prefix 0x * @param array bytes * @return hexstring */ - std::string hex_lower_0x(gsl::span bytes) noexcept; + std::string hex_lower_0x(BufferView bytes) noexcept; /** * @brief Adapter for ptr+size */ - inline std::string hex_lower_0x(const uint8_t *data, size_t size) noexcept { - return hex_lower_0x(gsl::span(data, size)); - } + std::string hex_lower_0x(const uint8_t *data, size_t size) noexcept; /** * @brief Converts hex representation to bytes diff --git a/core/common/int_serialization.cpp b/core/common/int_serialization.cpp index 85e33bea72..e65edc27e8 100644 --- a/core/common/int_serialization.cpp +++ b/core/common/int_serialization.cpp @@ -30,20 +30,16 @@ namespace kagome::common { } template - inline uint le_bytes_to_uint(gsl::span bytes) { - if (bytes.empty()) { - return uint(0); - } + inline uint le_bytes_to_uint(std::span bytes) { + BOOST_ASSERT(bytes.size() >= size); uint result; import_bits(result, bytes.begin(), bytes.end(), 8, false); return result; } template - inline uint be_bytes_to_uint(gsl::span bytes) { - if (bytes.empty()) { - return uint(0); - } + inline uint be_bytes_to_uint(std::span bytes) { + BOOST_ASSERT(bytes.size() >= size); uint result; import_bits(result, bytes.rbegin(), bytes.rend(), 8, false); return result; @@ -56,7 +52,8 @@ namespace kagome::common { return result; } - uint64_t le_bytes_to_uint64(gsl::span bytes) { + uint64_t le_bytes_to_uint64(std::span bytes) { + BOOST_ASSERT(bytes.size() >= 8); uint64_t number; memcpy(&number, bytes.data(), 8); return le64toh(number); @@ -68,7 +65,8 @@ namespace kagome::common { return result; } - uint64_t be_bytes_to_uint64(gsl::span bytes) { + uint64_t be_bytes_to_uint64(std::span bytes) { + BOOST_ASSERT(bytes.size() >= 8); uint64_t number; memcpy(&number, bytes.data(), 8); return be64toh(number); @@ -80,7 +78,8 @@ namespace kagome::common { } boost::multiprecision::uint128_t le_bytes_to_uint128( - gsl::span bytes) { + std::span bytes) { + BOOST_ASSERT(bytes.size() >= 16); return le_bytes_to_uint<16, boost::multiprecision::uint128_t>(bytes); } @@ -90,7 +89,8 @@ namespace kagome::common { } boost::multiprecision::uint128_t be_bytes_to_uint128( - gsl::span bytes) { + std::span bytes) { + BOOST_ASSERT(bytes.size() >= 16); return be_bytes_to_uint<16, boost::multiprecision::uint128_t>(bytes); } @@ -100,7 +100,8 @@ namespace kagome::common { } boost::multiprecision::uint256_t le_bytes_to_uint256( - gsl::span bytes) { + std::span bytes) { + BOOST_ASSERT(bytes.size() >= 32); return le_bytes_to_uint<32, boost::multiprecision::uint256_t>(bytes); } @@ -110,7 +111,8 @@ namespace kagome::common { } boost::multiprecision::uint256_t be_bytes_to_uint256( - gsl::span bytes) { + std::span bytes) { + BOOST_ASSERT(bytes.size() >= 32); return be_bytes_to_uint<32, boost::multiprecision::uint256_t>(bytes); } diff --git a/core/common/int_serialization.hpp b/core/common/int_serialization.hpp index ce87f4434c..8d97e25d3a 100644 --- a/core/common/int_serialization.hpp +++ b/core/common/int_serialization.hpp @@ -7,7 +7,7 @@ #pragma once #include -#include +#include namespace kagome::common { @@ -15,21 +15,21 @@ namespace kagome::common { using uint256_t = boost::multiprecision::uint256_t; std::array uint64_to_le_bytes(uint64_t number); - uint64_t le_bytes_to_uint64(gsl::span bytes); + uint64_t le_bytes_to_uint64(std::span bytes); std::array uint64_to_be_bytes(uint64_t number); - uint64_t be_bytes_to_uint64(gsl::span bytes); + uint64_t be_bytes_to_uint64(std::span bytes); std::array uint128_to_le_bytes(const uint128_t &i); - uint128_t le_bytes_to_uint128(gsl::span bytes); + uint128_t le_bytes_to_uint128(std::span bytes); std::array uint128_to_be_bytes(const uint128_t &i); - uint128_t be_bytes_to_uint128(gsl::span bytes); + uint128_t be_bytes_to_uint128(std::span bytes); std::array uint256_to_le_bytes(const uint256_t &i); - uint256_t le_bytes_to_uint256(gsl::span bytes); + uint256_t le_bytes_to_uint256(std::span bytes); std::array uint256_to_be_bytes(const uint256_t &i); - uint256_t be_bytes_to_uint256(gsl::span bytes); + uint256_t be_bytes_to_uint256(std::span bytes); } // namespace kagome::common diff --git a/core/common/size_limited_containers.hpp b/core/common/size_limited_containers.hpp index 0f30959d94..e62a014626 100644 --- a/core/common/size_limited_containers.hpp +++ b/core/common/size_limited_containers.hpp @@ -7,8 +7,8 @@ #pragma once #include -#include #include +#include #include #include #include @@ -29,7 +29,7 @@ namespace kagome::common { class SizeLimitedContainer : public BaseContainer { protected: using Base = BaseContainer; - using Span = gsl::span; + using Span = std::span; static constexpr bool size_check_is_enabled = MaxSize < std::numeric_limits::max(); @@ -364,7 +364,7 @@ namespace kagome::common { auto operator<=>(const SizeLimitedContainer &other) const { return cxx20::lexicographical_compare_three_way( - Base::cbegin(), Base::cend(), other.cbegin(), other.cend()); + Base::begin(), Base::end(), other.begin(), other.end()); } }; diff --git a/core/consensus/babe/impl/babe_digests_util.cpp b/core/consensus/babe/impl/babe_digests_util.cpp index 37a09966df..ee58d4caf7 100644 --- a/core/consensus/babe/impl/babe_digests_util.cpp +++ b/core/consensus/babe/impl/babe_digests_util.cpp @@ -41,11 +41,11 @@ namespace kagome::consensus::babe { const auto &digests = block_header.digest; for (const auto &digest : - gsl::make_span(digests).subspan(0, digests.size() - 1)) { + std::span(digests).subspan(0, digests.size() - 1)) { auto pre_runtime_opt = getFromVariant(digest); if (pre_runtime_opt.has_value()) { auto babe_block_header_res = - scale::decode(pre_runtime_opt->get().data); + scale::decode(pre_runtime_opt->get().data.view()); if (babe_block_header_res.has_value()) { // found the BabeBlockHeader digest; return return babe_block_header_res.value(); @@ -72,7 +72,7 @@ namespace kagome::consensus::babe { return DigestError::NO_TRAILING_SEAL_DIGEST; } - OUTCOME_TRY(seal_digest, scale::decode(seal_opt->get().data)); + OUTCOME_TRY(seal_digest, scale::decode(seal_opt->get().data.view())); return seal_digest; } diff --git a/core/consensus/grandpa/impl/authority_manager_impl.cpp b/core/consensus/grandpa/impl/authority_manager_impl.cpp index 80990b2a96..4e009723d0 100644 --- a/core/consensus/grandpa/impl/authority_manager_impl.cpp +++ b/core/consensus/grandpa/impl/authority_manager_impl.cpp @@ -498,8 +498,8 @@ namespace kagome::consensus::grandpa { // Zero-weighted authorities auto authorities = std::make_shared(*adjusted_node->authorities); - std::for_each(authorities->begin(), - authorities->end(), + std::for_each(authorities->authorities.begin(), + authorities->authorities.end(), [](auto &authority) { authority.weight = 0; }); return authorities; } @@ -552,7 +552,7 @@ namespace kagome::consensus::grandpa { new_authorities->id); size_t index = 0; - for (auto &authority : *new_authorities) { + for (auto &authority : new_authorities->authorities) { SL_TRACE(logger_, "New authority ({}/{}): id={} weight={}", ++index, @@ -688,13 +688,14 @@ namespace kagome::consensus::grandpa { node->authorities->id); size_t index = 0; - for (auto &authority : *new_authorities) { - SL_TRACE(logger_, - "New authority ({}/{}): id={} weight={}", - ++index, - new_authorities->authorities.size(), - authority.id.id, - authority.weight); + if (logger_->level() >= log::Level::TRACE) { + for (auto &authority : new_authorities->authorities) { + logger_->trace("New authority ({}/{}): id={} weight={}", + ++index, + new_authorities->authorities.size(), + authority.id.id, + authority.weight); + } } return outcome::success(); diff --git a/core/consensus/grandpa/voter_set.cpp b/core/consensus/grandpa/voter_set.cpp index 86af656241..996f5e4fe1 100644 --- a/core/consensus/grandpa/voter_set.cpp +++ b/core/consensus/grandpa/voter_set.cpp @@ -24,7 +24,7 @@ namespace kagome::consensus::grandpa { outcome::result> VoterSet::make( const primitives::AuthoritySet &voters) { auto set = std::make_shared(voters.id); - for (auto &voter : voters) { + for (auto &voter : voters.authorities) { OUTCOME_TRY(set->insert(primitives::GrandpaSessionKey{voter.id.id}, voter.weight)); } diff --git a/core/consensus/sassafras/impl/sassafras.cpp b/core/consensus/sassafras/impl/sassafras.cpp new file mode 100644 index 0000000000..daf4792517 --- /dev/null +++ b/core/consensus/sassafras/impl/sassafras.cpp @@ -0,0 +1,547 @@ +/** + * Copyright Quadrivium LLC + * All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "consensus/sassafras/impl/sassafras.hpp" + +#include +#include + +#include "application/app_configuration.hpp" +#include "blockchain/block_tree.hpp" +#include "consensus/babe/babe_config_repository.hpp" +#include "consensus/sassafras/impl/sassafras_digests_util.hpp" +#include "consensus/sassafras/impl/sassafras_error.hpp" +#include "consensus/sassafras/impl/threshold_util.hpp" +#include "consensus/sassafras/sassafras_config_repository.hpp" +#include "consensus/sassafras/sassafras_lottery.hpp" +#include "consensus/sassafras/types/seal.hpp" +#include "consensus/sassafras/types/slot_claim.hpp" +#include "consensus/timeline/backoff.hpp" +#include "consensus/timeline/impl/block_production_error.hpp" +#include "consensus/timeline/slots_util.hpp" +#include "crypto/crypto_store/session_keys.hpp" +#include "dispute_coordinator/dispute_coordinator.hpp" +#include "metrics/histogram_timer.hpp" +#include "parachain/availability/bitfield/store.hpp" +#include "parachain/backing/store.hpp" +#include "parachain/parachain_inherent_data.hpp" +#include "primitives/digest.hpp" +#include "primitives/inherent_data.hpp" +#include "scale.hpp" + +using namespace std::chrono_literals; + +namespace { + inline const auto kTimestampId = + kagome::primitives::InherentIdentifier::fromString("timstap0").value(); + inline const auto kSlotId = + kagome::primitives::InherentIdentifier::fromString("sassslot").value(); + inline const auto kParachainId = + kagome::primitives::InherentIdentifier::fromString("parachn0").value(); + + /// The maximum allowed number of slots past the expected slot as a delay for + /// block production. This is an intentional relaxation of block dropping algo + // static constexpr auto kMaxBlockSlotsOvertime = 2 + constexpr const char *kIsRelayChainValidator = + "kagome_node_is_active_validator"; + + kagome::metrics::HistogramTimer metric_block_proposal_time{ + "kagome_proposer_block_constructed", + "Time taken to construct new block", + {0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, + }; +} // namespace + +namespace kagome::consensus::sassafras { + + Sassafras::Sassafras( + const application::AppConfiguration &app_config, + const clock::SystemClock &clock, + std::shared_ptr block_tree, + LazySPtr slots_util, + std::shared_ptr sassafras_config_repo, + std::shared_ptr session_keys, + std::shared_ptr lottery, + std::shared_ptr bitfield_store, + std::shared_ptr backing_store, + std::shared_ptr dispute_coordinator) + : log_(log::createLogger("Sassafras", "sassafras")), + clock_(clock), + block_tree_(std::move(block_tree)), + slots_util_(std::move(slots_util)), + sassafras_config_repo_(std::move(sassafras_config_repo)), + session_keys_(std::move(session_keys)), + lottery_(std::move(lottery)), + bitfield_store_(std::move(bitfield_store)), + backing_store_(std::move(backing_store)), + dispute_coordinator_(std::move(dispute_coordinator)), + is_validator_by_config_(app_config.roles().flags.authority != 0), + telemetry_{telemetry::createTelemetryService()} { + BOOST_ASSERT(sassafras_config_repo_); + BOOST_ASSERT(session_keys_); + BOOST_ASSERT(lottery_); + BOOST_ASSERT(bitfield_store_); + BOOST_ASSERT(backing_store_); + BOOST_ASSERT(dispute_coordinator_); + + // Register metrics + metrics_registry_->registerGaugeFamily( + kIsRelayChainValidator, + "Tracks if the validator is in the active set. Updates at session " + "boundary."); + metric_is_relaychain_validator_ = + metrics_registry_->registerGaugeMetric(kIsRelayChainValidator); + metric_is_relaychain_validator_->set(false); + } + + ValidatorStatus Sassafras::getValidatorStatus( + const primitives::BlockInfo &block, EpochNumber epoch) const { + auto config = sassafras_config_repo_->config(block, epoch); + if (not config) { + SL_CRITICAL( + log_, + "Can't obtain digest of epoch {} from block tree for block {}", + epoch, + block); + return ValidatorStatus::NonValidator; + } + + const auto &authorities = config.value()->authorities; + if (session_keys_->getSassafrasKeyPair(authorities)) { + if (authorities.size() > 1) { + return ValidatorStatus::Validator; + } + return ValidatorStatus::SingleValidator; + } + + return ValidatorStatus::NonValidator; + } + + std::tuple Sassafras::getTimings() const { + return {sassafras_config_repo_->slotDuration(), + sassafras_config_repo_->epochLength()}; + } + + outcome::result Sassafras::getSlot( + const primitives::BlockHeader &header) const { + return sassafras::getSlot(header); + } + + outcome::result Sassafras::processSlot( + SlotNumber slot, const primitives::BlockInfo &best_block) { + auto slot_timestamp = clock_.now(); + + if (slot != slots_util_.get()->timeToSlot(slot_timestamp)) { + SL_DEBUG(log_, "Slot processing skipped: chance has missed"); + return outcome::success(); + } + OUTCOME_TRY(epoch_number, slots_util_.get()->slotToEpoch(best_block, slot)); + + auto config_res = sassafras_config_repo_->config(best_block, epoch_number); + [[unlikely]] if (not config_res.has_value()) { + SL_ERROR(log_, + "Can not get epoch: {}; Skipping slot processing", + config_res.error()); + return config_res.as_failure(); + } + auto &config = *config_res.value(); + + auto keypair = session_keys_->getBabeKeyPair(config.authorities); + if (not keypair) { + metric_is_relaychain_validator_->set(false); + if (is_validator_by_config_) { + SL_VERBOSE(log_, + "Authority not known, skipping slot processing. " + "Probably authority list has changed."); + } + return BlockProductionError::NO_VALIDATOR; + } + + Context ctx{.parent = best_block, + .epoch = epoch_number, + .slot = slot, + .slot_timestamp = slot_timestamp, + .keypair = std::move(keypair->first)}; + + metric_is_relaychain_validator_->set(true); + const auto &authority_index = keypair->second; + + // If epoch changed, generate and submit their candidate tickets along with + // validity proofs to the blockchain + if (lottery_->getEpoch() != epoch_number) { + // TODO Generate and submit tickets here + changeLotteryEpoch(ctx, epoch_number, authority_index, config); + } + + auto slot_leadership = + lottery_->getSlotLeadership(ctx.parent.hash, ctx.slot); + + if (slot_leadership.has_value()) { + const auto &vrf_result = slot_leadership.value(); + SL_DEBUG(log_, + "Babe author {} is primary slot-leader " + "(vrfOutput: {}, proof: {})", + ctx.keypair->public_key, + common::Buffer(vrf_result.output), + common::Buffer(vrf_result.proof)); + + return processSlotLeadership( + ctx, slot_timestamp, std::cref(vrf_result), authority_index); + } + + SL_TRACE(log_, + "Validator {} is not slot leader in current slot", + ctx.keypair->public_key); + + return BlockProductionError::NO_SLOT_LEADER; + } + + outcome::result Sassafras::calculatePreDigest( + const Context &ctx, + std::optional> output, + primitives::AuthorityIndex authority_index) const { + SlotClaim slot_claim{ + .authority_index = authority_index, + .slot_number = ctx.slot, + .signature = {}, // FIXME + .ticket_claim = {}, // FIXME + }; + + // if (slot_claim.needVRFCheck()) { + // if (not output.has_value()) { + // SL_ERROR( + // log_, + // "VRF proof is required to build block header but was not passed"); + // return BabeError::MISSING_PROOF; + // } + // slot_claim.vrf_output = output.value(); + // } + + auto encoded_slot_claim_res = scale::encode(slot_claim); + if (encoded_slot_claim_res.has_error()) { + SL_ERROR( + log_, "cannot encode SlotClaim: {}", encoded_slot_claim_res.error()); + return encoded_slot_claim_res.error(); + } + common::Buffer encoded_slot_claim{encoded_slot_claim_res.value()}; + + // clang-format on + return primitives::PreRuntime{ + {primitives::kBabeEngineId, encoded_slot_claim}}; + } + + outcome::result Sassafras::sealBlock( + const Context &ctx, const primitives::Block &block) const { + // BOOST_ASSERT(ctx.keypair != nullptr); + // + // // Calculate and save hash, 'cause it's new produced block + // // Note: it is temporary hash significant for signing + // primitives::calculateBlockHash( + // const_cast(block.header), *hasher_); + // + // auto signature_res = + // sr25519_provider_->sign(*ctx.keypair, block.header.hash()); + // if (signature_res.has_value()) { + // Seal seal{.signature = signature_res.value()}; + // auto encoded_seal = common::Buffer(scale::encode(seal).value()); + // return primitives::Seal{{primitives::kBabeEngineId, encoded_seal}}; + // } + // + // SL_ERROR(log_, "Error signing a block seal: {}", signature_res.error()); + // return signature_res.as_failure(); + return primitives::Seal{}; + } + + outcome::result Sassafras::processSlotLeadership( + const Context &ctx, + TimePoint slot_timestamp, + std::optional> output, + primitives::AuthorityIndex authority_index) { + auto parent_header_res = block_tree_->getBlockHeader(ctx.parent.hash); + BOOST_ASSERT_MSG(parent_header_res.has_value(), + "The best block is always known"); + auto &parent_header = parent_header_res.value(); + + if (backoff(*this, + parent_header, + block_tree_->getLastFinalized().number, + ctx.slot)) { + SL_INFO(log_, + "Backing off claiming new slot for block authorship: " + "finality is lagging."); + return BlockProductionError::BACKING_OFF; + } + + BOOST_ASSERT(ctx.keypair != nullptr); + + // build a block to be announced + SL_VERBOSE(log_, + "Obtained slot leadership in slot {} epoch {}", + ctx.slot, + ctx.epoch); + + SL_INFO(log_, "Babe builds block on top of block {}", ctx.parent); + + primitives::InherentData inherent_data; + auto now = std::chrono::duration_cast( + slot_timestamp.time_since_epoch()) + .count(); + + if (auto res = inherent_data.putData(kTimestampId, now); + res.has_error()) { + SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); + return SassafrasError::CAN_NOT_PREPARE_BLOCK; + } + + if (auto res = inherent_data.putData(kSlotId, ctx.slot); res.has_error()) { + SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); + return SassafrasError::CAN_NOT_PREPARE_BLOCK; + } + + parachain::ParachainInherentData parachain_inherent_data; + + { + auto &relay_parent = ctx.parent.hash; + parachain_inherent_data.bitfields = + bitfield_store_->getBitfields(relay_parent); + + parachain_inherent_data.backed_candidates = + backing_store_->get(relay_parent); + SL_TRACE(log_, + "Get backed candidates from store.(count={}, relay_parent={})", + parachain_inherent_data.backed_candidates.size(), + relay_parent); + + parachain_inherent_data.parent_header = std::move(parent_header); + + { // Fill disputes + std::latch latch(1); + dispute_coordinator_->getDisputeForInherentData( + ctx.parent, [&](auto res) { + parachain_inherent_data.disputes = std::move(res); + latch.count_down(); + }); + latch.wait(); + } + } + + if (auto res = inherent_data.putData(kParachainId, parachain_inherent_data); + res.has_error()) { + SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); + return SassafrasError::CAN_NOT_PREPARE_BLOCK; + } + + // clang-format off + +// auto proposal_start = std::chrono::steady_clock::now(); +// // calculate babe_pre_digest +// auto babe_pre_digest_res = +// 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; +// } +// const auto &babe_pre_digest = babe_pre_digest_res.value(); +// +// auto propose = [this, +// self{shared_from_this()}, +// inherent_data{std::move(inherent_data)}, +// now, +// proposal_start, +// babe_pre_digest{std::move(babe_pre_digest)}, +// ctx]() mutable { +// auto changes_tracker = +// std::make_shared(); +// +// // create new block +// auto res = proposer_->propose(ctx.parent, +// slots_util_.get()->slotFinishTime(ctx.slot) +// - +// babe_config_repo_->slotDuration() +// / 3, +// inherent_data, +// {babe_pre_digest}, +// changes_tracker); +// if (not res) { +// SL_ERROR(log_, "Cannot propose a block: {}", res.error()); +// return; +// } +// auto &unsealed_block = res.value(); +// auto proposed = [self, +// now, +// proposal_start, +// changes_tracker{std::move(changes_tracker)}, +// unsealed_block{std::move(unsealed_block)}, +// ctx]() mutable { +// auto res = +// self->processSlotLeadershipProposed(ctx, +// now, +// proposal_start, +// std::move(changes_tracker), +// std::move(unsealed_block)); +// if (res.has_error()) { +// SL_ERROR(self->log_, "Cannot propose a block: {}", res.error()); +// return; +// } +// }; +// main_thread_->post(std::move(proposed)); +// }; +// +// io_context_->post(std::move(propose)); + + // clang-format on + return outcome::success(); + } + + // outcome::result Sassafras::processSlotLeadershipProposed( + // const Context &ctx, + // uint64_t now, + // clock::SteadyClock::TimePoint proposal_start, + // std::shared_ptr + // &&changes_tracker, + // primitives::Block &&block) { + // auto duration_ms = + // metric_block_proposal_time.observe(proposal_start).count(); + // SL_DEBUG(log_, "Block has been built in {} ms", duration_ms); + // + // // Ensure block's extrinsics root matches extrinsics in block's body + // BOOST_ASSERT_MSG( + // [&block]() { + // using boost::adaptors::transformed; + // const auto &ext_root_res = + // storage::trie::calculateOrderedTrieHash( + // storage::trie::StateVersion::V0, + // block.body | transformed([](const auto &ext) { + // return common::Buffer{scale::encode(ext).value()}; + // })); + // return ext_root_res.has_value() + // and (ext_root_res.value() == block.header.extrinsics_root); + // }(), + // "Extrinsics root does not match extrinsics in the block"); + // + // // seal the block + // 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; + // } + // + // // add seal digest item + // block.header.digest.emplace_back(seal_res.value()); + // + // // Calculate and save hash, 'cause seal digest was added + // primitives::calculateBlockHash(block.header, *hasher_); + // + // if (clock_.now() > slots_util_.get()->slotFinishTime( + // ctx.slot + kMaxBlockSlotsOvertime)) { + // SL_WARN(log_, + // "Block was not built on time. " + // "Allowed slots ({}) have passed. " + // "If you are executing in debug mode, consider to rebuild in " + // "release", + // kMaxBlockSlotsOvertime); + // return BabeError::WAS_NOT_BUILD_ON_TIME; + // } + // + // const auto block_info = block.header.blockInfo(); + // + // auto previous_best_block = block_tree_->bestBlock(); + // + // // 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()); auto removal_res = + // block_tree_->removeLeaf(block_info.hash); if (removal_res.has_error() + // and removal_res + // != outcome::failure( + // blockchain::BlockTreeError::BLOCK_IS_NOT_LEAF)) { + // SL_WARN(log_, + // "Rolling back of block {} is failed: {}", + // block_info, + // removal_res.error()); + // } + // return BabeError::CAN_NOT_SAVE_BLOCK; + // } + // + // changes_tracker->onBlockAdded( + // block_info.hash, storage_sub_engine_, chain_sub_engine_); + // + // telemetry_->notifyBlockImported(block_info, + // telemetry::BlockOrigin::kOwn); telemetry_->pushBlockStats(); + // + // // observe digest of block + // // (must be done strictly after block will be added) + // auto digest_tracking_res = digest_tracker_->onDigest( + // {.block_info = block_info, .header = block.header}, + // block.header.digest); + // + // if (digest_tracking_res.has_error()) { + // SL_WARN(log_, + // "Error while tracking digest of block {}: {}", + // block_info, + // digest_tracking_res.error()); + // return outcome::success(); + // } + // + // // finally, broadcast the sealed block + // announce_transmitter_->blockAnnounce(network::BlockAnnounce{ + // block.header, + // block_info == block_tree_->bestBlock() ? network::BlockState::Best + // : + // network::BlockState::Normal, + // common::Buffer{}, + // }); + // SL_DEBUG( + // log_, + // "Announced block number {} in slot {} (epoch {}) with timestamp {}", + // block.header.number, + // ctx.slot, + // ctx.epoch, + // now); + // + // auto current_best_block = block_tree_->bestBlock(); + // + // // Create new offchain worker for block if it is best only + // if (current_best_block.number > previous_best_block.number) { + // auto ocw_res = offchain_worker_api_->offchain_worker( + // block.header.parent_hash, block.header); + // if (ocw_res.has_failure()) { + // log_->error("Can't spawn offchain worker for block {}: {}", + // block_info, + // ocw_res.error()); + // } + // } + // + // return outcome::success(); + // } + + void Sassafras::changeLotteryEpoch(const Context &ctx, + const EpochNumber &epoch, + primitives::AuthorityIndex authority_index, + const Epoch &sassafras_config) const { + BOOST_ASSERT(ctx.keypair != nullptr); + + Threshold ticket_threshold = + ticket_id_threshold(sassafras_config.config.redundancy_factor, + sassafras_config.epoch_length, + sassafras_config.config.attempts_number, + sassafras_config.authorities.size()) + .number; + + Threshold threshold; // FIXME + // = calculateThreshold(sassafras_config.leadership_rate, + // sassafras_config.authorities, + // authority_index); + + lottery_->changeEpoch(epoch, + sassafras_config.randomness, + ticket_threshold, + threshold, + *ctx.keypair); + } + +} // namespace kagome::consensus::sassafras diff --git a/core/crypto/bip39/bip39_provider.hpp b/core/crypto/bip39/bip39_provider.hpp index 0b378be45b..74c53b7d51 100644 --- a/core/crypto/bip39/bip39_provider.hpp +++ b/core/crypto/bip39/bip39_provider.hpp @@ -32,7 +32,7 @@ namespace kagome::crypto { * @return seed bytes */ virtual outcome::result makeSeed( - gsl::span entropy, std::string_view password) const = 0; + std::span entropy, std::string_view password) const = 0; virtual outcome::result generateSeed( std::string_view mnemonic_phrase) const = 0; diff --git a/core/crypto/bip39/bip39_types.hpp b/core/crypto/bip39/bip39_types.hpp index ccc5c55c81..794e84eb40 100644 --- a/core/crypto/bip39/bip39_types.hpp +++ b/core/crypto/bip39/bip39_types.hpp @@ -28,7 +28,7 @@ namespace kagome::crypto::bip39 { template outcome::result as() const { return T::fromSpan( - gsl::make_span(seed).first(std::min(seed.size(), T::size()))); + std::span(seed).first(std::min(seed.size(), T::size()))); } }; } // 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 16ce962fef..be003804a0 100644 --- a/core/crypto/bip39/impl/bip39_provider_impl.cpp +++ b/core/crypto/bip39/impl/bip39_provider_impl.cpp @@ -61,7 +61,7 @@ namespace kagome::crypto { } outcome::result Bip39ProviderImpl::makeSeed( - gsl::span entropy, std::string_view password) const { + std::span entropy, std::string_view password) const { constexpr size_t iterations_count = 2048u; constexpr auto default_salt = "mnemonic"; diff --git a/core/crypto/bip39/impl/bip39_provider_impl.hpp b/core/crypto/bip39/impl/bip39_provider_impl.hpp index ec5be0df76..3ae03f8bf2 100644 --- a/core/crypto/bip39/impl/bip39_provider_impl.hpp +++ b/core/crypto/bip39/impl/bip39_provider_impl.hpp @@ -25,7 +25,7 @@ namespace kagome::crypto { const std::vector &word_list) const override; outcome::result makeSeed( - gsl::span entropy, + std::span entropy, std::string_view password) const override; outcome::result generateSeed( diff --git a/core/crypto/bip39/mnemonic.cpp b/core/crypto/bip39/mnemonic.cpp index 0deebffd6a..ab5c7ae170 100644 --- a/core/crypto/bip39/mnemonic.cpp +++ b/core/crypto/bip39/mnemonic.cpp @@ -93,7 +93,7 @@ namespace kagome::crypto::bip39 { } } - if (boost::starts_with(seed, "0x")) { + if (seed.substr(0, 2) == "0x") { OUTCOME_TRY(bytes, common::unhexWith0x(seed)); mnemonic.seed = common::Buffer{std::move(bytes)}; } else { diff --git a/core/crypto/crypto_store/crypto_store_impl.cpp b/core/crypto/crypto_store/crypto_store_impl.cpp index 7b40810a1b..9242a1b5f2 100644 --- a/core/crypto/crypto_store/crypto_store_impl.cpp +++ b/core/crypto/crypto_store/crypto_store_impl.cpp @@ -6,7 +6,7 @@ #include "crypto/crypto_store/crypto_store_impl.hpp" -#include +#include #include "common/bytestr.hpp" #include "common/visitor.hpp" @@ -129,7 +129,7 @@ namespace kagome::crypto { return kp_opt.value(); } OUTCOME_TRY(phrase, - file_storage_->searchForPhrase(key_type, gsl::make_span(pk))); + file_storage_->searchForPhrase(key_type, std::span(pk))); if (not phrase) { return CryptoStoreError::KEY_NOT_FOUND; } @@ -144,7 +144,7 @@ namespace kagome::crypto { return kp_opt.value(); } OUTCOME_TRY(phrase, - file_storage_->searchForPhrase(key_type, gsl::make_span(pk))); + file_storage_->searchForPhrase(key_type, std::span(pk))); if (not phrase) { return CryptoStoreError::KEY_NOT_FOUND; } @@ -159,7 +159,7 @@ namespace kagome::crypto { return kp_opt.value(); } OUTCOME_TRY(phrase, - file_storage_->searchForPhrase(key_type, gsl::make_span(pk))); + file_storage_->searchForPhrase(key_type, std::span(pk))); if (not phrase) { return CryptoStoreError::KEY_NOT_FOUND; } diff --git a/core/crypto/crypto_store/crypto_suites.hpp b/core/crypto/crypto_store/crypto_suites.hpp index 4491e3d955..feb4be7aee 100644 --- a/core/crypto/crypto_store/crypto_suites.hpp +++ b/core/crypto/crypto_store/crypto_suites.hpp @@ -27,7 +27,7 @@ namespace kagome::crypto { using Keypair = KeypairT; using KeypairAndSeed = KeypairAndSeedT; using Seed = SeedT; - using Junctions = gsl::span; + using Junctions = std::span; virtual ~CryptoSuite() = default; @@ -65,13 +65,13 @@ namespace kagome::crypto { * Create a public key from its bytes */ virtual outcome::result toPublicKey( - gsl::span bytes) const noexcept = 0; + std::span bytes) const noexcept = 0; /** * Create a seed from its bytes */ virtual outcome::result toSeed( - gsl::span bytes) const noexcept = 0; + std::span bytes) const noexcept = 0; }; class EcdsaSuite : public CryptoSuite toPublicKey( - gsl::span bytes) const noexcept override { + std::span bytes) const noexcept override { OUTCOME_TRY(blob, EcdsaPublicKey::fromSpan(bytes)); return EcdsaPublicKey{blob}; } outcome::result toSeed( - gsl::span bytes) const noexcept override { + std::span bytes) const noexcept override { return EcdsaSeed::fromSpan(bytes); } @@ -146,13 +146,13 @@ namespace kagome::crypto { } outcome::result toPublicKey( - gsl::span bytes) const noexcept override { + std::span bytes) const noexcept override { OUTCOME_TRY(blob, Ed25519PublicKey::fromSpan(bytes)); return Ed25519PublicKey{blob}; } outcome::result toSeed( - gsl::span bytes) const noexcept override { + std::span bytes) const noexcept override { return Ed25519Seed::fromSpan(bytes); } @@ -189,13 +189,13 @@ namespace kagome::crypto { } outcome::result toPublicKey( - gsl::span bytes) const noexcept override { + std::span bytes) const noexcept override { OUTCOME_TRY(blob, Sr25519PublicKey::fromSpan(bytes)); return Sr25519PublicKey{std::move(blob)}; } outcome::result toSeed( - gsl::span bytes) const noexcept override { + std::span bytes) const noexcept override { return Sr25519Seed::fromSpan(bytes); } diff --git a/core/crypto/crypto_store/key_file_storage.cpp b/core/crypto/crypto_store/key_file_storage.cpp index 25416cf981..807bf53931 100644 --- a/core/crypto/crypto_store/key_file_storage.cpp +++ b/core/crypto/crypto_store/key_file_storage.cpp @@ -62,14 +62,14 @@ namespace kagome::crypto { } KeyFileStorage::Path KeyFileStorage::composeKeyPath( - KeyType key_type, gsl::span public_key) const { + KeyType key_type, std::span public_key) const { return keystore_path_ / encodeKeyFileName(key_type, public_key); } outcome::result KeyFileStorage::saveKeyPair( KeyType type, - gsl::span public_key, - gsl::span seed) const { + std::span public_key, + std::span seed) const { auto &&path = composeKeyPath(type, public_key); OUTCOME_TRY(saveKeyHexAtPath(seed, path)); SL_TRACE(logger_, @@ -110,7 +110,7 @@ namespace kagome::crypto { } outcome::result KeyFileStorage::saveKeyHexAtPath( - gsl::span private_key, + std::span private_key, const KeyFileStorage::Path &path) const { std::ofstream file; file.open(path.native(), std::ios::out | std::ios::trunc); @@ -154,7 +154,7 @@ namespace kagome::crypto { } outcome::result> KeyFileStorage::searchForPhrase( - KeyType type, gsl::span public_key_bytes) const { + KeyType type, std::span public_key_bytes) const { auto key_path = composeKeyPath(type, public_key_bytes); namespace fs = filesystem; std::error_code ec{}; diff --git a/core/crypto/crypto_store/key_file_storage.hpp b/core/crypto/crypto_store/key_file_storage.hpp index 853f9211a0..ceec895ba0 100644 --- a/core/crypto/crypto_store/key_file_storage.hpp +++ b/core/crypto/crypto_store/key_file_storage.hpp @@ -55,15 +55,15 @@ namespace kagome::crypto { * returns its content if it's a valid hex blob or mnemonic phrase json. */ outcome::result> searchForPhrase( - KeyType type, gsl::span public_key_bytes) const; + KeyType type, std::span public_key_bytes) const; /** * Stores the \param seed that generates the \param public_key to the key * storage */ outcome::result saveKeyPair(KeyType type, - gsl::span public_key, - gsl::span seed) const; + std::span public_key, + std::span seed) const; /** * Save key as hex to the specific path. @@ -72,7 +72,7 @@ namespace kagome::crypto { * @param file_path - user-provided path to create the file * @return an error if any */ - outcome::result saveKeyHexAtPath(gsl::span private_key, + outcome::result saveKeyHexAtPath(std::span private_key, const Path &path) const; private: @@ -84,7 +84,7 @@ namespace kagome::crypto { std::string_view file_name) const; Path composeKeyPath(KeyType key_type, - gsl::span public_key) const; + std::span public_key) const; Path keystore_path_; log::Logger logger_; diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.cpp b/core/crypto/ecdsa/ecdsa_provider_impl.cpp index 9dafb27e0d..6c8a623cf5 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.cpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.cpp @@ -42,7 +42,7 @@ namespace kagome::crypto { return Error::SOFT_JUNCTION_NOT_SUPPORTED; } seed = hasher_->blake2b_256( - scale::encode("Secp256k1HDKD", seed, junction.cc).value()); + scale::encode("Secp256k1HDKD"_bytes, seed, junction.cc).value()); } EcdsaKeypair keys; keys.secret_key = seed; @@ -65,7 +65,7 @@ namespace kagome::crypto { } outcome::result EcdsaProviderImpl::sign( - gsl::span message, const EcdsaPrivateKey &key) const { + std::span message, const EcdsaPrivateKey &key) const { return signPrehashed(hasher_->blake2b_256(message), key); } @@ -93,7 +93,7 @@ namespace kagome::crypto { } outcome::result EcdsaProviderImpl::verify( - gsl::span message, + std::span message, const EcdsaSignature &signature, const EcdsaPublicKey &publicKey) const { return verifyPrehashed(hasher_->blake2b_256(message), signature, publicKey); diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.hpp b/core/crypto/ecdsa/ecdsa_provider_impl.hpp index bdda8279c0..03979ddde2 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.hpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.hpp @@ -31,7 +31,7 @@ namespace kagome::crypto { const EcdsaSeed &seed, Junctions junctions) const override; outcome::result sign( - gsl::span message, + std::span message, const EcdsaPrivateKey &key) const override; outcome::result signPrehashed( @@ -39,7 +39,7 @@ namespace kagome::crypto { const EcdsaPrivateKey &key) const override; outcome::result verify( - gsl::span message, + std::span message, const EcdsaSignature &signature, const EcdsaPublicKey &publicKey) const override; diff --git a/core/crypto/ecdsa_provider.hpp b/core/crypto/ecdsa_provider.hpp index a2d0656f92..c70cff8757 100644 --- a/core/crypto/ecdsa_provider.hpp +++ b/core/crypto/ecdsa_provider.hpp @@ -13,7 +13,7 @@ namespace kagome::crypto { class EcdsaProvider { public: - using Junctions = gsl::span; + using Junctions = std::span; virtual ~EcdsaProvider() = default; @@ -21,14 +21,14 @@ namespace kagome::crypto { const EcdsaSeed &seed, Junctions junctions) const = 0; virtual outcome::result sign( - gsl::span message, const EcdsaPrivateKey &key) const = 0; + std::span message, const EcdsaPrivateKey &key) const = 0; virtual outcome::result signPrehashed( const EcdsaPrehashedMessage &message, const EcdsaPrivateKey &key) const = 0; virtual outcome::result verify( - gsl::span message, + std::span message, const EcdsaSignature &signature, const EcdsaPublicKey &publicKey) const = 0; diff --git a/core/crypto/ed25519/ed25519_provider_impl.cpp b/core/crypto/ed25519/ed25519_provider_impl.cpp index e9f3a7c937..50706af5cc 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.cpp +++ b/core/crypto/ed25519/ed25519_provider_impl.cpp @@ -39,7 +39,7 @@ namespace kagome::crypto { return Error::SOFT_JUNCTION_NOT_SUPPORTED; } seed = hasher_->blake2b_256( - scale::encode("Ed25519HDKD", seed, junction.cc).value()); + scale::encode("Ed25519HDKD"_bytes, seed, junction.cc).value()); } std::array kp_bytes{}; ed25519_keypair_from_seed(kp_bytes.data(), seed.data()); @@ -53,7 +53,7 @@ namespace kagome::crypto { } outcome::result Ed25519ProviderImpl::sign( - const Ed25519Keypair &keypair, gsl::span message) const { + const Ed25519Keypair &keypair, std::span message) const { Ed25519Signature sig; std::array keypair_bytes; std::copy(keypair.secret_key.begin(), @@ -74,7 +74,7 @@ namespace kagome::crypto { } outcome::result Ed25519ProviderImpl::verify( const Ed25519Signature &signature, - gsl::span message, + std::span message, const Ed25519PublicKey &public_key) const { auto res = ed25519_verify(signature.data(), public_key.data(), diff --git a/core/crypto/ed25519/ed25519_provider_impl.hpp b/core/crypto/ed25519/ed25519_provider_impl.hpp index d1e16467b9..deed896b17 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.hpp +++ b/core/crypto/ed25519/ed25519_provider_impl.hpp @@ -28,11 +28,11 @@ namespace kagome::crypto { outcome::result sign( const Ed25519Keypair &keypair, - gsl::span message) const override; + std::span message) const override; outcome::result verify( const Ed25519Signature &signature, - gsl::span message, + std::span message, const Ed25519PublicKey &public_key) const override; private: diff --git a/core/crypto/ed25519_provider.hpp b/core/crypto/ed25519_provider.hpp index 23e87a340a..7cd2ba96b6 100644 --- a/core/crypto/ed25519_provider.hpp +++ b/core/crypto/ed25519_provider.hpp @@ -13,7 +13,7 @@ namespace kagome::crypto { class Ed25519Provider { public: - using Junctions = gsl::span; + using Junctions = std::span; virtual ~Ed25519Provider() = default; @@ -35,7 +35,7 @@ namespace kagome::crypto { */ virtual outcome::result sign( const Ed25519Keypair &keypair, - gsl::span message) const = 0; + std::span message) const = 0; /** * Verifies that \param message was derived using \param public_key on @@ -43,7 +43,7 @@ namespace kagome::crypto { */ virtual outcome::result verify( const Ed25519Signature &signature, - gsl::span message, + std::span message, const Ed25519PublicKey &public_key) const = 0; }; } // namespace kagome::crypto diff --git a/core/crypto/hasher.hpp b/core/crypto/hasher.hpp index 0cdbbaba3d..15b9f0f77e 100644 --- a/core/crypto/hasher.hpp +++ b/core/crypto/hasher.hpp @@ -7,7 +7,7 @@ #pragma once #include "common/blob.hpp" -#include "common/buffer.hpp" +#include "common/buffer_view.hpp" namespace kagome::crypto { class Hasher { @@ -22,72 +22,72 @@ namespace kagome::crypto { /** * @brief twox_64 calculates 8-byte twox hash - * @param buffer source buffer + * @param data source data * @return 64-bit hash value */ - virtual Hash64 twox_64(gsl::span buffer) const = 0; + virtual Hash64 twox_64(common::BufferView data) const = 0; /** * @brief blake2b_64 function calculates 8-byte blake2b hash - * @param buffer source value + * @param data source value * @return 64-bit hash value */ - virtual Hash64 blake2b_64(gsl::span buffer) const = 0; + virtual Hash64 blake2b_64(common::BufferView data) const = 0; /** * @brief twox_128 calculates 16-byte twox hash - * @param buffer source buffer + * @param data source data * @return 128-bit hash value */ - virtual Hash128 twox_128(gsl::span buffer) const = 0; + virtual Hash128 twox_128(common::BufferView data) const = 0; /** * @brief blake2b_128 function calculates 16-byte blake2b hash - * @param buffer source value + * @param data source value * @return 128-bit hash value */ - virtual Hash128 blake2b_128(gsl::span buffer) const = 0; + virtual Hash128 blake2b_128(common::BufferView data) const = 0; /** * @brief twox_256 calculates 32-byte twox hash - * @param buffer source buffer + * @param data source data * @return 256-bit hash value */ - virtual Hash256 twox_256(gsl::span buffer) const = 0; + virtual Hash256 twox_256(common::BufferView data) const = 0; /** * @brief blake2b_256 function calculates 32-byte blake2b hash - * @param buffer source value + * @param data source value * @return 256-bit hash value */ - virtual Hash256 blake2b_256(gsl::span buffer) const = 0; + virtual Hash256 blake2b_256(common::BufferView data) const = 0; /** * @brief blake2b_512 function calculates 64-byte blake2b hash - * @param buffer source value + * @param data source value * @return 512-bit hash value */ - virtual Hash512 blake2b_512(gsl::span buffer) const = 0; + virtual Hash512 blake2b_512(common::BufferView data) const = 0; /** * @brief keccak_256 function calculates 32-byte keccak hash - * @param buffer source value + * @param data source value * @return 256-bit hash value */ - virtual Hash256 keccak_256(gsl::span buffer) const = 0; + virtual Hash256 keccak_256(common::BufferView data) const = 0; /** * @brief blake2s_256 function calculates 32-byte blake2s hash - * @param buffer source value + * @param data source value * @return 256-bit hash value */ - virtual Hash256 blake2s_256(gsl::span buffer) const = 0; + virtual Hash256 blake2s_256(common::BufferView data) const = 0; /** * @brief sha2_256 function calculates 32-byte sha2-256 hash - * @param buffer source value + * @param data source value * @return 256-bit hash value */ - virtual Hash256 sha2_256(gsl::span buffer) const = 0; + virtual Hash256 sha2_256(common::BufferView data) const = 0; }; } // namespace kagome::crypto diff --git a/core/crypto/hasher/hasher_impl.cpp b/core/crypto/hasher/hasher_impl.cpp index 688ac7cff7..d2f36c0eb0 100644 --- a/core/crypto/hasher/hasher_impl.cpp +++ b/core/crypto/hasher/hasher_impl.cpp @@ -6,7 +6,7 @@ #include "crypto/hasher/hasher_impl.hpp" -#include +#include #include "crypto/blake2/blake2b.h" #include "crypto/blake2/blake2s.h" @@ -20,60 +20,60 @@ namespace kagome::crypto { using common::Hash512; using common::Hash64; - Hash64 HasherImpl::twox_64(gsl::span buffer) const { - return make_twox64(buffer); + Hash64 HasherImpl::twox_64(common::BufferView data) const { + return make_twox64(data); } - Hash64 HasherImpl::blake2b_64(gsl::span buffer) const { + Hash64 HasherImpl::blake2b_64(common::BufferView data) const { Hash64 out; - blake2b(out.data(), out.size(), nullptr, 0, buffer.data(), buffer.size()); + blake2b(out.data(), out.size(), nullptr, 0, data.data(), data.size()); return out; } - Hash128 HasherImpl::twox_128(gsl::span buffer) const { - return make_twox128(buffer); + Hash128 HasherImpl::twox_128(common::BufferView data) const { + return make_twox128(data); } - Hash128 HasherImpl::blake2b_128(gsl::span buffer) const { + Hash128 HasherImpl::blake2b_128(common::BufferView data) const { Hash128 out; - blake2b(out.data(), out.size(), nullptr, 0, buffer.data(), buffer.size()); + blake2b(out.data(), out.size(), nullptr, 0, data.data(), data.size()); return out; } - Hash256 HasherImpl::twox_256(gsl::span buffer) const { - return make_twox256(buffer); + Hash256 HasherImpl::twox_256(common::BufferView data) const { + return make_twox256(data); } - Hash256 HasherImpl::blake2b_256(gsl::span buffer) const { + Hash256 HasherImpl::blake2b_256(common::BufferView data) const { Hash256 out; - blake2b(out.data(), 32, nullptr, 0, buffer.data(), buffer.size()); + blake2b(out.data(), 32, nullptr, 0, data.data(), data.size()); return out; } - Hash512 HasherImpl::blake2b_512(gsl::span buffer) const { + Hash512 HasherImpl::blake2b_512(common::BufferView data) const { Hash512 out; - blake2b(out.data(), 64, nullptr, 0, buffer.data(), buffer.size()); + blake2b(out.data(), 64, nullptr, 0, data.data(), data.size()); return out; } - Hash256 HasherImpl::keccak_256(gsl::span buffer) const { + Hash256 HasherImpl::keccak_256(common::BufferView data) const { Hash256 out; sha3_HashBuffer(256, SHA3_FLAGS::SHA3_FLAGS_KECCAK, - buffer.data(), - buffer.size(), + data.data(), + data.size(), out.data(), 32); return out; } - Hash256 HasherImpl::blake2s_256(gsl::span buffer) const { + Hash256 HasherImpl::blake2s_256(common::BufferView data) const { Hash256 out; - blake2s(out.data(), 32, nullptr, 0, buffer.data(), buffer.size()); + blake2s(out.data(), 32, nullptr, 0, data.data(), data.size()); return out; } - Hash256 HasherImpl::sha2_256(gsl::span buffer) const { - return crypto::sha256(buffer); + Hash256 HasherImpl::sha2_256(common::BufferView data) const { + return crypto::sha256(data); } } // namespace kagome::crypto diff --git a/core/crypto/hasher/hasher_impl.hpp b/core/crypto/hasher/hasher_impl.hpp index 996183df62..0ee62fb2c4 100644 --- a/core/crypto/hasher/hasher_impl.hpp +++ b/core/crypto/hasher/hasher_impl.hpp @@ -14,25 +14,25 @@ namespace kagome::crypto { public: ~HasherImpl() override = default; - Hash64 twox_64(gsl::span buffer) const override; + Hash64 twox_64(common::BufferView data) const override; - Hash64 blake2b_64(gsl::span buffer) const override; + Hash64 blake2b_64(common::BufferView data) const override; - Hash128 twox_128(gsl::span buffer) const override; + Hash128 twox_128(common::BufferView data) const override; - Hash128 blake2b_128(gsl::span buffer) const override; + Hash128 blake2b_128(common::BufferView data) const override; - Hash256 twox_256(gsl::span buffer) const override; + Hash256 twox_256(common::BufferView data) const override; - Hash256 blake2b_256(gsl::span buffer) const override; + Hash256 blake2b_256(common::BufferView data) const override; - Hash256 keccak_256(gsl::span buffer) const override; + Hash256 keccak_256(common::BufferView data) const override; - Hash256 blake2s_256(gsl::span buffer) const override; + Hash256 blake2s_256(common::BufferView data) const override; - Hash256 sha2_256(gsl::span buffer) const override; + Hash256 sha2_256(common::BufferView data) const override; - Hash512 blake2b_512(gsl::span buffer) const override; + Hash512 blake2b_512(common::BufferView data) const override; }; } // namespace kagome::crypto diff --git a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp index 788e104633..bc61b4fee7 100644 --- a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp +++ b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp @@ -11,8 +11,8 @@ namespace kagome::crypto { outcome::result Pbkdf2ProviderImpl::deriveKey( - gsl::span data, - gsl::span salt, + std::span data, + std::span salt, size_t iterations, size_t key_length) const { common::Buffer out(key_length, 0); diff --git a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp index e60907782d..e2dc10faf0 100644 --- a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp +++ b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp @@ -14,8 +14,8 @@ namespace kagome::crypto { public: ~Pbkdf2ProviderImpl() override = default; - outcome::result deriveKey(gsl::span data, - gsl::span salt, + outcome::result deriveKey(std::span data, + std::span salt, size_t iterations, size_t key_length) const override; }; diff --git a/core/crypto/pbkdf2/pbkdf2_provider.hpp b/core/crypto/pbkdf2/pbkdf2_provider.hpp index cf7484cf18..eb96600645 100644 --- a/core/crypto/pbkdf2/pbkdf2_provider.hpp +++ b/core/crypto/pbkdf2/pbkdf2_provider.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include #include "common/buffer.hpp" #include "outcome/outcome.hpp" @@ -30,8 +30,8 @@ namespace kagome::crypto { * @return derived key */ virtual outcome::result deriveKey( - gsl::span data, - gsl::span salt, + std::span data, + std::span salt, size_t iterations, size_t key_length) const = 0; }; diff --git a/core/crypto/sha/sha256.cpp b/core/crypto/sha/sha256.cpp index 920931be3a..fd6e3665e7 100644 --- a/core/crypto/sha/sha256.cpp +++ b/core/crypto/sha/sha256.cpp @@ -12,10 +12,10 @@ namespace kagome::crypto { common::Hash256 sha256(std::string_view input) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const auto *bytes_ptr = reinterpret_cast(input.data()); - return sha256(gsl::make_span(bytes_ptr, input.length())); + return sha256(std::span(bytes_ptr, input.length())); } - common::Hash256 sha256(gsl::span input) { + common::Hash256 sha256(std::span input) { common::Hash256 out; SHA256_CTX ctx; SHA256_Init(&ctx); diff --git a/core/crypto/sha/sha256.hpp b/core/crypto/sha/sha256.hpp index f45717f3cf..1e077a675a 100644 --- a/core/crypto/sha/sha256.hpp +++ b/core/crypto/sha/sha256.hpp @@ -8,7 +8,7 @@ #include -#include +#include #include "common/blob.hpp" namespace kagome::crypto { @@ -24,5 +24,5 @@ namespace kagome::crypto { * @param input to be hashed * @return hashed bytes */ - common::Hash256 sha256(gsl::span input); + common::Hash256 sha256(std::span input); } // namespace kagome::crypto diff --git a/core/crypto/sr25519/sr25519_provider_impl.cpp b/core/crypto/sr25519/sr25519_provider_impl.cpp index 32ceb578f0..c89eb80b08 100644 --- a/core/crypto/sr25519/sr25519_provider_impl.cpp +++ b/core/crypto/sr25519/sr25519_provider_impl.cpp @@ -33,7 +33,7 @@ namespace kagome::crypto { } outcome::result Sr25519ProviderImpl::sign( - const Sr25519Keypair &keypair, gsl::span message) const { + const Sr25519Keypair &keypair, std::span message) const { Sr25519Signature signature{}; try { @@ -51,7 +51,7 @@ namespace kagome::crypto { outcome::result Sr25519ProviderImpl::verify_deprecated( const Sr25519Signature &signature, - gsl::span message, + std::span message, const Sr25519PublicKey &public_key) const { bool result = false; try { @@ -65,7 +65,7 @@ namespace kagome::crypto { outcome::result Sr25519ProviderImpl::verify( const Sr25519Signature &signature, - gsl::span message, + std::span message, const Sr25519PublicKey &public_key) const { bool result = false; try { diff --git a/core/crypto/sr25519/sr25519_provider_impl.hpp b/core/crypto/sr25519/sr25519_provider_impl.hpp index c6220fb6c2..272332801f 100644 --- a/core/crypto/sr25519/sr25519_provider_impl.hpp +++ b/core/crypto/sr25519/sr25519_provider_impl.hpp @@ -17,16 +17,16 @@ namespace kagome::crypto { outcome::result sign( const Sr25519Keypair &keypair, - gsl::span message) const override; + std::span message) const override; outcome::result verify_deprecated( const Sr25519Signature &signature, - gsl::span message, + std::span message, const Sr25519PublicKey &public_key) const override; outcome::result verify( const Sr25519Signature &signature, - gsl::span message, + std::span message, const Sr25519PublicKey &public_key) const override; }; diff --git a/core/crypto/sr25519_provider.hpp b/core/crypto/sr25519_provider.hpp index a93a912586..dab4768a63 100644 --- a/core/crypto/sr25519_provider.hpp +++ b/core/crypto/sr25519_provider.hpp @@ -23,7 +23,7 @@ namespace kagome::crypto { class Sr25519Provider { public: - using Junctions = gsl::span; + using Junctions = std::span; virtual ~Sr25519Provider() = default; @@ -43,7 +43,7 @@ namespace kagome::crypto { */ virtual outcome::result sign( const Sr25519Keypair &keypair, - gsl::span message) const = 0; + std::span message) const = 0; /** * Verifies that \param message was derived using \param public_key on @@ -51,12 +51,12 @@ namespace kagome::crypto { */ virtual outcome::result verify( const Sr25519Signature &signature, - gsl::span message, + std::span message, const Sr25519PublicKey &public_key) const = 0; virtual outcome::result verify_deprecated( const Sr25519Signature &signature, - gsl::span message, + std::span message, const Sr25519PublicKey &public_key) const = 0; }; } // namespace kagome::crypto diff --git a/core/crypto/sr25519_types.hpp b/core/crypto/sr25519_types.hpp index c80af14a33..2eb12d5d41 100644 --- a/core/crypto/sr25519_types.hpp +++ b/core/crypto/sr25519_types.hpp @@ -10,7 +10,7 @@ extern "C" { #include } #include -#include +#include #include "common/blob.hpp" #include "common/int_serialization.hpp" diff --git a/core/crypto/twox/twox.cpp b/core/crypto/twox/twox.cpp index dd14cedb46..f386390900 100644 --- a/core/crypto/twox/twox.cpp +++ b/core/crypto/twox/twox.cpp @@ -17,7 +17,7 @@ namespace kagome::crypto { ptr[0] = XXH64(in, len, 0); } - common::Hash64 make_twox64(gsl::span buf) { + common::Hash64 make_twox64(std::span buf) { common::Hash64 hash{}; make_twox64(buf.data(), buf.size(), hash.data()); return hash; @@ -32,7 +32,7 @@ namespace kagome::crypto { ptr[1] = XXH64(in, len, 1); } - common::Hash128 make_twox128(gsl::span buf) { + common::Hash128 make_twox128(std::span buf) { common::Hash128 hash{}; make_twox128(buf.data(), buf.size(), hash.data()); return hash; @@ -51,7 +51,7 @@ namespace kagome::crypto { ptr[3] = XXH64(in, len, 3); } - common::Hash256 make_twox256(gsl::span buf) { + common::Hash256 make_twox256(std::span buf) { common::Hash256 hash{}; make_twox256(buf.data(), buf.size(), hash.data()); return hash; diff --git a/core/crypto/twox/twox.hpp b/core/crypto/twox/twox.hpp index 3c943d8b7d..86f028ad51 100644 --- a/core/crypto/twox/twox.hpp +++ b/core/crypto/twox/twox.hpp @@ -12,10 +12,10 @@ namespace kagome::crypto { // TODO(warchant): PRE-357 refactor to span - common::Hash64 make_twox64(gsl::span buf); + common::Hash64 make_twox64(std::span buf); - common::Hash128 make_twox128(gsl::span buf); + common::Hash128 make_twox128(std::span buf); - common::Hash256 make_twox256(gsl::span buf); + common::Hash256 make_twox256(std::span buf); } // namespace kagome::crypto diff --git a/core/crypto/vrf/vrf_provider_impl.cpp b/core/crypto/vrf/vrf_provider_impl.cpp index 1a39f06b92..e0601be9b2 100644 --- a/core/crypto/vrf/vrf_provider_impl.cpp +++ b/core/crypto/vrf/vrf_provider_impl.cpp @@ -6,7 +6,7 @@ #include "crypto/vrf/vrf_provider_impl.hpp" -#include +#include #include "common/int_serialization.hpp" diff --git a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp index 5dc3af2460..6f475a939e 100644 --- a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp +++ b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp @@ -148,7 +148,7 @@ namespace kagome::dispute { for (size_t i = 0; i < disputes.size();) { auto batch_size = std::min(kVotesSelectionBatchSize, disputes.size() - i); - auto batch = gsl::span(&disputes[i], batch_size); + auto batch = std::span(&disputes[i], batch_size); i += batch_size; // Filter votes which are already onchain diff --git a/core/host_api/impl/child_storage_extension.cpp b/core/host_api/impl/child_storage_extension.cpp index 5ba72b9c51..b61f39657b 100644 --- a/core/host_api/impl/child_storage_extension.cpp +++ b/core/host_api/impl/child_storage_extension.cpp @@ -126,6 +126,7 @@ namespace kagome::host_api { key_buffer.toHex(), result.error()); } + // okay to throw, we want to end this runtime call with error return memory.storeBuffer( scale::encode( diff --git a/core/host_api/impl/crypto_extension.cpp b/core/host_api/impl/crypto_extension.cpp index f08d66d7fe..b442b7de2c 100644 --- a/core/host_api/impl/crypto_extension.cpp +++ b/core/host_api/impl/crypto_extension.cpp @@ -11,7 +11,7 @@ #include #include -#include +#include #include "crypto/crypto_store.hpp" #include "crypto/crypto_store/key_type.hpp" @@ -493,7 +493,7 @@ namespace kagome::host_api { // returned key shouldn't include the 0x04 prefix // specification says, that it should have 64 bytes, not 65 as with prefix // On success it contains the 64-byte recovered public key or an error type - auto truncated_span = gsl::span(public_key.value()).subspan(1, 64); + auto truncated_span = std::span(public_key.value()).subspan(1, 64); auto truncated_public_key = secp256k1::PublicKey::fromSpan(truncated_span).value(); SL_TRACE_FUNC_CALL(logger_, truncated_public_key, sig_buffer, msg_buffer); diff --git a/core/injector/application_injector.cpp b/core/injector/application_injector.cpp index 1215e95a00..55804073c4 100644 --- a/core/injector/application_injector.cpp +++ b/core/injector/application_injector.cpp @@ -280,7 +280,7 @@ namespace { const application::ChainSpec &chain_spec, std::chrono::seconds random_wak_interval) { libp2p::protocol::kademlia::Config kademlia_config; - kademlia_config.protocolId = "/" + chain_spec.protocolId() + "/kad", + kademlia_config.protocols = {"/" + chain_spec.protocolId() + "/kad"}, kademlia_config.maxBucketSize = 1000, kademlia_config.randomWalk = {.interval = random_wak_interval}; diff --git a/core/network/adapters/protobuf.hpp b/core/network/adapters/protobuf.hpp index f2e659893f..62941e9258 100644 --- a/core/network/adapters/protobuf.hpp +++ b/core/network/adapters/protobuf.hpp @@ -8,8 +8,8 @@ #include #include -#include #include +#include #include #include "network/adapters/adapter_errors.hpp" diff --git a/core/network/adapters/protobuf_block_request.hpp b/core/network/adapters/protobuf_block_request.hpp index 92da5d125d..6e65051a22 100644 --- a/core/network/adapters/protobuf_block_request.hpp +++ b/core/network/adapters/protobuf_block_request.hpp @@ -8,8 +8,8 @@ #include "network/adapters/protobuf.hpp" -#include #include +#include #include "common/visitor.hpp" #include "macro/endianness_utils.hpp" diff --git a/core/network/adapters/protobuf_block_response.hpp b/core/network/adapters/protobuf_block_response.hpp index 38b4e42a89..b1329e90ea 100644 --- a/core/network/adapters/protobuf_block_response.hpp +++ b/core/network/adapters/protobuf_block_response.hpp @@ -157,7 +157,7 @@ namespace kagome::network { if (const auto &buffer = std::forward(f)(); !buffer.empty()) { OUTCOME_TRY( decoded, - scale::decode(gsl::span( + scale::decode(std::span( reinterpret_cast(buffer.data()), // NOLINT buffer.size()))); return decoded; diff --git a/core/network/adapters/protobuf_state_request.hpp b/core/network/adapters/protobuf_state_request.hpp index c976ccc239..ab42c3bb66 100644 --- a/core/network/adapters/protobuf_state_request.hpp +++ b/core/network/adapters/protobuf_state_request.hpp @@ -8,8 +8,8 @@ #include "network/adapters/protobuf.hpp" -#include #include +#include #include "common/visitor.hpp" #include "macro/endianness_utils.hpp" diff --git a/core/network/adapters/uvar.hpp b/core/network/adapters/uvar.hpp index 74e8530b5c..eff53aab1b 100644 --- a/core/network/adapters/uvar.hpp +++ b/core/network/adapters/uvar.hpp @@ -8,8 +8,8 @@ #include #include -#include #include +#include #include #include "network/adapters/adapter_errors.hpp" diff --git a/core/network/helpers/message_read_writer.hpp b/core/network/helpers/message_read_writer.hpp index 145a9985d8..fa56e7105d 100644 --- a/core/network/helpers/message_read_writer.hpp +++ b/core/network/helpers/message_read_writer.hpp @@ -9,8 +9,8 @@ #include #include #include -#include #include +#include #include #include "outcome/outcome.hpp" diff --git a/core/network/helpers/protobuf_message_read_writer.hpp b/core/network/helpers/protobuf_message_read_writer.hpp index f1a2bdefd8..79e42314fd 100644 --- a/core/network/helpers/protobuf_message_read_writer.hpp +++ b/core/network/helpers/protobuf_message_read_writer.hpp @@ -80,7 +80,7 @@ namespace kagome::network { std::vector out; auto it = ProtobufRW::write(msg, out); - gsl::span data(it.base(), + std::span data(it.base(), out.size() - std::distance(out.begin(), it)); read_writer_->write(data, diff --git a/core/network/helpers/stream_proxy_base.hpp b/core/network/helpers/stream_proxy_base.hpp index 4eddf712aa..277a4bf895 100644 --- a/core/network/helpers/stream_proxy_base.hpp +++ b/core/network/helpers/stream_proxy_base.hpp @@ -19,12 +19,12 @@ namespace libp2p::connection { explicit StreamProxyBase(std::shared_ptr stream) : stream{std::move(stream)} {} - void read(gsl::span out, + void read(std::span out, size_t bytes, ReadCallbackFunc cb) override { stream->read(out, bytes, std::move(cb)); } - void readSome(gsl::span out, + void readSome(std::span out, size_t bytes, ReadCallbackFunc cb) override { stream->readSome(out, bytes, std::move(cb)); @@ -34,12 +34,12 @@ namespace libp2p::connection { stream->deferReadCallback(res, std::move(cb)); } - void write(gsl::span in, + void write(std::span in, size_t bytes, WriteCallbackFunc cb) override { stream->write(in, bytes, std::move(cb)); } - void writeSome(gsl::span in, + void writeSome(std::span in, size_t bytes, WriteCallbackFunc cb) override { stream->writeSome(in, bytes, std::move(cb)); diff --git a/core/network/helpers/stream_read_buffer.hpp b/core/network/helpers/stream_read_buffer.hpp index 06a571d8d1..ade3238ff4 100644 --- a/core/network/helpers/stream_read_buffer.hpp +++ b/core/network/helpers/stream_read_buffer.hpp @@ -36,7 +36,7 @@ namespace libp2p::connection { return end - begin; } - void read(gsl::span out, size_t n, ReadCallbackFunc cb) override { + void read(std::span out, size_t n, ReadCallbackFunc cb) override { libp2p::ambigousSize(out, n); libp2p::readReturnSize(shared_from_this(), out, std::move(cb)); } @@ -44,7 +44,7 @@ namespace libp2p::connection { /** * Read from buffer. */ - size_t readFromBuffer(gsl::span out) { + size_t readFromBuffer(std::span out) { // can't read more bytes than available auto n = std::min(gsl::narrow(out.size()), size()); BOOST_ASSERT(n != 0); @@ -55,7 +55,7 @@ namespace libp2p::connection { return n; } - void readSome(gsl::span out, + void readSome(std::span out, size_t n, ReadCallbackFunc cb) override { libp2p::ambigousSize(out, n); diff --git a/core/network/impl/protocols/propagate_transactions_protocol.cpp b/core/network/impl/protocols/propagate_transactions_protocol.cpp index 8a4082899e..6f786bc124 100644 --- a/core/network/impl/protocols/propagate_transactions_protocol.cpp +++ b/core/network/impl/protocols/propagate_transactions_protocol.cpp @@ -131,7 +131,7 @@ namespace kagome::network { } void PropagateTransactionsProtocol::propagateTransactions( - gsl::span txs) { + std::span txs) { SL_DEBUG( base_.logger(), "Propagate transactions : {} extrinsics", txs.size()); diff --git a/core/network/impl/protocols/propagate_transactions_protocol.hpp b/core/network/impl/protocols/propagate_transactions_protocol.hpp index 1789038002..4b76a9bd93 100644 --- a/core/network/impl/protocols/propagate_transactions_protocol.hpp +++ b/core/network/impl/protocols/propagate_transactions_protocol.hpp @@ -73,7 +73,7 @@ namespace kagome::network { std::function>)> &&cb) override; - void propagateTransactions(gsl::span txs); + void propagateTransactions(std::span txs); private: inline static const auto kPropagateTransactionsProtocolName = diff --git a/core/network/impl/state_protocol_observer_impl.cpp b/core/network/impl/state_protocol_observer_impl.cpp index 80df482c19..2a4fe28116 100644 --- a/core/network/impl/state_protocol_observer_impl.cpp +++ b/core/network/impl/state_protocol_observer_impl.cpp @@ -107,8 +107,7 @@ namespace kagome::network { return Error::INVALID_CHILD_ROOTHASH; } if (request.start.size() == 2 - and not boost::starts_with(request.start[0], - storage::kChildStoragePrefix)) { + and not request.start[0].startsWith(storage::kChildStoragePrefix)) { return Error::INVALID_CHILD_ROOTHASH; } OUTCOME_TRY(header, blocks_headers_->getBlockHeader(request.hash)); @@ -161,7 +160,7 @@ namespace kagome::network { size += entry.entries.back().key.size() + entry.entries.back().value.size(); // if key is child state storage hash iterate child storage keys - if (boost::starts_with(cursor->key().value(), child_prefix)) { + if (cursor->key()->startsWith(child_prefix)) { OUTCOME_TRY(hash, storage::trie::RootHash::fromSpan(*value_res.value())); OUTCOME_TRY(entry_res, @@ -234,7 +233,7 @@ namespace kagome::network { } auto key = cursor->key().value(); if (stack.size() == 1 - and boost::starts_with(key, storage::kChildStoragePrefix)) { + and key.startsWith(storage::kChildStoragePrefix)) { OUTCOME_TRY(root, common::Hash256::fromSpan(*value)); if (child_roots.emplace(root).second) { OUTCOME_TRY(batch, get_batch(root)); diff --git a/core/network/impl/transactions_transmitter_impl.cpp b/core/network/impl/transactions_transmitter_impl.cpp index b11031739d..7f25a494eb 100644 --- a/core/network/impl/transactions_transmitter_impl.cpp +++ b/core/network/impl/transactions_transmitter_impl.cpp @@ -15,7 +15,7 @@ namespace kagome::network { : router_(std::move(router)) {} void TransactionsTransmitterImpl::propagateTransactions( - gsl::span txs) { + std::span txs) { auto protocol = router_->getPropagateTransactionsProtocol(); BOOST_ASSERT_MSG(protocol, "Router did not provide propagate transactions protocol"); diff --git a/core/network/impl/transactions_transmitter_impl.hpp b/core/network/impl/transactions_transmitter_impl.hpp index 2a3f81d3b3..5bd7c6fdf0 100644 --- a/core/network/impl/transactions_transmitter_impl.hpp +++ b/core/network/impl/transactions_transmitter_impl.hpp @@ -16,7 +16,7 @@ namespace kagome::network { TransactionsTransmitterImpl(std::shared_ptr router); void propagateTransactions( - gsl::span txs) override; + std::span txs) override; private: std::shared_ptr router_; diff --git a/core/network/notifications/handshake.hpp b/core/network/notifications/handshake.hpp index 8704b07e01..f8106d1b50 100644 --- a/core/network/notifications/handshake.hpp +++ b/core/network/notifications/handshake.hpp @@ -17,7 +17,7 @@ namespace kagome::network::notifications { template void handshakeRaw(std::shared_ptr stream, std::shared_ptr frame_stream, - gsl::span handshake, + std::span handshake, OnHandhake on_handshake) { auto cb = [stream = std::move(stream), frame_stream, diff --git a/core/network/transactions_transmitter.hpp b/core/network/transactions_transmitter.hpp index 4670204279..c8fbc33cb6 100644 --- a/core/network/transactions_transmitter.hpp +++ b/core/network/transactions_transmitter.hpp @@ -23,6 +23,6 @@ namespace kagome::network { * @param txs - list of transaction to be sent */ virtual void propagateTransactions( - gsl::span txs) = 0; + std::span txs) = 0; }; } // namespace kagome::network diff --git a/core/network/types/own_peer_info.hpp b/core/network/types/own_peer_info.hpp index c796a9ccc3..0aee04578a 100644 --- a/core/network/types/own_peer_info.hpp +++ b/core/network/types/own_peer_info.hpp @@ -6,9 +6,9 @@ #pragma once -#include #include #include +#include #include "application/app_configuration.hpp" #include "crypto/crypto_store.hpp" diff --git a/core/parachain/pvf/pvf_impl.cpp b/core/parachain/pvf/pvf_impl.cpp index fac914d61f..4055f48a16 100644 --- a/core/parachain/pvf/pvf_impl.cpp +++ b/core/parachain/pvf/pvf_impl.cpp @@ -79,7 +79,7 @@ namespace kagome::parachain { }; struct DontProvideCode : runtime::RuntimeCodeProvider { - outcome::result> getCodeAt( + outcome::result getCodeAt( const storage::trie::RootHash &) const override { abort(); } diff --git a/core/parachain/validator/impl/parachain_observer_impl.cpp b/core/parachain/validator/impl/parachain_observer_impl.cpp index b136be77d4..b927721d4b 100644 --- a/core/parachain/validator/impl/parachain_observer_impl.cpp +++ b/core/parachain/validator/impl/parachain_observer_impl.cpp @@ -6,7 +6,7 @@ #include "parachain/validator/impl/parachain_observer_impl.hpp" -#include +#include #include "crypto/sr25519_provider.hpp" #include "network/common.hpp" @@ -150,7 +150,7 @@ namespace kagome::parachain { payload.insert(payload.end(), {'C', 'O', 'L', 'L'}); if (auto result = crypto_provider_->verify( - signature, gsl::span(payload), pubkey); + signature, std::span(payload), pubkey); !result) { logger_->warn("Received incorrect collation declaration from {}:{}", peer_id, diff --git a/core/parachain/validator/impl/parachain_processor.cpp b/core/parachain/validator/impl/parachain_processor.cpp index bb1a89a994..4148072397 100644 --- a/core/parachain/validator/impl/parachain_processor.cpp +++ b/core/parachain/validator/impl/parachain_processor.cpp @@ -7,7 +7,7 @@ #include "parachain/validator/parachain_processor.hpp" #include -#include +#include #include #include "crypto/hasher.hpp" diff --git a/core/primitives/authority.hpp b/core/primitives/authority.hpp index 96980492f5..88d004ad3b 100644 --- a/core/primitives/authority.hpp +++ b/core/primitives/authority.hpp @@ -64,22 +64,6 @@ namespace kagome::primitives { AuthoritySetId id{}; AuthorityList authorities; - - auto begin() { - return authorities.begin(); - } - - auto end() { - return authorities.end(); - } - - auto begin() const { - return authorities.cbegin(); - } - - auto end() const { - return authorities.cend(); - } }; } // namespace kagome::primitives diff --git a/core/primitives/block_header.hpp b/core/primitives/block_header.hpp index 3a0b00e9ac..35ab1b7766 100644 --- a/core/primitives/block_header.hpp +++ b/core/primitives/block_header.hpp @@ -66,7 +66,7 @@ namespace kagome::primitives { const BlockNumber &number; const storage::trie::RootHash &state_root; const common::Hash256 &extrinsics_root; - gsl::span digest; + std::span digest; BlockHeaderReflection(const BlockHeader &origin) : parent_hash(origin.parent_hash), diff --git a/core/primitives/event_types.hpp b/core/primitives/event_types.hpp index 30c87d9f91..63b64d9ed5 100644 --- a/core/primitives/event_types.hpp +++ b/core/primitives/event_types.hpp @@ -95,10 +95,10 @@ namespace kagome::primitives::events { INVALID }; - using Hash256Span = gsl::span; + using Hash256Span = std::span; struct BroadcastEventParams { - gsl::span peers; + std::span peers; }; struct InBlockEventParams { @@ -149,7 +149,7 @@ namespace kagome::primitives::events { } static ExtrinsicLifecycleEvent Broadcast( - SubscribedExtrinsicId id, gsl::span peers) { + SubscribedExtrinsicId id, std::span peers) { return ExtrinsicLifecycleEvent{ id, ExtrinsicEventType::BROADCAST, diff --git a/core/primitives/ss58_codec.cpp b/core/primitives/ss58_codec.cpp index 4f5a673a4e..e2d48af281 100644 --- a/core/primitives/ss58_codec.cpp +++ b/core/primitives/ss58_codec.cpp @@ -25,13 +25,12 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::primitives, Ss58Error, e) { namespace kagome::primitives { - static common::Buffer calculateChecksum(gsl::span ss58_address, + static common::Buffer calculateChecksum(std::span ss58_address, const crypto::Hasher &hasher) { constexpr auto PREFIX = "SS58PRE"; auto preimage = common::Buffer{}.put(PREFIX).put(ss58_address); auto checksum = hasher.blake2b_512(preimage); - return common::Buffer{ - gsl::make_span(checksum).subspan(0, kSs58ChecksumLength)}; + return common::Buffer{std::span(checksum).subspan(0, kSs58ChecksumLength)}; } outcome::result decodeSs58(std::string_view account_address, @@ -41,14 +40,15 @@ namespace kagome::primitives { OUTCOME_TRY(ss58_account_id, libp2p::multi::detail::decodeBase58(account_address)); - auto ss58_no_checksum = gsl::make_span( + auto ss58_no_checksum = std::span( ss58_account_id.data(), ss58_account_id.size() - kSs58ChecksumLength); - auto checksum = gsl::make_span( + auto checksum = std::span( ss58_account_id.data() + ss58_no_checksum.size(), kSs58ChecksumLength); auto calculated_checksum = calculateChecksum(ss58_no_checksum, hasher); - if (gsl::span(calculated_checksum) != checksum) { + if (common::BufferView(calculated_checksum) + != common::BufferView(checksum)) { return Ss58Error::INVALID_CHECKSUM; } diff --git a/core/primitives/ss58_codec.hpp b/core/primitives/ss58_codec.hpp index 0f3806b92c..3d5c6b88e0 100644 --- a/core/primitives/ss58_codec.hpp +++ b/core/primitives/ss58_codec.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include #include "outcome/outcome.hpp" #include "primitives/account.hpp" diff --git a/core/primitives/strobe.hpp b/core/primitives/strobe.hpp index 18bc3dfe87..d504bc9922 100644 --- a/core/primitives/strobe.hpp +++ b/core/primitives/strobe.hpp @@ -9,12 +9,12 @@ #include #include #include -#include #include #include #include +#include "common/buffer_view.hpp" #include "crypto/keccak/keccak.h" #include "primitives/math.hpp" @@ -226,12 +226,8 @@ namespace kagome::primitives { overwrite(data); } - auto data() { - return gsl::make_span(as(), count() + 3ull); - } - auto data() const { - return gsl::make_span(as(), count() + 3ull); + return std::span(as(), count() + 3ull); } }; diff --git a/core/runtime/binaryen/memory_impl.cpp b/core/runtime/binaryen/memory_impl.cpp index bb0b46c2b1..b1e7b5f616 100644 --- a/core/runtime/binaryen/memory_impl.cpp +++ b/core/runtime/binaryen/memory_impl.cpp @@ -118,16 +118,14 @@ namespace kagome::runtime::binaryen { } void MemoryImpl::storeBuffer(kagome::runtime::WasmPointer addr, - gsl::span value) { - BOOST_ASSERT( - (allocator_->checkAddress(addr, static_cast(value.size())))); + common::BufferView value) { + BOOST_ASSERT((allocator_->checkAddress(addr, value.size()))); memory_->set(addr, std::move(value)); } - WasmSpan MemoryImpl::storeBuffer(gsl::span value) { - const auto size = static_cast(value.size()); - BOOST_ASSERT(std::numeric_limits::max() > size); - auto wasm_pointer = allocate(size); + WasmSpan MemoryImpl::storeBuffer(common::BufferView value) { + BOOST_ASSERT(std::numeric_limits::max() > value.size()); + auto wasm_pointer = allocate(value.size()); if (wasm_pointer == 0) { return 0; } diff --git a/core/runtime/binaryen/memory_impl.hpp b/core/runtime/binaryen/memory_impl.hpp index 6694c15110..5a84e59f78 100644 --- a/core/runtime/binaryen/memory_impl.hpp +++ b/core/runtime/binaryen/memory_impl.hpp @@ -70,9 +70,9 @@ namespace kagome::runtime::binaryen { void store128(WasmPointer addr, const std::array &value) override; void storeBuffer(kagome::runtime::WasmPointer addr, - gsl::span value) override; + common::BufferView value) override; - WasmSpan storeBuffer(gsl::span value) override; + WasmSpan storeBuffer(common::BufferView value) override; void resize(WasmSize new_size) override { /** diff --git a/core/runtime/binaryen/module/module_factory_impl.cpp b/core/runtime/binaryen/module/module_factory_impl.cpp index 64610771b4..d7c240d18f 100644 --- a/core/runtime/binaryen/module/module_factory_impl.cpp +++ b/core/runtime/binaryen/module/module_factory_impl.cpp @@ -28,7 +28,7 @@ namespace kagome::runtime::binaryen { } outcome::result> ModuleFactoryImpl::make( - gsl::span code) const { + common::BufferView code) const { std::vector code_vec{code.begin(), code.end()}; OUTCOME_TRY(module, ModuleImpl::createFromCode( diff --git a/core/runtime/binaryen/module/module_factory_impl.hpp b/core/runtime/binaryen/module/module_factory_impl.hpp index b2df0c0cf9..523c853a2e 100644 --- a/core/runtime/binaryen/module/module_factory_impl.hpp +++ b/core/runtime/binaryen/module/module_factory_impl.hpp @@ -39,7 +39,7 @@ namespace kagome::runtime::binaryen { std::shared_ptr hasher); outcome::result> make( - gsl::span code) const override; + common::BufferView code) const override; private: std::shared_ptr env_factory_; diff --git a/core/runtime/binaryen/module/module_instance_impl.cpp b/core/runtime/binaryen/module/module_instance_impl.cpp index 07b7ad551c..0216f685b7 100644 --- a/core/runtime/binaryen/module/module_instance_impl.cpp +++ b/core/runtime/binaryen/module/module_instance_impl.cpp @@ -173,7 +173,7 @@ namespace kagome::runtime::binaryen { throw std::runtime_error("invalid offset when initializing memory"); } callback(offset, - gsl::span( + std::span( reinterpret_cast(segment.data.data()), segment.data.size())); } diff --git a/core/runtime/binaryen/runtime_external_interface.hpp b/core/runtime/binaryen/runtime_external_interface.hpp index a17a9bd252..0b0e2686c1 100644 --- a/core/runtime/binaryen/runtime_external_interface.hpp +++ b/core/runtime/binaryen/runtime_external_interface.hpp @@ -10,6 +10,7 @@ #include +#include "common/buffer_view.hpp" #include "log/logger.hpp" namespace kagome::host_api { @@ -63,7 +64,7 @@ namespace kagome::runtime::binaryen { return memory.size(); } auto getData() const { - return gsl::span(memory); + return std::span(memory); } template void set(size_t address, T value) { @@ -73,11 +74,8 @@ namespace kagome::runtime::binaryen { std::memcpy(&memory[address], &value, sizeof(T)); } } - template - void set(size_t address, gsl::span value) { - static_assert(std::is_trivially_copyable_v, - "T must be trivially copyable"); - std::memcpy(&memory[address], value.data(), sizeof(T) * value.size()); + void set(size_t address, common::BufferView value) { + std::memcpy(&memory[address], value.data(), value.size()); } template T get(size_t address) { @@ -93,8 +91,8 @@ namespace kagome::runtime::binaryen { template and std::is_trivial_v>> - gsl::span getBuffer(size_t address, size_t n) const { - return gsl::span((T *)&memory[address], n); + common::BufferView getBuffer(size_t address, size_t n) const { + return common::BufferView((T *)&memory[address], n); ; } } memory; diff --git a/core/runtime/common/constant_code_provider.cpp b/core/runtime/common/constant_code_provider.cpp index f70f1e62f0..9dece14d69 100644 --- a/core/runtime/common/constant_code_provider.cpp +++ b/core/runtime/common/constant_code_provider.cpp @@ -11,7 +11,7 @@ namespace kagome::runtime { ConstantCodeProvider::ConstantCodeProvider(common::Buffer code) : code_{std::move(code)} {} - outcome::result> ConstantCodeProvider::getCodeAt( + outcome::result ConstantCodeProvider::getCodeAt( const storage::trie::RootHash &) const { return code_; } diff --git a/core/runtime/common/constant_code_provider.hpp b/core/runtime/common/constant_code_provider.hpp index 45e29f87d5..5b436eeff1 100644 --- a/core/runtime/common/constant_code_provider.hpp +++ b/core/runtime/common/constant_code_provider.hpp @@ -17,7 +17,7 @@ namespace kagome::runtime { public: explicit ConstantCodeProvider(common::Buffer code); - outcome::result> getCodeAt( + outcome::result getCodeAt( const storage::trie::RootHash &at) const override; private: diff --git a/core/runtime/common/module_instance.cpp b/core/runtime/common/module_instance.cpp index 0b5fc8dd72..9439a0547d 100644 --- a/core/runtime/common/module_instance.cpp +++ b/core/runtime/common/module_instance.cpp @@ -69,7 +69,7 @@ namespace kagome::runtime { max_data_segment_end = std::max(max_data_segment_end, offset + segment.size()); }); - if (gsl::narrow(heap_base) < max_data_segment_end) { + if (static_cast(heap_base) < max_data_segment_end) { return ModuleInstance::Error::HEAP_BASE_TOO_LOW; } diff --git a/core/runtime/common/storage_code_provider.cpp b/core/runtime/common/storage_code_provider.cpp index 80ae4aa5d6..1d786517b1 100644 --- a/core/runtime/common/storage_code_provider.cpp +++ b/core/runtime/common/storage_code_provider.cpp @@ -31,7 +31,7 @@ namespace kagome::runtime { BOOST_ASSERT(runtime_upgrade_tracker_ != nullptr); } - outcome::result> StorageCodeProvider::getCodeAt( + outcome::result StorageCodeProvider::getCodeAt( const storage::trie::RootHash &state) const { std::unique_lock lock{mutex_}; if (last_state_root_ != state) { diff --git a/core/runtime/common/storage_code_provider.hpp b/core/runtime/common/storage_code_provider.hpp index fdb36dc51f..5d8095dc12 100644 --- a/core/runtime/common/storage_code_provider.hpp +++ b/core/runtime/common/storage_code_provider.hpp @@ -31,7 +31,7 @@ namespace kagome::runtime { std::shared_ptr code_substitutes, std::shared_ptr chain_spec); - outcome::result> getCodeAt( + outcome::result getCodeAt( const storage::trie::RootHash &state) const override; private: diff --git a/core/runtime/memory.hpp b/core/runtime/memory.hpp index 7f2fa89fb0..cdc315e142 100644 --- a/core/runtime/memory.hpp +++ b/core/runtime/memory.hpp @@ -8,10 +8,10 @@ #include -#include #include #include "common/buffer.hpp" +#include "common/buffer_view.hpp" #include "common/literals.hpp" #include "runtime/types.hpp" @@ -105,14 +105,13 @@ namespace kagome::runtime { virtual void store64(WasmPointer addr, int64_t value) = 0; virtual void store128(WasmPointer addr, const std::array &value) = 0; - virtual void storeBuffer(WasmPointer addr, - gsl::span value) = 0; + virtual void storeBuffer(WasmPointer addr, common::BufferView value) = 0; /** * @brief allocates buffer in memory and copies value into memory * @param value buffer to store * @return full wasm pointer to allocated buffer */ - virtual WasmSpan storeBuffer(gsl::span value) = 0; + virtual WasmSpan storeBuffer(common::BufferView value) = 0; }; } // namespace kagome::runtime diff --git a/core/runtime/module_factory.hpp b/core/runtime/module_factory.hpp index c92ec72271..5425d36378 100644 --- a/core/runtime/module_factory.hpp +++ b/core/runtime/module_factory.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include #include "outcome/outcome.hpp" #include "runtime/instance_environment.hpp" @@ -21,7 +21,7 @@ namespace kagome::runtime { virtual ~ModuleFactory() = default; virtual outcome::result> make( - gsl::span code) const = 0; + common::BufferView code) const = 0; }; } // namespace kagome::runtime diff --git a/core/runtime/module_instance.hpp b/core/runtime/module_instance.hpp index 7ae5ef12f9..6f45ea0024 100644 --- a/core/runtime/module_instance.hpp +++ b/core/runtime/module_instance.hpp @@ -55,7 +55,7 @@ namespace kagome::runtime { std::string_view name) const = 0; using SegmentOffset = size_t; - using SegmentData = gsl::span; + using SegmentData = std::span; using DataSegmentProcessor = std::function; virtual void forDataSegment(const DataSegmentProcessor &callback) const = 0; diff --git a/core/runtime/module_repository.hpp b/core/runtime/module_repository.hpp index b49e9a6e76..e76fb5b8b2 100644 --- a/core/runtime/module_repository.hpp +++ b/core/runtime/module_repository.hpp @@ -8,7 +8,7 @@ #include -#include +#include #include "host_api/host_api.hpp" #include "outcome/outcome.hpp" diff --git a/core/runtime/runtime_code_provider.hpp b/core/runtime/runtime_code_provider.hpp index ad6723cd5f..c3cde37a05 100644 --- a/core/runtime/runtime_code_provider.hpp +++ b/core/runtime/runtime_code_provider.hpp @@ -6,9 +6,10 @@ #pragma once -#include #include +#include +#include "common/buffer_view.hpp" #include "primitives/block_id.hpp" #include "storage/trie/types.hpp" @@ -20,7 +21,7 @@ namespace kagome::runtime { public: virtual ~RuntimeCodeProvider() = default; - virtual outcome::result> getCodeAt( + virtual outcome::result getCodeAt( const storage::trie::RootHash &state) const = 0; }; diff --git a/core/runtime/wavm/core_api_factory_impl.cpp b/core/runtime/wavm/core_api_factory_impl.cpp index 5a1cfca8d1..0a6ed94d38 100644 --- a/core/runtime/wavm/core_api_factory_impl.cpp +++ b/core/runtime/wavm/core_api_factory_impl.cpp @@ -31,7 +31,7 @@ namespace kagome::runtime::wavm { std::shared_ptr module_params, std::shared_ptr intrinsic_module, std::shared_ptr instance_env_factory, - gsl::span code, + std::span code, const common::Hash256 &code_hash, std::shared_ptr last_compiled_module) : instance_env_factory_{std::move(instance_env_factory)}, @@ -69,7 +69,7 @@ namespace kagome::runtime::wavm { std::shared_ptr compartment_; std::shared_ptr module_params_; std::shared_ptr intrinsic_module_; - gsl::span code_; + std::span code_; const common::Hash256 code_hash_; std::shared_ptr last_compiled_module_; }; @@ -107,17 +107,13 @@ namespace kagome::runtime::wavm { auto code_hash = hasher->sha2_256(runtime_code); auto ctx_factory = std::make_shared( - std::make_shared( - compartment_, - module_params_, - intrinsic_module_, - instance_env_factory_, - gsl::span{ - runtime_code.data(), - static_cast::index_type>( - runtime_code.size())}, - code_hash, - last_compiled_module_), + std::make_shared(compartment_, + module_params_, + intrinsic_module_, + instance_env_factory_, + runtime_code, + code_hash, + last_compiled_module_), block_header_repo_); auto executor = std::make_unique(ctx_factory, cache_); return std::make_unique( diff --git a/core/runtime/wavm/memory_impl.cpp b/core/runtime/wavm/memory_impl.cpp index d0b98ab61b..1b0f4711a4 100644 --- a/core/runtime/wavm/memory_impl.cpp +++ b/core/runtime/wavm/memory_impl.cpp @@ -101,11 +101,11 @@ namespace kagome::runtime::wavm { storeBuffer(addr, value); } void MemoryImpl::storeBuffer(kagome::runtime::WasmPointer addr, - gsl::span value) { + common::BufferView value) { storeArray(addr, value); } - WasmSpan MemoryImpl::storeBuffer(gsl::span value) { + WasmSpan MemoryImpl::storeBuffer(common::BufferView value) { auto wasm_pointer = allocate(value.size()); if (wasm_pointer == 0) { return 0; diff --git a/core/runtime/wavm/memory_impl.hpp b/core/runtime/wavm/memory_impl.hpp index 0c6336847a..ea3e77f4e0 100644 --- a/core/runtime/wavm/memory_impl.hpp +++ b/core/runtime/wavm/memory_impl.hpp @@ -8,8 +8,8 @@ #include "runtime/memory.hpp" -#include #include +#include #include "common/buffer.hpp" #include "common/literals.hpp" @@ -48,9 +48,9 @@ namespace kagome::runtime::wavm { template and std::is_trivial_v>> - gsl::span loadArray(WasmPointer addr, size_t num) const { + std::span loadArray(WasmPointer addr, size_t num) const { auto res = WAVM::Runtime::memoryArrayPtr(memory_, addr, num); - gsl::span buffer(res, num); + std::span buffer(res, num); SL_TRACE_FUNC_CALL(logger_, common::BufferView(buffer), static_cast(this), @@ -83,7 +83,7 @@ namespace kagome::runtime::wavm { } template >> - void storeArray(WasmPointer addr, gsl::span array) { + void storeArray(WasmPointer addr, std::span array) { SL_TRACE_VOID_FUNC_CALL(logger_, static_cast(this), addr, @@ -100,9 +100,9 @@ namespace kagome::runtime::wavm { void store64(WasmPointer addr, int64_t value) override; void store128(WasmPointer addr, const std::array &value) override; - void storeBuffer(WasmPointer addr, gsl::span value) override; + void storeBuffer(WasmPointer addr, common::BufferView value) override; - WasmSpan storeBuffer(gsl::span value) override; + WasmSpan storeBuffer(common::BufferView value) override; WasmSize size() const override { return WAVM::Runtime::getMemoryNumPages(memory_) * kMemoryPageSize; diff --git a/core/runtime/wavm/module.cpp b/core/runtime/wavm/module.cpp index 6f2ac01c5c..547f3decc0 100644 --- a/core/runtime/wavm/module.cpp +++ b/core/runtime/wavm/module.cpp @@ -26,7 +26,7 @@ namespace kagome::runtime::wavm { ModuleParams &module_params, std::shared_ptr intrinsic_module, std::shared_ptr env_factory, - gsl::span code, + std::span code, const common::Hash256 &code_hash) { std::shared_ptr module = nullptr; WAVM::WASM::LoadError loadError; diff --git a/core/runtime/wavm/module.hpp b/core/runtime/wavm/module.hpp index a0735fb49e..2a33f5de13 100644 --- a/core/runtime/wavm/module.hpp +++ b/core/runtime/wavm/module.hpp @@ -36,7 +36,7 @@ namespace kagome::runtime::wavm { ModuleParams &module_params, std::shared_ptr intrinsic_module, std::shared_ptr env_factory, - gsl::span code, + std::span code, const common::Hash256 &code_hash); outcome::result> instantiate() diff --git a/core/runtime/wavm/module_cache.cpp b/core/runtime/wavm/module_cache.cpp index 3fe02a3838..d41ff4a5a2 100644 --- a/core/runtime/wavm/module_cache.cpp +++ b/core/runtime/wavm/module_cache.cpp @@ -27,7 +27,7 @@ namespace kagome::runtime::wavm { WAVM::Uptr numWASMBytes, std::function()> &&compileThunk) { auto runtime_hash = - hasher_->twox_64(gsl::span(wasmBytes, numWASMBytes)).toHex(); + hasher_->twox_64(std::span(wasmBytes, numWASMBytes)).toHex(); auto filepath = cache_dir_ / runtime_hash; if (!exists(filepath) and !exists(cache_dir_) and !fs::createDirectoryRecursive(cache_dir_)) { diff --git a/core/runtime/wavm/module_factory_impl.cpp b/core/runtime/wavm/module_factory_impl.cpp index ce81899ef6..af8ab6350d 100644 --- a/core/runtime/wavm/module_factory_impl.cpp +++ b/core/runtime/wavm/module_factory_impl.cpp @@ -37,7 +37,7 @@ namespace kagome::runtime::wavm { } outcome::result> ModuleFactoryImpl::make( - gsl::span code) const { + common::BufferView code) const { return ModuleImpl::compileFrom(compartment_, *module_params_, intrinsic_module_, diff --git a/core/runtime/wavm/module_factory_impl.hpp b/core/runtime/wavm/module_factory_impl.hpp index 85f017d938..04934d0f2b 100644 --- a/core/runtime/wavm/module_factory_impl.hpp +++ b/core/runtime/wavm/module_factory_impl.hpp @@ -36,7 +36,7 @@ namespace kagome::runtime::wavm { std::shared_ptr hasher); outcome::result> make( - gsl::span code) const override; + common::BufferView code) const override; private: std::shared_ptr compartment_; diff --git a/core/storage/map_prefix/prefix.cpp b/core/storage/map_prefix/prefix.cpp index 4ad2ab0a22..09dd5d5ab9 100644 --- a/core/storage/map_prefix/prefix.cpp +++ b/core/storage/map_prefix/prefix.cpp @@ -51,7 +51,7 @@ namespace kagome::storage { bool MapPrefix::Cursor::isValid() const { if (cursor->isValid()) { - return boost::starts_with(*cursor->key(), map.prefix); + return cursor->key()->startsWith(map.prefix); } return false; } diff --git a/core/storage/rocksdb/rocksdb_util.hpp b/core/storage/rocksdb/rocksdb_util.hpp index af67e835e8..713124db9f 100644 --- a/core/storage/rocksdb/rocksdb_util.hpp +++ b/core/storage/rocksdb/rocksdb_util.hpp @@ -44,10 +44,10 @@ namespace kagome::storage { return rocksdb::Slice{ptr, n}; } - inline gsl::span make_span(const rocksdb::Slice &s) { + inline std::span make_span(const rocksdb::Slice &s) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const auto *ptr = reinterpret_cast(s.data()); - return gsl::make_span(ptr, s.size()); + return std::span(ptr, s.size()); } inline common::Buffer make_buffer(const rocksdb::Slice &s) { diff --git a/core/storage/trie/impl/topper_trie_batch_impl.cpp b/core/storage/trie/impl/topper_trie_batch_impl.cpp index f7f203fbb5..efddcb713b 100644 --- a/core/storage/trie/impl/topper_trie_batch_impl.cpp +++ b/core/storage/trie/impl/topper_trie_batch_impl.cpp @@ -118,7 +118,7 @@ namespace kagome::storage::trie { outcome::result> TopperTrieBatchImpl::clearPrefix( const BufferView &prefix, std::optional) { for (auto it = cache_.lower_bound(prefix); - it != cache_.end() && boost::starts_with(it->first, prefix); + it != cache_.end() && it->first.startsWith(prefix); ++it) { it->second = std::nullopt; } @@ -158,7 +158,7 @@ namespace kagome::storage::trie { bool TopperTrieBatchImpl::wasClearedByPrefix(const BufferView &key) const { for (const auto &prefix : cleared_prefixes_) { - if (boost::starts_with(key, prefix)) { + if (key.startsWith(prefix)) { return true; } } 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 288170ec5d..64841940a4 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp @@ -121,7 +121,7 @@ namespace kagome::storage::trie { } outcome::result PolkadotTrieCursorImpl::seekLowerBoundInternal( - const TrieNode ¤t, gsl::span sought_nibbles) { + const TrieNode ¤t, std::span sought_nibbles) { BOOST_ASSERT(isValid()); auto [sought_nibbles_mismatch, current_mismatch] = std::mismatch(sought_nibbles.begin(), 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 9273dd0c8c..219cdd5b29 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp @@ -68,7 +68,7 @@ namespace kagome::storage::trie { private: outcome::result seekLowerBoundInternal( - const TrieNode ¤t, gsl::span left_nibbles); + const TrieNode ¤t, std::span left_nibbles); outcome::result nextNodeWithValueInOuterTree(); outcome::result nextNodeWithValueInSubTree( const TrieNode &subtree_root); diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp index 7b5091e869..799b384933 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp @@ -409,8 +409,7 @@ namespace kagome::storage::trie { // if we are not replacing previous leaf, then add it as a // child to the new branch - if (static_cast(parent->getKeyNibbles().size()) - > key_nibbles.size()) { + if (parent->getKeyNibbles().size() > key_nibbles.size()) { parent->setKeyNibbles(parent->getKeyNibbles().subbuffer(length + 1)); br->children.at(parentKey[length]) = parent; } @@ -518,7 +517,7 @@ namespace kagome::storage::trie { if (current->getKeyNibbles() == nibbles or nibbles.empty()) { return current; } - if (nibbles.size() < static_cast(current->getKeyNibbles().size())) { + if (nibbles.size() < current->getKeyNibbles().size()) { return nullptr; } auto parent_as_branch = @@ -548,12 +547,11 @@ namespace kagome::storage::trie { } auto common_length = getCommonPrefixLength(parent->getKeyNibbles(), path); auto common_nibbles = - gsl::make_span(parent->getKeyNibbles().data(), common_length); + std::span(parent->getKeyNibbles().data(), common_length); // path is even less than the parent key (path is the prefix of the // parent key) if (path == common_nibbles - and path.size() - < static_cast(parent->getKeyNibbles().size())) { + and path.size() < parent->getKeyNibbles().size()) { return outcome::success(); } auto parent_as_branch = diff --git a/core/storage/trie/polkadot_trie/trie_node.hpp b/core/storage/trie/polkadot_trie/trie_node.hpp index d219550c24..39d1a863f2 100644 --- a/core/storage/trie/polkadot_trie/trie_node.hpp +++ b/core/storage/trie/polkadot_trie/trie_node.hpp @@ -40,7 +40,7 @@ namespace kagome::storage::trie { auto l = key.size() * 2; KeyNibbles res(common::Buffer(l, 0)); - for (ssize_t i = 0; i < key.size(); i++) { + for (size_t i = 0; i < key.size(); i++) { res[2 * i] = key[i] >> 4u; res[2 * i + 1] = key[i] & 0xfu; } diff --git a/core/storage/trie/serialization/buffer_stream.hpp b/core/storage/trie/serialization/buffer_stream.hpp index 0c831b4c9d..6f82546938 100644 --- a/core/storage/trie/serialization/buffer_stream.hpp +++ b/core/storage/trie/serialization/buffer_stream.hpp @@ -6,7 +6,7 @@ #pragma once -#include +#include #include "common/buffer.hpp" @@ -17,26 +17,29 @@ namespace kagome::storage::trie { * future, when one appears */ class BufferStream { - using index_type = gsl::span::index_type; + using index_type = std::span::size_type; public: - explicit BufferStream(gsl::span buf) : data_{buf} {} + explicit BufferStream(std::span buf) : data_{buf} {} bool hasMore(index_type num_bytes) const { return data_.size() >= num_bytes; } uint8_t next() { - auto byte = data_.at(0); + if (data_.empty()) { + throw std::out_of_range("Data is out"); + } + auto byte = data_[0]; data_ = data_.last(data_.size() - 1); return byte; } - gsl::span leftBytes() const { + std::span leftBytes() const { return data_; } private: - gsl::span data_; + std::span data_; }; } // namespace kagome::storage::trie diff --git a/core/transaction_pool/impl/transaction_pool_impl.cpp b/core/transaction_pool/impl/transaction_pool_impl.cpp index 6e5caf7f1c..9cdab4a2c5 100644 --- a/core/transaction_pool/impl/transaction_pool_impl.cpp +++ b/core/transaction_pool/impl/transaction_pool_impl.cpp @@ -118,7 +118,8 @@ namespace kagome::transaction_pool { OUTCOME_TRY(tx, constructTransaction(source, extrinsic, hash)); if (tx.should_propagate) { - tx_transmitter_->propagateTransactions(gsl::make_span(std::vector{tx})); + std::vector txs{tx}; + tx_transmitter_->propagateTransactions(txs); } OUTCOME_TRY( diff --git a/core/utils/block_info_key.hpp b/core/utils/block_info_key.hpp index 29e7d027ca..daceed1202 100644 --- a/core/utils/block_info_key.hpp +++ b/core/utils/block_info_key.hpp @@ -6,10 +6,10 @@ #pragma once -#include -#include #include +#include + #include "primitives/common.hpp" namespace kagome { @@ -26,7 +26,7 @@ namespace kagome { } static std::optional decode(common::BufferView key) { - if (libp2p::spanSize(key) != Key::size()) { + if (key.size() != Key::size()) { return std::nullopt; } primitives::BlockInfo info; diff --git a/core/utils/block_number_key.hpp b/core/utils/block_number_key.hpp index 8d9c16a795..f6a7f0cb3c 100644 --- a/core/utils/block_number_key.hpp +++ b/core/utils/block_number_key.hpp @@ -6,13 +6,14 @@ #pragma once -#include -#include #include +#include + #include "primitives/common.hpp" namespace kagome { + struct BlockNumberKey { using Key = common::Blob; @@ -24,10 +25,11 @@ namespace kagome { static std::optional decode( common::BufferView key) { - if (libp2p::spanSize(key) != Key::size()) { + if (key.size() != Key::size()) { return std::nullopt; } return boost::endian::load_big_u32(key.data()); } }; + } // namespace kagome diff --git a/core/utils/kagome_db_editor.cpp b/core/utils/kagome_db_editor.cpp index 32f3fddfc7..39e5b2eda7 100644 --- a/core/utils/kagome_db_editor.cpp +++ b/core/utils/kagome_db_editor.cpp @@ -17,7 +17,6 @@ #undef TRUE #undef FALSE -#include #include #include @@ -189,7 +188,7 @@ void child_storage_root_hashes(const std::unique_ptr &batch, auto res = cursor->seekUpperBound(child_prefix); if (res.has_value()) { auto key = cursor->key(); - while (key.has_value() && boost::starts_with(key.value(), child_prefix)) { + while (key.has_value() && key->startsWith(child_prefix)) { if (auto value_res = batch->tryGet(key.value()); value_res.has_value() && value_res.value().has_value()) { auto &value_opt = value_res.value(); diff --git a/core/utils/storage_explorer.cpp b/core/utils/storage_explorer.cpp index 89d939949a..c1928dbc62 100644 --- a/core/utils/storage_explorer.cpp +++ b/core/utils/storage_explorer.cpp @@ -31,7 +31,7 @@ using kagome::primitives::events::ChainSubscriptionEngine; using kagome::runtime::GrandpaApi; using kagome::storage::trie::TrieStorage; -using ArgumentList = gsl::span; +using ArgumentList = std::span; class CommandExecutionError : public std::runtime_error { public: @@ -66,7 +66,7 @@ class Command { } protected: - void assertArgumentCount(const ArgumentList &args, int min, int max) { + void assertArgumentCount(const ArgumentList &args, size_t min, size_t max) { if (args.size() < min or args.size() > max) { throw CommandExecutionError{ name, @@ -512,7 +512,7 @@ class SearchChainCommand : public Command { }; int storage_explorer_main(int argc, const char **argv) { - ArgumentList args{argv, argc}; + ArgumentList args(argv, argc); CommandParser parser; parser.addCommand(std::make_unique(parser)); @@ -524,7 +524,7 @@ int storage_explorer_main(int argc, const char **argv) { std::make_shared(logger); int kagome_args_start = -1; - for (int i = 1; i < args.size(); i++) { + for (size_t i = 1; i < args.size(); i++) { if (strcmp(args[i], "--") == 0) { kagome_args_start = i; } diff --git a/test/core/api/service/author/author_api_test.cpp b/test/core/api/service/author/author_api_test.cpp index 0813a742d7..94bb1076fa 100644 --- a/test/core/api/service/author/author_api_test.cpp +++ b/test/core/api/service/author/author_api_test.cpp @@ -145,8 +145,8 @@ struct AuthorApiTest : public ::testing::Test { key_pair = generateSr25519Keypair(); ASSERT_OUTCOME_SUCCESS_TRY(key_store->saveKeyPair( KeyTypes::BABE, - gsl::make_span(key_pair.public_key.data(), 32), - gsl::make_span(std::array({1}).begin(), 1))); + std::span(key_pair.public_key.data(), 32), + std::span(std::array({1}).begin(), 1))); role.flags.authority = 1; EXPECT_CALL(*config, roles()).WillOnce(Return(role)); keys = std::make_shared(store, *config); @@ -267,8 +267,7 @@ TEST_F(AuthorApiTest, InsertKeyGran) { TEST_F(AuthorApiTest, HasSessionKeysEmpty) { Buffer keys; EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), false); } @@ -282,8 +281,7 @@ TEST_F(AuthorApiTest, HasSessionKeysLessThanOne) { Buffer keys; keys.resize(31); EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), false); } @@ -297,8 +295,7 @@ TEST_F(AuthorApiTest, HasSessionKeysOverload) { Buffer keys; keys.resize(32 * 6 + 1); EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), false); } @@ -312,8 +309,7 @@ TEST_F(AuthorApiTest, HasSessionKeysNotEqualKeys) { Buffer keys; keys.resize(32 * 5 + 1); EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), false); } @@ -347,8 +343,7 @@ TEST_F(AuthorApiTest, HasSessionKeysSuccess6Keys) { .Times(1) .WillOnce(Return(srOk)); EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), true); } @@ -365,8 +360,7 @@ TEST_F(AuthorApiTest, HasSessionKeysSuccess1Keys) { .Times(1) .WillOnce(Return(edOk)); EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), true); } @@ -385,8 +379,7 @@ TEST_F(AuthorApiTest, HasSessionKeysFailureNotFound) { .Times(1) .WillOnce(Return(srErr)); EXPECT_OUTCOME_SUCCESS( - res, - author_api->hasSessionKeys(gsl::make_span(keys.data(), keys.size()))); + res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); EXPECT_EQ(res.value(), false); } @@ -398,7 +391,7 @@ TEST_F(AuthorApiTest, HasSessionKeysFailureNotFound) { TEST_F(AuthorApiTest, HasKeySuccess) { EXPECT_OUTCOME_SUCCESS( res, - author_api->hasKey(gsl::make_span(key_pair.public_key.data(), 32), + author_api->hasKey(std::span(key_pair.public_key.data(), 32), KeyTypes::BABE)); EXPECT_EQ(res.value(), true); } diff --git a/test/core/api/service/child_state/child_state_api_test.cpp b/test/core/api/service/child_state/child_state_api_test.cpp index f17115c527..400929040d 100644 --- a/test/core/api/service/child_state/child_state_api_test.cpp +++ b/test/core/api/service/child_state/child_state_api_test.cpp @@ -236,13 +236,14 @@ namespace kagome::api { return batch; })); - ASSERT_EQ(expected_keys, - api_->getKeysPaged(child_storage_key, - prefix_opt, - keys_amount, - prev_key_opt, - block_hash_opt) - .value()); + auto actual_keys = api_->getKeysPaged(child_storage_key, + prefix_opt, + keys_amount, + prev_key_opt, + block_hash_opt) + .value(); + + ASSERT_EQ(expected_keys, actual_keys); } /** diff --git a/test/core/api/service/payment/payment_api_test.cpp b/test/core/api/service/payment/payment_api_test.cpp index 5968f70f7b..51b91dec38 100644 --- a/test/core/api/service/payment/payment_api_test.cpp +++ b/test/core/api/service/payment/payment_api_test.cpp @@ -95,7 +95,7 @@ TEST_F(PaymentApiTest, DecodeRuntimeDispatchInfo) { // partialFee: 15.7681 mDOT (157681946) // } TEST_F(PaymentApiTest, DecodeRuntimeDispatchInfoWithFee) { - gsl::span data{{ + std::span data{{ 0x42, 0xae, 0x2b, 0x22, 0x00, 0x00, 0x1a, 0x09, 0x66, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }}; diff --git a/test/core/api/service/state/state_jrpc_processor_test.cpp b/test/core/api/service/state/state_jrpc_processor_test.cpp index d68e6695f2..d3c763271b 100644 --- a/test/core/api/service/state/state_jrpc_processor_test.cpp +++ b/test/core/api/service/state/state_jrpc_processor_test.cpp @@ -27,7 +27,19 @@ using kagome::api::state::StateJrpcProcessor; using kagome::common::Buffer; using kagome::common::BufferView; using kagome::primitives::BlockHash; + using testing::_; +using testing::Invoke; +using testing::Return; +using testing::Truly; + +auto operator==(const std::span lhs, + const std::span rhs) noexcept { + return std::equal( + lhs.begin(), lhs.end(), rhs.begin(), [](const auto &le, const auto &re) { + return std::equal(le.begin(), le.end(), re.begin()); + }); +} class StateJrpcProcessorTest : public testing::Test { public: @@ -58,78 +70,78 @@ class StateJrpcProcessorTest : public testing::Test { void registerHandlers() { call_contexts_.clear(); EXPECT_CALL(*server, registerHandler("state_call", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair(CallType::kCallType_Call, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_getRuntimeVersion", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace( std::make_pair(CallType::kCallType_GetRuntimeVersion, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("chain_getRuntimeVersion", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace( std::make_pair(CallType::kCallType_SubscribeRuntimeVersion, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_subscribeRuntimeVersion", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace( std::make_pair(CallType::kCallType_SubscribeRuntimeVersion, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_unsubscribeRuntimeVersion", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace( std::make_pair(CallType::kCallType_UnsubscribeRuntimeVersion, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_getKeysPaged", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair( CallType::kCallType_GetKeysPaged, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_getStorage", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair(CallType::kCallType_GetStorage, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_getStorageAt", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair(CallType::kCallType_GetStorage, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_queryStorage", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair( CallType::kCallType_QueryStorage, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_queryStorageAt", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair( CallType::kCallType_QueryStorageAt, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_getReadProof", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair( CallType::kCallType_GetReadProof, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_subscribeStorage", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair( CallType::kCallType_StorageSubscribe, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_unsubscribeStorage", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace( std::make_pair(CallType::kCallType_StorageUnsubscribe, CallContext{.handler = f})); })); EXPECT_CALL(*server, registerHandler("state_getMetadata", _, _)) - .WillOnce(testing::Invoke([&](auto &name, auto &&f, bool) { + .WillOnce(Invoke([&](auto &name, auto &&f, bool) { call_contexts_.emplace(std::make_pair(CallType::kCallType_GetMetadata, CallContext{.handler = f})); })); @@ -155,7 +167,7 @@ TEST_F(StateJrpcProcessorTest, ProcessRequest) { auto expected_result = "ABCDEF"_hex2buf; auto key = "01234567"_hex2buf; EXPECT_CALL(*state_api, getStorage(key.view())) - .WillOnce(testing::Return(expected_result)); + .WillOnce(Return(expected_result)); registerHandlers(); @@ -175,7 +187,7 @@ TEST_F(StateJrpcProcessorTest, ProcessAnotherRequest) { auto key = "01234567"_hex2buf; EXPECT_CALL(*state_api, getStorageAt(key.view(), "010203"_hash256)) - .WillOnce(testing::Return(expected_result)); + .WillOnce(Return(expected_result)); registerHandlers(); @@ -199,11 +211,12 @@ TEST_F(StateJrpcProcessorTest, ProcessQueryStorage) { BlockHash from{"from"_hash256}; std::vector res{StateApi::StorageChangeSet{ from, {StateApi::StorageChangeSet::Change{"key1"_buf, "42"_buf}}}}; - EXPECT_CALL( - *state_api, - queryStorage( - gsl::span(keys), from, std::optional{})) - .WillOnce(testing::Return(outcome::success(res))); + auto if_keys = Truly([&](const auto &x) { + return std::equal(x.begin(), x.end(), keys.begin()); + }); + EXPECT_CALL(*state_api, + queryStorage(if_keys, from, std::optional{})) + .WillOnce(Return(outcome::success(res))); registerHandlers(); @@ -242,10 +255,11 @@ TEST_F(StateJrpcProcessorTest, ProcessQueryStorageAt) { BlockHash at{"at"_hash256}; std::vector res{StateApi::StorageChangeSet{ at, {StateApi::StorageChangeSet::Change{"key1"_buf, "42"_buf}}}}; - EXPECT_CALL( - *state_api, - queryStorageAt(gsl::span(keys), std::make_optional(at))) - .WillOnce(testing::Return(outcome::success(res))); + + auto if_keys = Truly( + [&](auto x) { return std::equal(x.begin(), x.end(), keys.begin()); }); + EXPECT_CALL(*state_api, queryStorageAt(if_keys, std::make_optional(at))) + .WillOnce(Return(outcome::success(res))); registerHandlers(); @@ -306,7 +320,7 @@ TEST_F(StateJrpcProcessorTest, ProcessGetVersionRequest) { std::optional hash = std::nullopt; EXPECT_CALL(*state_api, getRuntimeVersion(hash)) - .WillOnce(testing::Return(test_version)); + .WillOnce(Return(test_version)); registerHandlers(); @@ -333,8 +347,7 @@ TEST_F(StateJrpcProcessorTest, ProcessSubscribeStorage) { keys.emplace_back(kagome::common::unhexWith0x("0x1011").value()); keys.emplace_back(kagome::common::unhexWith0x("0x2002").value()); - EXPECT_CALL(*state_api, subscribeStorage(keys)) - .WillOnce(testing::Return(val)); + EXPECT_CALL(*state_api, subscribeStorage(keys)).WillOnce(Return(val)); registerHandlers(); @@ -359,7 +372,7 @@ TEST_F(StateJrpcProcessorTest, ProcessUnsubscribeStorage) { EXPECT_CALL(*state_api, unsubscribeStorage(std::vector{ static_cast(subscription_id)})) - .WillOnce(testing::Return(true)); + .WillOnce(Return(true)); registerHandlers(); diff --git a/test/core/api/service/system/system_api_test.cpp b/test/core/api/service/system/system_api_test.cpp index 56d785af3f..45b3d03024 100644 --- a/test/core/api/service/system/system_api_test.cpp +++ b/test/core/api/service/system/system_api_test.cpp @@ -91,7 +91,7 @@ TEST_F(SystemApiTest, GetNonceNoPendingTxs) { .WillOnce(Return(kInitialNonce)); auto hash_preimage = Buffer{}.put("SS58PRE").putUint8(42).put(kAccountId); EXPECT_CALL(*hasher_mock_, - blake2b_512(gsl::span(hash_preimage))) + blake2b_512(kagome::common::BufferView(hash_preimage))) .WillOnce(Return(kagome::common::Hash512{{'\035', '!'}})); EXPECT_CALL(*transaction_pool_mock_, getReadyTransactions()); @@ -115,7 +115,7 @@ TEST_F(SystemApiTest, GetNonceWithPendingTxs) { .WillOnce(Return(kInitialNonce)); auto hash_preimage = Buffer{}.put("SS58PRE").putUint8(42).put(kAccountId); EXPECT_CALL(*hasher_mock_, - blake2b_512(gsl::span(hash_preimage))) + blake2b_512(kagome::common::BufferView(hash_preimage))) .WillOnce(Return(kagome::common::Hash512{{'\035', '!'}})); constexpr auto kReadyTxNum = 5; diff --git a/test/core/common/buffer_view_test.cpp b/test/core/common/buffer_view_test.cpp index e2583f9c14..2e58cb44c4 100644 --- a/test/core/common/buffer_view_test.cpp +++ b/test/core/common/buffer_view_test.cpp @@ -9,7 +9,7 @@ #include using namespace kagome::common; -using Span = gsl::span; +using Span = std::span; TEST(BufferView, Constructor_default) { BufferView v; diff --git a/test/core/consensus/babe/babe_test.cpp b/test/core/consensus/babe/babe_test.cpp index 5b090051b3..645d26de55 100644 --- a/test/core/consensus/babe/babe_test.cpp +++ b/test/core/consensus/babe/babe_test.cpp @@ -164,13 +164,13 @@ class BabeTest : public testing::Test { hasher = std::make_shared(); static const auto d1 = scale::encode(genesis_block_header).value(); - ON_CALL(*hasher, blake2b_256(gsl::span(d1))) + ON_CALL(*hasher, blake2b_256(BufferView(d1))) .WillByDefault(Return(genesis_block_info.hash)); static const auto d2 = scale::encode(best_block_header).value(); - ON_CALL(*hasher, blake2b_256(gsl::span(d2))) + ON_CALL(*hasher, blake2b_256(BufferView(d2))) .WillByDefault(Return(best_block_info.hash)); static const auto d3 = scale::encode(new_block_header).value(); - ON_CALL(*hasher, blake2b_256(gsl::span(d3))) + ON_CALL(*hasher, blake2b_256(BufferView(d3))) .WillByDefault(Return(new_block_info.hash)); sr25519_provider = std::make_shared(); diff --git a/test/core/consensus/grandpa/authority_manager_test.cpp b/test/core/consensus/grandpa/authority_manager_test.cpp index e025dc2ee8..9d63612838 100644 --- a/test/core/consensus/grandpa/authority_manager_test.cpp +++ b/test/core/consensus/grandpa/authority_manager_test.cpp @@ -223,7 +223,7 @@ class AuthorityManagerTest : public testing::Test { auto encoded_header = encoded_headers.emplace(block.hash, scale::encode(header).value()) .first->second; - EXPECT_CALL(*hasher, blake2b_256(gsl::span(encoded_header))) + EXPECT_CALL(*hasher, blake2b_256(common::BufferView(encoded_header))) .WillRepeatedly(Return(block.hash)); chain_events_engine->notify( primitives::events::ChainEventType::kFinalizedHeads, header); @@ -506,7 +506,7 @@ TEST_F(AuthorityManagerTest, OnConsensus_OnPause) { primitives::Pause(delay))); primitives::AuthoritySet new_authorities = old_authorities; - for (auto &authority : new_authorities) { + for (auto &authority : new_authorities.authorities) { authority.weight = 0; } @@ -538,7 +538,7 @@ TEST_F(AuthorityManagerTest, OnConsensus_OnResume) { auto &enabled_authorities = *old_auth_opt.value(); primitives::AuthoritySet disabled_authorities = enabled_authorities; - for (auto &authority : disabled_authorities) { + for (auto &authority : disabled_authorities.authorities) { authority.weight = 0; } diff --git a/test/core/crypto/ecdsa/ecdsa_provider_test.cpp b/test/core/crypto/ecdsa/ecdsa_provider_test.cpp index 355368bf45..3b60614cb3 100644 --- a/test/core/crypto/ecdsa/ecdsa_provider_test.cpp +++ b/test/core/crypto/ecdsa/ecdsa_provider_test.cpp @@ -6,7 +6,7 @@ #include -#include +#include #include "crypto/bip39/impl/bip39_provider_impl.hpp" #include "crypto/ecdsa/ecdsa_provider_impl.hpp" diff --git a/test/core/crypto/ed25519/ed25519_provider_test.cpp b/test/core/crypto/ed25519/ed25519_provider_test.cpp index 5e83cf3ce1..b9af6e7409 100644 --- a/test/core/crypto/ed25519/ed25519_provider_test.cpp +++ b/test/core/crypto/ed25519/ed25519_provider_test.cpp @@ -6,7 +6,7 @@ #include -#include +#include #include "crypto/bip39/impl/bip39_provider_impl.hpp" #include "crypto/ed25519/ed25519_provider_impl.hpp" @@ -53,7 +53,7 @@ struct Ed25519ProviderTest : public ::testing::Test { std::string_view hex_seed; std::string_view hex_public_key; - gsl::span message_span; + std::span message_span; std::vector message; std::shared_ptr csprng = std::make_shared(); diff --git a/test/core/crypto/hasher/hasher_test.cpp b/test/core/crypto/hasher/hasher_test.cpp index 22dfee428e..c560abef2e 100644 --- a/test/core/crypto/hasher/hasher_test.cpp +++ b/test/core/crypto/hasher/hasher_test.cpp @@ -29,7 +29,7 @@ class HasherFixture : public testing::Test { template static Buffer blob2buffer(const kagome::common::Blob &blob) noexcept { Buffer out; - out.put({blob.data(), static_cast(blob.size())}); + out.put(blob); return out; } diff --git a/test/core/crypto/sr25519/sr25519_provider_test.cpp b/test/core/crypto/sr25519/sr25519_provider_test.cpp index f72fde8f11..0051915a8f 100644 --- a/test/core/crypto/sr25519/sr25519_provider_test.cpp +++ b/test/core/crypto/sr25519/sr25519_provider_test.cpp @@ -7,7 +7,7 @@ #include "crypto/sr25519/sr25519_provider_impl.hpp" #include -#include +#include #include "crypto/bip39/impl/bip39_provider_impl.hpp" #include "crypto/hasher/hasher_impl.hpp" @@ -59,7 +59,7 @@ struct Sr25519ProviderTest : public ::testing::Test { std::string_view hex_sk; std::string_view hex_vk; - gsl::span message_span; + std::span message_span; std::vector message; std::shared_ptr random_generator; std::shared_ptr sr25519_provider; diff --git a/test/core/host_api/CMakeLists.txt b/test/core/host_api/CMakeLists.txt index 6c385dce39..ada2280b68 100644 --- a/test/core/host_api/CMakeLists.txt +++ b/test/core/host_api/CMakeLists.txt @@ -25,6 +25,7 @@ addtest(memory_extension_test target_link_libraries(memory_extension_test memory_extension logger_for_tests + hexutil ) addtest(misc_extension_test diff --git a/test/core/host_api/child_storage_extension_test.cpp b/test/core/host_api/child_storage_extension_test.cpp index 448d4a2857..f354e67159 100644 --- a/test/core/host_api/child_storage_extension_test.cpp +++ b/test/core/host_api/child_storage_extension_test.cpp @@ -27,6 +27,7 @@ #include "testutil/prepare_loggers.hpp" using kagome::common::Buffer; +using kagome::common::BufferView; using kagome::host_api::ChildStorageExtension; using kagome::runtime::Memory; using kagome::runtime::MemoryMock; @@ -143,13 +144,14 @@ TEST_P(ReadOutcomeParameterizedTest, GetTest) { }, std::runtime_error); } else { - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(encoded_opt_value))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(encoded_opt_value))) .WillOnce(Return(value_span)); - ASSERT_EQ(value_span, - child_storage_extension_->ext_default_child_storage_get_version_1( - child_storage_key_span, key_span)); + auto actual = + child_storage_extension_->ext_default_child_storage_get_version_1( + child_storage_key_span, key_span); + + ASSERT_EQ(value_span, actual); } } @@ -197,9 +199,8 @@ TEST_P(ReadOutcomeParameterizedTest, ReadTest) { encoded_opt_offset_val_size, scale::encode(std::make_optional(offset_value_data.size()))); encoded_result = encoded_opt_offset_val_size; - EXPECT_CALL( - *memory_, - storeBuffer(value_pointer, gsl::span(offset_value_data))) + EXPECT_CALL(*memory_, + storeBuffer(value_pointer, BufferView(offset_value_data))) .WillOnce(Return()); } @@ -219,7 +220,7 @@ TEST_P(ReadOutcomeParameterizedTest, ReadTest) { std::runtime_error); } else { WasmSpan res_wasm_span = 1337; - EXPECT_CALL(*memory_, storeBuffer(gsl::span(encoded_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(encoded_result))) .WillOnce(Return(res_wasm_span)); ASSERT_EQ( @@ -423,7 +424,7 @@ TEST_F(ChildStorageExtensionTest, RootTest) { PtrSize(new_child_root_ptr, new_child_root_size).combine(); EXPECT_CALL(*trie_child_storage_batch_, commit(_)) .WillOnce(Return(new_child_root)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(new_child_root))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(new_child_root))) .WillOnce(Return(new_child_root_span)); ASSERT_EQ(new_child_root_span, diff --git a/test/core/host_api/crypto_extension_test.cpp b/test/core/host_api/crypto_extension_test.cpp index ac858916e7..c1f5c928b5 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" @@ -30,6 +30,7 @@ using namespace kagome::host_api; using kagome::common::Blob; using kagome::common::Buffer; +using kagome::common::BufferView; using kagome::crypto::BoostRandomGenerator; using kagome::crypto::CryptoStore; using kagome::crypto::CryptoStoreImpl; @@ -129,7 +130,7 @@ class CryptoExtensionTest : public ::testing::Test { std::copy_n(seed_tmp.begin(), Blob<32>::size(), seed.begin()); // scale-encoded string - std::optional> optional_seed(seed); + std::optional> optional_seed(seed); seed_buffer.put(scale::encode(optional_seed).value()); std::optional optional_mnemonic(mnemonic); mnemonic_buffer.put(scale::encode(optional_mnemonic).value()); @@ -151,10 +152,9 @@ class CryptoExtensionTest : public ::testing::Test { .value(); // first byte contains 0x04 // and needs to be omitted in runtime api return value - secp_truncated_public_key = - secp256k1::PublicKey::fromSpan( - gsl::make_span(secp_public_key_bytes).subspan(1)) - .value(); + secp_truncated_public_key = secp256k1::PublicKey::fromSpan( + std::span(secp_public_key_bytes).subspan(1)) + .value(); secp_signature = secp256k1::RSVSignature::fromSpan(secp_signature_bytes).value(); @@ -298,8 +298,7 @@ TEST_F(CryptoExtensionTest, Blake2_128Valid) { WasmPointer out_ptr = 42; EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(blake2b_128_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(blake2b_128_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(out_ptr, @@ -319,8 +318,7 @@ TEST_F(CryptoExtensionTest, Blake2_256Valid) { WasmPointer out_ptr = 42; EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(blake2b_256_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(blake2b_256_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_blake2_256_version_1( @@ -339,7 +337,7 @@ TEST_F(CryptoExtensionTest, KeccakValid) { WasmPointer out_ptr = 42; EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(keccak_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(keccak_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(out_ptr, @@ -422,7 +420,7 @@ TEST_F(CryptoExtensionTest, Ed25519VerifyFailure) { * @then verification is successful */ TEST_F(CryptoExtensionTest, Sr25519VerifySuccess) { - auto pub_key = gsl::span(sr25519_keypair.public_key); + auto pub_key = std::span(sr25519_keypair.public_key); WasmPointer input_data = 0; WasmSize input_size = input.size(); WasmPointer sig_data_ptr = 42; @@ -448,7 +446,7 @@ TEST_F(CryptoExtensionTest, Sr25519VerifySuccess) { * @then verification fails */ TEST_F(CryptoExtensionTest, Sr25519VerifyFailure) { - auto pub_key = gsl::span(sr25519_keypair.public_key); + auto pub_key = std::span(sr25519_keypair.public_key); auto false_signature = Buffer(sr25519_signature); ++false_signature[0]; ++false_signature[1]; @@ -522,7 +520,7 @@ TEST_F(CryptoExtensionTest, Twox128) { EXPECT_CALL(*memory_, loadN(twox_input_data, twox_input_size)) .WillOnce(Return(twox_input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(twox128_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(twox128_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(out_ptr, @@ -542,7 +540,7 @@ TEST_F(CryptoExtensionTest, Twox256) { EXPECT_CALL(*memory_, loadN(twox_input_data, twox_input_size)) .WillOnce(Return(twox_input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(twox256_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(twox256_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(out_ptr, @@ -569,8 +567,7 @@ TEST_F(CryptoExtensionTest, Secp256k1RecoverUncompressedSuccess) { .WillOnce(Return(Buffer(msg_input))); EXPECT_CALL(*memory_, - storeBuffer(gsl::span( - scale_encoded_secp_truncated_public_key))) + storeBuffer(BufferView(scale_encoded_secp_truncated_public_key))) .WillOnce(Return(res)); auto ptrsize = @@ -599,9 +596,7 @@ TEST_F(CryptoExtensionTest, Secp256k1RecoverUncompressedFailure) { EXPECT_CALL(*memory_, loadN(msg, msg_input.size())) .WillOnce(Return(Buffer(msg_input))); - EXPECT_CALL( - *memory_, - storeBuffer(gsl::span(secp_invalid_signature_error))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(secp_invalid_signature_error))) .WillOnce(Return(res)); auto ptrsize = @@ -628,8 +623,7 @@ TEST_F(CryptoExtensionTest, Secp256k1RecoverCompressed) { .WillOnce(Return(Buffer(msg_input))); EXPECT_CALL(*memory_, - storeBuffer(gsl::span( - scale_encoded_secp_compressed_public_key))) + storeBuffer(BufferView(scale_encoded_secp_compressed_public_key))) .WillOnce(Return(res)); auto ptrsize = @@ -661,9 +655,7 @@ TEST_F(CryptoExtensionTest, Secp256k1RecoverCompressedFailure) { EXPECT_CALL(*memory_, loadN(msg, msg_input.size())) .WillOnce(Return(Buffer(msg_input))); - EXPECT_CALL( - *memory_, - storeBuffer(gsl::span(secp_invalid_signature_error))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(secp_invalid_signature_error))) .WillOnce(Return(res)); auto ptrsize = @@ -687,8 +679,7 @@ TEST_F(CryptoExtensionTest, Ed25519GetPublicKeysSuccess) { .WillOnce(Return(ed_public_keys)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(ed_public_keys_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(ed_public_keys_result))) .WillOnce(Return(res)); ASSERT_EQ(crypto_ext_->ext_crypto_ed25519_public_keys_version_1(key_type_ptr), @@ -710,8 +701,7 @@ TEST_F(CryptoExtensionTest, Sr25519GetPublicKeysSuccess) { .WillOnce(Return(sr_public_keys)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(sr_public_keys_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(sr_public_keys_result))) .WillOnce(Return(res)); ASSERT_EQ(crypto_ext_->ext_crypto_sr25519_public_keys_version_1(key_type_ptr), @@ -741,8 +731,7 @@ TEST_F(CryptoExtensionTest, Ed25519SignSuccess) { .WillOnce(Return(ed25519_keypair)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(ed25519_signature_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(ed25519_signature_result))) .WillOnce(Return(res)); ASSERT_EQ( crypto_ext_->ext_crypto_ed25519_sign_version_1(key_type_ptr, key, msg), @@ -775,8 +764,7 @@ TEST_F(CryptoExtensionTest, Ed25519SignFailure) { outcome::failure(kagome::crypto::CryptoStoreError::KEY_NOT_FOUND))); EXPECT_CALL(*memory_, - storeBuffer(gsl::span( - ed_sr_signature_failure_result_buffer))) + storeBuffer(BufferView(ed_sr_signature_failure_result_buffer))) .WillOnce(Return(res)); ASSERT_EQ( crypto_ext_->ext_crypto_ed25519_sign_version_1(key_type_ptr, key, msg), @@ -809,7 +797,7 @@ TEST_F(CryptoExtensionTest, Sr25519SignSuccess) { EXPECT_CALL( *memory_, storeBuffer(VerifySr25519Signature(sr25519_provider_, - gsl::span(input), + std::span(input), sr25519_keypair.public_key))) .WillOnce(Return(res)); @@ -844,8 +832,7 @@ TEST_F(CryptoExtensionTest, Sr25519SignFailure) { outcome::failure(kagome::crypto::CryptoStoreError::KEY_NOT_FOUND))); EXPECT_CALL(*memory_, - storeBuffer(gsl::span( - ed_sr_signature_failure_result_buffer))) + storeBuffer(BufferView(ed_sr_signature_failure_result_buffer))) .WillOnce(Return(res)); ASSERT_EQ( crypto_ext_->ext_crypto_sr25519_sign_version_1(key_type_ptr, key, msg), @@ -867,8 +854,7 @@ TEST_F(CryptoExtensionTest, Ed25519GenerateByHexSeedSuccess) { generateEd25519Keypair(key_type, std::string_view(mnemonic))) .WillOnce(Return(ed25519_keypair)); EXPECT_CALL(*memory_, loadN(3, 4)).WillOnce(Return(mnemonic_buffer)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(ed_public_key_buffer))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(ed_public_key_buffer))) .WillOnce(Return(res)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); ASSERT_EQ(res, @@ -888,8 +874,7 @@ TEST_F(CryptoExtensionTest, Ed25519GenerateByMnemonicSuccess) { auto seed_ptr = PtrSize(3, 4).combine(); EXPECT_CALL(*memory_, loadN(3, 4)).WillOnce(Return(mnemonic_buffer)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(ed_public_key_buffer))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(ed_public_key_buffer))) .WillOnce(Return(res)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); EXPECT_CALL(*crypto_store_, @@ -912,8 +897,7 @@ TEST_F(CryptoExtensionTest, Sr25519GenerateByHexSeedSuccess) { auto seed_ptr = PtrSize(3, 4).combine(); EXPECT_CALL(*memory_, loadN(3, 4)).WillOnce(Return(mnemonic_buffer)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(sr_public_key_buffer))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(sr_public_key_buffer))) .WillOnce(Return(res)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); @@ -937,8 +921,7 @@ TEST_F(CryptoExtensionTest, Sr25519GenerateByMnemonicSuccess) { auto seed_ptr = PtrSize(3, 4).combine(); EXPECT_CALL(*memory_, loadN(3, 4)).WillOnce(Return(mnemonic_buffer)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(sr_public_key_buffer))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(sr_public_key_buffer))) .WillOnce(Return(res)); EXPECT_CALL(*memory_, load32u(key_type_ptr)).WillOnce(Return(key_type)); EXPECT_CALL(*crypto_store_, @@ -961,7 +944,7 @@ TEST_F(CryptoExtensionTest, Keccac256Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(keccak_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(keccak_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_keccak_256_version_1(data_span), out_ptr); @@ -979,7 +962,7 @@ TEST_F(CryptoExtensionTest, Sha2_256Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(sha2_256_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(sha2_256_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_sha2_256_version_1(data_span), out_ptr); @@ -997,8 +980,7 @@ TEST_F(CryptoExtensionTest, Blake2_128Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(blake2b_128_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(blake2b_128_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_blake2_128_version_1(data_span), out_ptr); @@ -1016,8 +998,7 @@ TEST_F(CryptoExtensionTest, Blake2_256Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(input)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(blake2b_256_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(blake2b_256_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_blake2_256_version_1(data_span), out_ptr); @@ -1035,7 +1016,7 @@ TEST_F(CryptoExtensionTest, Twox_256Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(twox_input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(twox256_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(twox256_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_twox_256_version_1(data_span), out_ptr); @@ -1053,7 +1034,7 @@ TEST_F(CryptoExtensionTest, Twox_128Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(twox_input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(twox128_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(twox128_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_twox_128_version_1(data_span), out_ptr); @@ -1071,7 +1052,7 @@ TEST_F(CryptoExtensionTest, Twox_64Version1_Success) { WasmSpan data_span = PtrSize(data, size).combine(); EXPECT_CALL(*memory_, loadN(data, size)).WillOnce(Return(twox_input)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(twox64_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(twox64_result))) .WillOnce(Return(out_ptr)); ASSERT_EQ(crypto_ext_->ext_hashing_twox_64_version_1(data_span), out_ptr); diff --git a/test/core/host_api/misc_extension_test.cpp b/test/core/host_api/misc_extension_test.cpp index 2ebc8b73da..6ee45106d4 100644 --- a/test/core/host_api/misc_extension_test.cpp +++ b/test/core/host_api/misc_extension_test.cpp @@ -22,6 +22,7 @@ using kagome::blockchain::BlockHeaderRepositoryMock; using kagome::common::Buffer; +using kagome::common::BufferView; using kagome::crypto::HasherMock; using kagome::host_api::HostApiMock; using kagome::host_api::MiscExtension; @@ -104,7 +105,7 @@ TEST_F(MiscExtensionTest, CoreVersion) { using namespace std::placeholders; - EXPECT_CALL(*memory, storeBuffer(gsl::span(v1_enc))) + EXPECT_CALL(*memory, storeBuffer(BufferView(v1_enc))) .WillOnce(Return(res1.combine())); kagome::host_api::MiscExtension m{ 42, std::make_shared(), memory_provider, core_factory}; @@ -118,7 +119,7 @@ TEST_F(MiscExtensionTest, CoreVersion) { return core; })); - EXPECT_CALL(*memory, storeBuffer(gsl::span(v2_enc))) + EXPECT_CALL(*memory, storeBuffer(BufferView(v2_enc))) .WillOnce(Return(res2.combine())); kagome::host_api::MiscExtension m2( 34, std::make_shared(), memory_provider, core_factory); diff --git a/test/core/host_api/offchain_extension_test.cpp b/test/core/host_api/offchain_extension_test.cpp index c641695481..c328ca1865 100644 --- a/test/core/host_api/offchain_extension_test.cpp +++ b/test/core/host_api/offchain_extension_test.cpp @@ -229,7 +229,7 @@ TEST_F(OffchainExtensionTest, RandomSeed) { EXPECT_CALL(*offchain_worker_, timestamp()).WillOnce(Return(result)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_result = scale::decode(data).value(); return actual_result == result; }; @@ -333,7 +333,7 @@ TEST_P(TernaryParametrizedTest, LocalStorageGet) { .WillOnce(Return(result)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_result = scale::decode>(data).value(); return actual_result == result_opt; }; @@ -384,7 +384,7 @@ TEST_P(HttpMethodsParametrizedTest, HttpRequestStart) { .WillOnce(Return(result)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_result = scale::decode>(data).value(); return actual_result.isSuccess(); @@ -435,7 +435,7 @@ TEST_F(OffchainExtensionTest, HttpRequestAddHeader) { .WillOnce(Return(result)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_result = scale::decode>(data).value(); return actual_result.isSuccess(); @@ -476,13 +476,12 @@ TEST_F(OffchainExtensionTest, HttpRequestWriteBody) { EXPECT_CALL(*memory_, loadN(chunk_pointer, chunk_size)) .WillOnce(Return(chunk)); EXPECT_CALL(*memory_, loadN(deadline_pointer, deadline_size)) - .WillOnce( - Return(Buffer{gsl::make_span(scale::encode(deadline_opt).value())})); + .WillOnce(Return(Buffer{scale::encode(deadline_opt).value()})); EXPECT_CALL(*offchain_worker_, httpRequestWriteBody(id, chunk, deadline_opt)) .WillOnce(Return(result)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_result = scale::decode>(data).value(); return actual_result.isSuccess(); @@ -520,15 +519,14 @@ TEST_F(OffchainExtensionTest, HttpResponseWait) { WasmSpan return_span = 45; EXPECT_CALL(*memory_, loadN(ids_pointer, ids_size)) - .WillOnce(Return(Buffer{gsl::make_span(scale::encode(ids).value())})); + .WillOnce(Return(Buffer{scale::encode(ids).value()})); EXPECT_CALL(*memory_, loadN(deadline_pointer, deadline_size)) - .WillOnce( - Return(Buffer{gsl::make_span(scale::encode(deadline_opt).value())})); + .WillOnce(Return(Buffer{scale::encode(deadline_opt).value()})); EXPECT_CALL(*offchain_worker_, httpResponseWait(ids, deadline_opt)) .WillOnce(Return(result)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_result = scale::decode>(data).value(); return std::equal( actual_result.begin(), actual_result.end(), result.begin()); @@ -558,7 +556,7 @@ TEST_F(OffchainExtensionTest, HttpResponseHeaders) { .WillOnce(Return(headers)); { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_headers = scale::decode>>(data) .value(); @@ -591,10 +589,9 @@ TEST_P(HttpResultParametrizedTest, HttpResponseReadBody) { auto deadline_opt = std::make_optional(deadline); Result response(GetParam()); WasmSpan result = 44; - gsl::span dst_buf = gsl::make_span(dst); + auto dst_buf = BufferView(dst); EXPECT_CALL(*memory_, loadN(deadline_pointer, deadline_size)) - .WillOnce( - Return(Buffer{gsl::make_span(scale::encode(deadline_opt).value())})); + .WillOnce(Return(Buffer{scale::encode(deadline_opt).value()})); EXPECT_CALL(*offchain_worker_, httpResponseReadBody(request_id, dst, deadline_opt)) .WillOnce(Return(response)); @@ -603,7 +600,7 @@ TEST_P(HttpResultParametrizedTest, HttpResponseReadBody) { } { - auto matcher = [&](const gsl::span &data) { + auto matcher = [&](const std::span &data) { auto actual_response = scale::decode>(data).value(); return actual_response.isSuccess() == response.isSuccess(); @@ -640,7 +637,7 @@ TEST_F(OffchainExtensionTest, SetAuthNodes) { WasmSize nodes_pos_size = 43; std::vector nodes{Buffer("asd"_peerid.toVector())}; EXPECT_CALL(*memory_, loadN(nodes_pos_pointer, nodes_pos_size)) - .WillOnce(Return(Buffer{gsl::make_span(scale::encode(nodes).value())})); + .WillOnce(Return(Buffer{scale::encode(nodes).value()})); EXPECT_CALL(*offchain_worker_, setAuthorizedNodes(_, true)) .WillOnce(Return()); offchain_extension_->ext_offchain_set_authorized_nodes_version_1( diff --git a/test/core/host_api/storage_extension_test.cpp b/test/core/host_api/storage_extension_test.cpp index 2934935680..3ae2fe8463 100644 --- a/test/core/host_api/storage_extension_test.cpp +++ b/test/core/host_api/storage_extension_test.cpp @@ -313,12 +313,8 @@ TEST_P(OutcomeParameterizedTest, StorageReadTest) { .WillOnce(Return(trie_batch_)); EXPECT_CALL(*trie_batch_, tryGetMock(key_data.view())) .WillOnce(Return(value_data)); - EXPECT_CALL( - *memory_, - storeBuffer(value.ptr, gsl::span(offset_value_data))); - EXPECT_CALL( - *memory_, - storeBuffer(gsl::span(encoded_opt_offset_val_size))) + EXPECT_CALL(*memory_, storeBuffer(value.ptr, BufferView(offset_value_data))); + EXPECT_CALL(*memory_, storeBuffer(BufferView(encoded_opt_offset_val_size))) .WillOnce(Return(res_wasm_span)); ASSERT_EQ(res_wasm_span, @@ -447,13 +443,12 @@ TEST_P(BuffersParametrizedTest, Blake2_256_EnumeratedTrieRoot) { auto &[values, hash_array] = GetParam(); auto values_enc = scale::encode(values).value(); - using testing::_; PtrSize values_span{42, static_cast(values_enc.size())}; EXPECT_CALL(*memory_, loadN(values_span.ptr, values_span.size)) .WillOnce(Return(Buffer{values_enc})); WasmPointer result = 1984; - EXPECT_CALL(*memory_, storeBuffer(gsl::span(hash_array))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(hash_array))) .WillOnce(Return(result)); storage_extension_->ext_trie_blake2_256_ordered_root_version_1( @@ -470,7 +465,6 @@ TEST_P(BuffersParametrizedTest, Blake2_256_EnumeratedTrieRoot) { TEST_P(BuffersParametrizedTest, Blake2_256_OrderedTrieRootV1) { auto &[values, hash_array] = GetParam(); - using testing::_; WasmPointer values_ptr = 1; WasmSize values_size = 2; WasmSpan values_data = PtrSize(values_ptr, values_size).combine(); @@ -481,7 +475,7 @@ TEST_P(BuffersParametrizedTest, Blake2_256_OrderedTrieRootV1) { EXPECT_CALL(*memory_, loadN(values_ptr, values_size)) .WillOnce(Return(buffer)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(hash_array))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(hash_array))) .WillOnce(Return(result)); ASSERT_EQ(result, @@ -524,8 +518,7 @@ TEST_F(StorageExtensionTest, StorageGetV1Test) { // expect key and value were loaded EXPECT_CALL(*memory_, loadN(key_pointer, key_size)).WillOnce(Return(key)); - EXPECT_CALL(*memory_, - storeBuffer(gsl::span(encoded_opt_value))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(encoded_opt_value))) .WillOnce(Return(value_span)); // expect key-value pair was put to db @@ -610,7 +603,7 @@ TEST_F(StorageExtensionTest, ExtStorageClearPrefixV2Test) { WasmPointer result_pointer = 43; WasmSize result_size = 43; WasmSpan result_span = PtrSize(result_pointer, result_size).combine(); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(enc_result))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(enc_result))) .WillOnce(Return(result_span)); ASSERT_EQ(result_span, @@ -631,7 +624,7 @@ TEST_F(StorageExtensionTest, RootTest) { WasmSpan root_span = PtrSize(root_pointer, root_size).combine(); EXPECT_CALL(*storage_provider_, commit(_)) .WillOnce(Return(outcome::success(root_val))); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(root_val))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(root_val))) .WillOnce(Return(root_span)); ASSERT_EQ(root_span, storage_extension_->ext_storage_root_version_1()); @@ -660,7 +653,7 @@ TEST_F(StorageExtensionTest, Blake2_256_TrieRootV1) { EXPECT_CALL(*memory_, loadN(values_ptr, values_size)) .WillOnce(Return(buffer)); - EXPECT_CALL(*memory_, storeBuffer(gsl::span(hash_array))) + EXPECT_CALL(*memory_, storeBuffer(BufferView(hash_array))) .WillOnce(Return(result)); ASSERT_EQ(result, diff --git a/test/core/network/types/block_announce_test.cpp b/test/core/network/types/block_announce_test.cpp index 2ce7aedad4..361589ebf8 100644 --- a/test/core/network/types/block_announce_test.cpp +++ b/test/core/network/types/block_announce_test.cpp @@ -55,7 +55,7 @@ struct BlockAnnounceTest : public ::testing::Test { * @then decoded block announce matches initial one */ TEST_F(BlockAnnounceTest, EncodeSuccess) { - EXPECT_OUTCOME_TRUE(buffer, encode(block_announce)); - EXPECT_OUTCOME_TRUE(ba, decode(buffer)); + ASSERT_OUTCOME_SUCCESS(buffer, encode(block_announce)); + ASSERT_OUTCOME_SUCCESS(ba, decode(buffer)); ASSERT_EQ(block_announce, ba); } diff --git a/test/core/parachain/pvf_test.cpp b/test/core/parachain/pvf_test.cpp index 0ea442c84d..7005780285 100644 --- a/test/core/parachain/pvf_test.cpp +++ b/test/core/parachain/pvf_test.cpp @@ -95,7 +95,7 @@ class PvfTest : public testing::Test { } outcome::result> make_module_mock( - gsl::span code, const Hash256 &code_hash) { + std::span code, const Hash256 &code_hash) { auto module = std::make_shared(); auto instance = std::make_shared(); ON_CALL(*module, instantiate()).WillByDefault(Return(instance)); diff --git a/test/core/runtime/binaryen/CMakeLists.txt b/test/core/runtime/binaryen/CMakeLists.txt index 4b02c59772..c1f97c812f 100644 --- a/test/core/runtime/binaryen/CMakeLists.txt +++ b/test/core/runtime/binaryen/CMakeLists.txt @@ -96,4 +96,5 @@ target_link_libraries(binaryen_memory_test binaryen_wasm_memory binaryen_runtime_external_interface log_configurator + hexutil ) diff --git a/test/core/runtime/storage_code_provider_test.cpp b/test/core/runtime/storage_code_provider_test.cpp index 085bc62da9..2c564ba6b0 100644 --- a/test/core/runtime/storage_code_provider_test.cpp +++ b/test/core/runtime/storage_code_provider_test.cpp @@ -73,9 +73,7 @@ TEST_F(StorageCodeProviderTest, GetCodeWhenNoStorageUpdates) { wasm_provider->getCodeAt(first_state_root)); // then - ASSERT_EQ(obtained_state_code, - gsl::span(state_code_.data(), - state_code_.data() + state_code_.size())); + ASSERT_TRUE(obtained_state_code == std::span(state_code_)); } /** @@ -122,5 +120,5 @@ TEST_F(StorageCodeProviderTest, DISABLED_GetCodeWhenStorageUpdates) { wasm_provider->getCodeAt(second_state_root)); // then - ASSERT_EQ(obtained_state_code, gsl::span(state_code_)); + ASSERT_EQ(obtained_state_code, std::span(state_code_)); } diff --git a/test/mock/core/api/service/author/author_api_mock.hpp b/test/mock/core/api/service/author/author_api_mock.hpp index 5807a6fef8..b1cb2b3f1f 100644 --- a/test/mock/core/api/service/author/author_api_mock.hpp +++ b/test/mock/core/api/service/author/author_api_mock.hpp @@ -24,20 +24,20 @@ namespace kagome::api { MOCK_METHOD(outcome::result, insertKey, (crypto::KeyType, - const gsl::span &, - const gsl::span &), + const std::span &, + const std::span &), (override)); MOCK_METHOD(outcome::result, rotateKeys, (), (override)); MOCK_METHOD(outcome::result, hasSessionKeys, - (const gsl::span &), + (const std::span &), (override)); MOCK_METHOD(outcome::result, hasKey, - (const gsl::span &, crypto::KeyType), + (const std::span &, crypto::KeyType), (override)); MOCK_METHOD(outcome::result, diff --git a/test/mock/core/api/service/chain/chain_api_mock.hpp b/test/mock/core/api/service/chain/chain_api_mock.hpp index 80ee086ae6..140499a962 100644 --- a/test/mock/core/api/service/chain/chain_api_mock.hpp +++ b/test/mock/core/api/service/chain/chain_api_mock.hpp @@ -33,7 +33,7 @@ namespace kagome::api { MOCK_METHOD(outcome::result>, getBlockHash, - (gsl::span), + (std::span), (const, override)); MOCK_METHOD(outcome::result, diff --git a/test/mock/core/api/service/state/state_api_mock.hpp b/test/mock/core/api/service/state/state_api_mock.hpp index 5c8a72205f..6ac51eca35 100644 --- a/test/mock/core/api/service/state/state_api_mock.hpp +++ b/test/mock/core/api/service/state/state_api_mock.hpp @@ -35,36 +35,35 @@ namespace kagome::api { MOCK_METHOD(outcome::result>, getStorage, - (const common::BufferView &key), + (common::BufferView key), (const, override)); outcome::result> getStorage( - const common::Buffer &key) const { + common::Buffer key) const { return getStorage(common::BufferView{key}); } MOCK_METHOD(outcome::result>, getStorageAt, - (const common::BufferView &key, - const primitives::BlockHash &at), + (common::BufferView key, const primitives::BlockHash &at), (const, override)); MOCK_METHOD(outcome::result>, queryStorage, - (gsl::span keys, + (std::span keys, const primitives::BlockHash &from, std::optional to), (const, override)); MOCK_METHOD(outcome::result>, queryStorageAt, - (gsl::span keys, + (std::span keys, std::optional at), (const, override)); MOCK_METHOD(outcome::result, getReadProof, - (gsl::span keys, + (std::span keys, std::optional at), (const, override)); diff --git a/test/mock/core/crypto/ecdsa_provider_mock.hpp b/test/mock/core/crypto/ecdsa_provider_mock.hpp index 9846ff1233..49a0498e95 100644 --- a/test/mock/core/crypto/ecdsa_provider_mock.hpp +++ b/test/mock/core/crypto/ecdsa_provider_mock.hpp @@ -25,12 +25,12 @@ namespace kagome::crypto { MOCK_METHOD(outcome::result, sign, - (gsl::span, const EcdsaPrivateKey &), + (std::span, const EcdsaPrivateKey &), (const, override)); MOCK_METHOD(outcome::result, verify, - (gsl::span, + (std::span, const EcdsaSignature &, const EcdsaPublicKey &), (const, override)); diff --git a/test/mock/core/crypto/ed25519_provider_mock.hpp b/test/mock/core/crypto/ed25519_provider_mock.hpp index e23522f751..57ffcfd2c7 100644 --- a/test/mock/core/crypto/ed25519_provider_mock.hpp +++ b/test/mock/core/crypto/ed25519_provider_mock.hpp @@ -19,13 +19,13 @@ namespace kagome::crypto { MOCK_METHOD(outcome::result, sign, - (const Ed25519Keypair &, gsl::span), + (const Ed25519Keypair &, std::span), (const, override)); MOCK_METHOD(outcome::result, verify, (const Ed25519Signature &, - gsl::span, + std::span, const Ed25519PublicKey &), (const, override)); }; diff --git a/test/mock/core/crypto/hasher_mock.hpp b/test/mock/core/crypto/hasher_mock.hpp index a80516488b..bebd0ba68d 100644 --- a/test/mock/core/crypto/hasher_mock.hpp +++ b/test/mock/core/crypto/hasher_mock.hpp @@ -15,51 +15,24 @@ namespace kagome::crypto { public: ~HasherMock() override = default; - MOCK_METHOD(Hash64, twox_64, (gsl::span), (const, override)); + MOCK_METHOD(Hash64, twox_64, (common::BufferView), (const, override)); - MOCK_METHOD(Hash64, - blake2b_64, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash64, blake2b_64, (common::BufferView), (const, override)); - MOCK_METHOD(Hash128, - blake2b_128, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash128, blake2b_128, (common::BufferView), (const, override)); - MOCK_METHOD(Hash128, - twox_128, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash128, twox_128, (common::BufferView), (const, override)); - MOCK_METHOD(Hash256, - twox_256, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash256, twox_256, (common::BufferView), (const, override)); - MOCK_METHOD(Hash256, - blake2b_256, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash256, blake2b_256, (common::BufferView), (const, override)); - MOCK_METHOD(Hash256, - blake2s_256, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash256, blake2s_256, (common::BufferView), (const, override)); - MOCK_METHOD(Hash256, - keccak_256, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash256, keccak_256, (common::BufferView), (const, override)); - MOCK_METHOD(Hash256, - sha2_256, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash256, sha2_256, (common::BufferView), (const, override)); - MOCK_METHOD(Hash512, - blake2b_512, - (gsl::span), - (const, override)); + MOCK_METHOD(Hash512, blake2b_512, (common::BufferView), (const, override)); }; } // namespace kagome::crypto diff --git a/test/mock/core/crypto/sr25519_provider_mock.hpp b/test/mock/core/crypto/sr25519_provider_mock.hpp index a2e210918b..ec267c8cb0 100644 --- a/test/mock/core/crypto/sr25519_provider_mock.hpp +++ b/test/mock/core/crypto/sr25519_provider_mock.hpp @@ -18,20 +18,20 @@ namespace kagome::crypto { MOCK_METHOD(outcome::result, sign, - (const Sr25519Keypair &, gsl::span), + (const Sr25519Keypair &, std::span), (const, override)); MOCK_METHOD(outcome::result, verify, (const Sr25519Signature &, - gsl::span, + std::span, const Sr25519PublicKey &), (const, override)); MOCK_METHOD(outcome::result, verify_deprecated, (const Sr25519Signature &, - gsl::span, + std::span, const Sr25519PublicKey &), (const, override)); }; diff --git a/test/mock/core/network/transactions_transmitter_mock.hpp b/test/mock/core/network/transactions_transmitter_mock.hpp index 835b6274cf..b9a51993bb 100644 --- a/test/mock/core/network/transactions_transmitter_mock.hpp +++ b/test/mock/core/network/transactions_transmitter_mock.hpp @@ -16,7 +16,7 @@ namespace kagome::network { public: MOCK_METHOD(void, propagateTransactions, - (gsl::span), + (std::span), (override)); }; diff --git a/test/mock/core/runtime/memory_mock.hpp b/test/mock/core/runtime/memory_mock.hpp index cbc9395cfa..2b890378f8 100644 --- a/test/mock/core/runtime/memory_mock.hpp +++ b/test/mock/core/runtime/memory_mock.hpp @@ -72,10 +72,10 @@ namespace kagome::runtime { MOCK_METHOD(void, storeBuffer, - (WasmPointer, gsl::span), + (WasmPointer, common::BufferView), (override)); - MOCK_METHOD(WasmSpan, storeBuffer, (gsl::span), (override)); + MOCK_METHOD(WasmSpan, storeBuffer, (common::BufferView), (override)); }; } // namespace kagome::runtime diff --git a/test/mock/core/runtime/module_factory_mock.hpp b/test/mock/core/runtime/module_factory_mock.hpp index 708fd63ba1..66218fc91f 100644 --- a/test/mock/core/runtime/module_factory_mock.hpp +++ b/test/mock/core/runtime/module_factory_mock.hpp @@ -18,7 +18,7 @@ namespace kagome::runtime { public: MOCK_METHOD(outcome::result>, make, - (gsl::span), + (common::BufferView), (const, override)); }; } // namespace kagome::runtime diff --git a/test/mock/libp2p/basic/read_writer_mock.hpp b/test/mock/libp2p/basic/read_writer_mock.hpp index 5878e68c45..b056757a88 100644 --- a/test/mock/libp2p/basic/read_writer_mock.hpp +++ b/test/mock/libp2p/basic/read_writer_mock.hpp @@ -15,22 +15,22 @@ namespace libp2p::basic { struct ReadWriterMock : public ReadWriter { MOCK_METHOD(void, read, - (gsl::span, size_t, Reader::ReadCallbackFunc), + (std::span, size_t, Reader::ReadCallbackFunc), (override)); MOCK_METHOD(void, readSome, - (gsl::span, size_t, Reader::ReadCallbackFunc), + (std::span, size_t, Reader::ReadCallbackFunc), (override)); MOCK_METHOD(void, write, - (gsl::span, size_t, Writer::WriteCallbackFunc), + (std::span, size_t, Writer::WriteCallbackFunc), (override)); MOCK_METHOD(void, writeSome, - (gsl::span, size_t, Writer::WriteCallbackFunc), + (std::span, size_t, Writer::WriteCallbackFunc), (override)); MOCK_METHOD(void, diff --git a/test/testutil/runtime/common/basic_code_provider.cpp b/test/testutil/runtime/common/basic_code_provider.cpp index 8459786639..765ea4e515 100644 --- a/test/testutil/runtime/common/basic_code_provider.cpp +++ b/test/testutil/runtime/common/basic_code_provider.cpp @@ -15,13 +15,12 @@ namespace kagome::runtime { initialize(path); } - outcome::result> BasicCodeProvider::getCodeAt( + outcome::result BasicCodeProvider::getCodeAt( const storage::trie::RootHash &at) const { return buffer_; } void BasicCodeProvider::initialize(std::string_view path) { - common::Buffer buffer; if (not readFile(buffer_, std::string{path})) { throw std::runtime_error("File with test code " + std::string(path) + " not found"); diff --git a/test/testutil/runtime/common/basic_code_provider.hpp b/test/testutil/runtime/common/basic_code_provider.hpp index ff20f4b92b..2b747b3897 100644 --- a/test/testutil/runtime/common/basic_code_provider.hpp +++ b/test/testutil/runtime/common/basic_code_provider.hpp @@ -16,7 +16,7 @@ namespace kagome::runtime { ~BasicCodeProvider() override = default; - outcome::result> getCodeAt( + outcome::result getCodeAt( const storage::trie::RootHash &state) const override; private: From f208e0bf4336597e5c623ae30eed375182874d00 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Wed, 25 Oct 2023 21:24:06 +0300 Subject: [PATCH 02/12] refactor: gst to std Signed-off-by: Dmitriy Khaustov aka xDimon --- cmake/Hunter/config.cmake | 8 +-- cmake/dependencies.cmake | 4 -- core/api/service/mmr/rpc.cpp | 5 +- core/blockchain/impl/block_tree_impl.hpp | 3 +- core/common/final_action.hpp | 64 +++++++++++++++++++ core/common/int_serialization.cpp | 2 - core/consensus/grandpa/impl/grandpa_impl.cpp | 3 +- core/crypto/bip39/dictionary.cpp | 3 +- core/metrics/histogram_timer.hpp | 5 +- core/network/helpers/stream_read_buffer.hpp | 10 +-- core/network/impl/synchronizer_impl.cpp | 7 +- core/network/types/blocks_request.hpp | 1 - core/network/warp/cache.cpp | 3 +- core/network/warp/sync.cpp | 3 +- core/offchain/impl/offchain_worker_impl.cpp | 10 +-- core/offchain/impl/runner.hpp | 4 +- core/parachain/pvf/precheck.cpp | 5 +- .../validator/impl/parachain_processor.cpp | 4 +- core/primitives/transcript.hpp | 4 +- .../runtime_api/impl/block_builder.cpp | 5 +- core/runtime/wavm/module_instance.cpp | 3 +- test/core/consensus/babe/babe_test.cpp | 1 + 22 files changed, 113 insertions(+), 44 deletions(-) create mode 100644 core/common/final_action.hpp diff --git a/cmake/Hunter/config.cmake b/cmake/Hunter/config.cmake index e9dd52012e..88a0324633 100644 --- a/cmake/Hunter/config.cmake +++ b/cmake/Hunter/config.cmake @@ -45,8 +45,8 @@ hunter_config( #) hunter_config( libp2p - URL https://github.com/libp2p/cpp-libp2p/archive/a688ddfcf2a2a3a069e7cc7a74e9f07b900bc095.tar.gz - SHA1 8e0aeb3d54c4be3b1fb834c4be387645bbd4aecb + URL https://github.com/libp2p/cpp-libp2p/archive/b581ee763c893feb84ebeea4f03e8d3667fbbaf4.tar.gz + SHA1 6be0e175200e13decfe4395bcda5ff311c6c9e5b ) hunter_config( @@ -71,8 +71,8 @@ hunter_config( hunter_config( scale - URL https://github.com/qdrvm/scale-codec-cpp/archive/fc06c2f1c8f56ced279134703ced187da645f737.tar.gz - SHA1 9c0362aa6a5f1dcc9ff5e56c4220f4aef15e2eb9 + URL https://github.com/qdrvm/scale-codec-cpp/archive/2a223956d9cc0c78a95848da2fd1be35b2a4bd2d.tar.gz + SHA1 12879475cc5a00f23ad9e660ee8ecbd74b6e16a0 ) # Fix for Apple clang (or clang from brew) of versions 15 and higher diff --git a/cmake/dependencies.cmake b/cmake/dependencies.cmake index cf633e2494..ece0afc3bd 100644 --- a/cmake/dependencies.cmake +++ b/cmake/dependencies.cmake @@ -44,10 +44,6 @@ find_package(Protobuf CONFIG REQUIRED) hunter_add_package(RapidJSON) find_package(RapidJSON CONFIG REQUIRED) -# https://docs.hunter.sh/en/latest/packages/pkg/Microsoft.GSL.html -hunter_add_package(Microsoft.GSL) -find_package(Microsoft.GSL CONFIG REQUIRED) - hunter_add_package(erasure_coding_crust) find_package(erasure_coding_crust CONFIG REQUIRED) diff --git a/core/api/service/mmr/rpc.cpp b/core/api/service/mmr/rpc.cpp index 84db25d223..d7b0ba9a03 100644 --- a/core/api/service/mmr/rpc.cpp +++ b/core/api/service/mmr/rpc.cpp @@ -9,6 +9,7 @@ #include "api/jrpc/jrpc_server_impl.hpp" #include "api/service/jrpc_fn.hpp" #include "blockchain/block_tree.hpp" +#include "common/final_action.hpp" #include "offchain/offchain_worker_factory.hpp" #include "offchain/offchain_worker_pool.hpp" #include "runtime/runtime_api/mmr.hpp" @@ -62,8 +63,8 @@ namespace kagome::api { auto MmrRpc::withOffchain(const primitives::BlockHash &at) { // TODO(turuslan): simplify offchain - auto remove = - gsl::finally([&] { offchain_worker_pool_.get()->removeWorker(); }); + common::MovableFinalAction remove( + [&] { offchain_worker_pool_.get()->removeWorker(); }); outcome::result result{std::move(remove)}; if (auto r = block_tree_.get()->getBlockHeader(at)) { offchain_worker_pool_.get()->addWorker( diff --git a/core/blockchain/impl/block_tree_impl.hpp b/core/blockchain/impl/block_tree_impl.hpp index 036eeea6be..32084123f1 100644 --- a/core/blockchain/impl/block_tree_impl.hpp +++ b/core/blockchain/impl/block_tree_impl.hpp @@ -19,6 +19,7 @@ #include "blockchain/block_header_repository.hpp" #include "blockchain/block_storage.hpp" #include "blockchain/block_tree_error.hpp" +#include "common/final_action.hpp" #include "consensus/timeline/types.hpp" #include "crypto/hasher.hpp" #include "log/logger.hpp" @@ -227,7 +228,7 @@ namespace kagome::blockchain { return block_tree_data_.exclusiveAccess([&f, this](BlockTreeData &data) { exclusive_owner_ = std::this_thread::get_id(); - auto reset = gsl::finally([&] { exclusive_owner_ = std::nullopt; }); + common::FinalAction reset([&] { exclusive_owner_ = std::nullopt; }); return f(data); }); } diff --git a/core/common/final_action.hpp b/core/common/final_action.hpp new file mode 100644 index 0000000000..a19ecd150f --- /dev/null +++ b/core/common/final_action.hpp @@ -0,0 +1,64 @@ +/** + * Copyright Quadrivium LLC + * All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include + +namespace kagome::common { + + template + struct FinalAction { + FinalAction() = delete; + FinalAction(FinalAction &&func) = delete; + FinalAction(const FinalAction &func) = delete; + FinalAction &operator=(FinalAction &&func) = delete; + FinalAction &operator=(const FinalAction &func) = delete; + + FinalAction(F &&func) : func(std::forward(func)) {} + + ~FinalAction() { + func(); + } + + public: + // To prevent an object being created on the heap + void *operator new(std::size_t) = delete; // standard new + void *operator new(std::size_t, void *) = delete; // placement new + void *operator new[](std::size_t) = delete; // array new + void *operator new[](std::size_t, void *) = delete; // placement array new + + private: + F func; + }; + + template + FinalAction(F &&) -> FinalAction; + + template + struct MovableFinalAction { + MovableFinalAction() = delete; + MovableFinalAction(MovableFinalAction &&func) = default; + MovableFinalAction(const MovableFinalAction &func) = delete; + MovableFinalAction &operator=(MovableFinalAction &&func) = default; + MovableFinalAction &operator=(const MovableFinalAction &func) = delete; + + MovableFinalAction(F &&func) : func(std::forward(func)) {} + + ~MovableFinalAction() { + if (func.has_value()) { + func->operator()(); + } + } + + private: + std::optional func; + }; + + template + MovableFinalAction(F &&) -> MovableFinalAction; + +} // namespace kagome::common diff --git a/core/common/int_serialization.cpp b/core/common/int_serialization.cpp index e65edc27e8..d4a916e4ad 100644 --- a/core/common/int_serialization.cpp +++ b/core/common/int_serialization.cpp @@ -6,8 +6,6 @@ #include "common/int_serialization.hpp" -#include - #include "macro/endianness_utils.hpp" namespace kagome::common { diff --git a/core/consensus/grandpa/impl/grandpa_impl.cpp b/core/consensus/grandpa/impl/grandpa_impl.cpp index a8b1e9f3e6..8800848b5c 100644 --- a/core/consensus/grandpa/impl/grandpa_impl.cpp +++ b/core/consensus/grandpa/impl/grandpa_impl.cpp @@ -13,6 +13,7 @@ #include "application/app_state_manager.hpp" #include "blockchain/block_tree.hpp" +#include "common/final_action.hpp" #include "common/tagged.hpp" #include "consensus/grandpa/authority_manager.hpp" #include "consensus/grandpa/environment.hpp" @@ -776,7 +777,7 @@ namespace kagome::consensus::grandpa { need_cleanup_when_exiting_scope = true; } - auto cleanup = gsl::finally([&] { + common::FinalAction cleanup([&] { if (need_cleanup_when_exiting_scope) { catchup_request_timer_handle_.cancel(); pending_catchup_request_.reset(); diff --git a/core/crypto/bip39/dictionary.cpp b/core/crypto/bip39/dictionary.cpp index 13376dad43..6f2a08dc31 100644 --- a/core/crypto/bip39/dictionary.cpp +++ b/core/crypto/bip39/dictionary.cpp @@ -6,7 +6,6 @@ #include "crypto/bip39/dictionary.hpp" -#include #include "crypto/bip39/entropy_accumulator.hpp" #include "crypto/bip39/wordlist/english.hpp" @@ -15,7 +14,7 @@ namespace kagome::crypto::bip39 { void Dictionary::initialize() { for (size_t i = 0; i < english::dictionary.size(); ++i) { auto token = EntropyToken(i); - std::string_view word = gsl::at(english::dictionary, i); + std::string_view word = english::dictionary[i]; entropy_map_[word] = token; } } diff --git a/core/metrics/histogram_timer.hpp b/core/metrics/histogram_timer.hpp index 3b41117f8f..f91d1fee2d 100644 --- a/core/metrics/histogram_timer.hpp +++ b/core/metrics/histogram_timer.hpp @@ -6,8 +6,7 @@ #pragma once -#include - +#include "common/final_action.hpp" #include "metrics/metrics.hpp" namespace kagome::metrics { @@ -69,7 +68,7 @@ namespace kagome::metrics { } auto timer() { - return std::make_optional(gsl::finally(manual())); + return std::make_optional(common::MovableFinalAction(manual())); } }; } // namespace kagome::metrics diff --git a/core/network/helpers/stream_read_buffer.hpp b/core/network/helpers/stream_read_buffer.hpp index ade3238ff4..0ede2ca11e 100644 --- a/core/network/helpers/stream_read_buffer.hpp +++ b/core/network/helpers/stream_read_buffer.hpp @@ -46,7 +46,7 @@ namespace libp2p::connection { */ size_t readFromBuffer(std::span out) { // can't read more bytes than available - auto n = std::min(gsl::narrow(out.size()), size()); + auto n = std::min(out.size(), size()); BOOST_ASSERT(n != 0); // copy bytes from buffer std::copy_n(buffer->begin() + begin, n, out.begin()); @@ -143,12 +143,12 @@ namespace kagome::network { return stream_->remoteMultiaddr(); } - void read(gsl::span out, size_t bytes, ReadCallbackFunc cb) { + void read(std::span out, size_t bytes, ReadCallbackFunc cb) { check(); stream_->read(out, bytes, std::move(cb)); } - void readSome(gsl::span out, size_t bytes, ReadCallbackFunc cb) { + void readSome(std::span out, size_t bytes, ReadCallbackFunc cb) { check(); stream_->readSome(out, bytes, std::move(cb)); } @@ -157,14 +157,14 @@ namespace kagome::network { stream_->deferReadCallback(std::move(res), std::move(cb)); } - void write(gsl::span in, + void write(std::span in, size_t bytes, WriteCallbackFunc cb) { check(); stream_->write(in, bytes, std::move(cb)); } - void writeSome(gsl::span in, + void writeSome(std::span in, size_t bytes, WriteCallbackFunc cb) { check(); diff --git a/core/network/impl/synchronizer_impl.cpp b/core/network/impl/synchronizer_impl.cpp index ce614fbb39..79c09982e2 100644 --- a/core/network/impl/synchronizer_impl.cpp +++ b/core/network/impl/synchronizer_impl.cpp @@ -10,6 +10,7 @@ #include "application/app_configuration.hpp" #include "blockchain/block_tree_error.hpp" +#include "common/final_action.hpp" #include "consensus/babe/has_babe_consensus_digest.hpp" #include "consensus/grandpa/environment.hpp" #include "consensus/grandpa/has_authority_set_change.hpp" @@ -818,7 +819,7 @@ namespace kagome::network { } busy_peers_.insert(peer_id); - auto cleanup = gsl::finally([this, peer_id] { + common::FinalAction cleanup([this, peer_id] { auto peer = busy_peers_.find(peer_id); if (peer != busy_peers_.end()) { busy_peers_.erase(peer); @@ -1070,7 +1071,7 @@ namespace kagome::network { return; } SL_TRACE(log_, "Begin applying"); - auto cleanup = gsl::finally([weak = weak_from_this()] { + common::MovableFinalAction cleanup([weak = weak_from_this()] { if (auto self = weak.lock()) { SL_TRACE(self->log_, "End applying"); self->applying_in_progress_ = false; @@ -1289,7 +1290,7 @@ namespace kagome::network { return; } SL_TRACE(log_, "Begin justification applying"); - auto cleanup = gsl::finally([this] { + common::FinalAction cleanup([this] { SL_TRACE(log_, "End justification applying"); applying_in_progress_ = false; }); diff --git a/core/network/types/blocks_request.hpp b/core/network/types/blocks_request.hpp index 4052b6ba04..54a28db769 100644 --- a/core/network/types/blocks_request.hpp +++ b/core/network/types/blocks_request.hpp @@ -8,7 +8,6 @@ #include -#include #include #include "network/types/block_attributes.hpp" diff --git a/core/network/warp/cache.cpp b/core/network/warp/cache.cpp index 5b087e2637..a64acd248b 100644 --- a/core/network/warp/cache.cpp +++ b/core/network/warp/cache.cpp @@ -10,6 +10,7 @@ #include #include "blockchain/impl/storage_util.hpp" +#include "common/final_action.hpp" #include "consensus/grandpa/has_authority_set_change.hpp" #include "storage/predefined_keys.hpp" @@ -135,7 +136,7 @@ namespace kagome::network { if (bool old = false; not caching_.compare_exchange_strong(old, true)) { return outcome::success(); } - auto unlock = gsl::finally([&] { caching_.store(false); }); + common::FinalAction unlock([&] { caching_.store(false); }); for (; cache_next_ <= finalized; ++cache_next_) { OUTCOME_TRY(hash, block_repository_->getHashByNumber(cache_next_)); OUTCOME_TRY(header, block_repository_->getBlockHeader(hash)); diff --git a/core/network/warp/sync.cpp b/core/network/warp/sync.cpp index a969c921f5..6eb847a67d 100644 --- a/core/network/warp/sync.cpp +++ b/core/network/warp/sync.cpp @@ -8,6 +8,7 @@ #include "blockchain/block_storage.hpp" #include "blockchain/block_tree.hpp" +#include "common/final_action.hpp" #include "consensus/babe/babe_config_repository.hpp" #include "consensus/grandpa/authority_manager.hpp" #include "consensus/grandpa/has_authority_set_change.hpp" @@ -63,7 +64,7 @@ namespace kagome::network { return; } std::optional min, max; - auto log = gsl::finally([&] { + common::FinalAction log([&] { if (min) { SL_INFO(log_, "finalized {}..{}", *min, *max); } diff --git a/core/offchain/impl/offchain_worker_impl.cpp b/core/offchain/impl/offchain_worker_impl.cpp index ec5f215ba9..7dd4b1bd8e 100644 --- a/core/offchain/impl/offchain_worker_impl.cpp +++ b/core/offchain/impl/offchain_worker_impl.cpp @@ -6,11 +6,13 @@ #include "offchain/impl/offchain_worker_impl.hpp" -#include #include +#include + #include "api/service/author/author_api.hpp" #include "application/app_configuration.hpp" +#include "common/final_action.hpp" #include "crypto/hasher.hpp" #include "offchain/impl/offchain_local_storage.hpp" #include "offchain/offchain_worker_pool.hpp" @@ -62,15 +64,15 @@ namespace kagome::offchain { outcome::result OffchainWorkerImpl::run() { BOOST_ASSERT(not ocw_pool_->getWorker()); - auto at_end = - gsl::finally([prev_thread_name = soralog::util::getThreadName()] { + common::FinalAction at_end( + [prev_thread_name = soralog::util::getThreadName()] { soralog::util::setThreadName(prev_thread_name); }); soralog::util::setThreadName("ocw.#" + std::to_string(block_.number)); ocw_pool_->addWorker(shared_from_this()); - auto remove = gsl::finally([&] { ocw_pool_->removeWorker(); }); + common::FinalAction remove([&] { ocw_pool_->removeWorker(); }); SL_TRACE(log_, "Offchain worker is started for block {}", block_); diff --git a/core/offchain/impl/runner.hpp b/core/offchain/impl/runner.hpp index ee5653dcc3..4b157ee02a 100644 --- a/core/offchain/impl/runner.hpp +++ b/core/offchain/impl/runner.hpp @@ -7,9 +7,9 @@ #pragma once #include -#include #include +#include "common/final_action.hpp" #include "utils/thread_pool.hpp" namespace kagome::offchain { @@ -41,7 +41,7 @@ namespace kagome::offchain { thread_pool_.io_context()->post( [weak{weak_from_this()}, task{std::move(task)}] { if (auto self = weak.lock()) { - auto release = gsl::finally([&] { + common::FinalAction release([&] { std::unique_lock lock{self->mutex_}; ++self->free_threads_; }); diff --git a/core/parachain/pvf/precheck.cpp b/core/parachain/pvf/precheck.cpp index ed27ecd4cb..dc2234baf2 100644 --- a/core/parachain/pvf/precheck.cpp +++ b/core/parachain/pvf/precheck.cpp @@ -6,6 +6,7 @@ #include "parachain/pvf/precheck.hpp" +#include "common/final_action.hpp" #include "metrics/histogram_timer.hpp" #include "offchain/offchain_worker_factory.hpp" #include "offchain/offchain_worker_pool.hpp" @@ -119,8 +120,8 @@ namespace kagome::parachain { OUTCOME_TRY(signature, signer->signRaw(statement.signable())); offchain_worker_pool_->addWorker( offchain_worker_factory_->make(executor_, header)); - auto remove = - gsl::finally([&] { offchain_worker_pool_->removeWorker(); }); + common::FinalAction remove( + [&] { offchain_worker_pool_->removeWorker(); }); OUTCOME_TRY(parachain_api_->submit_pvf_check_statement( block_hash, statement, signature)); } diff --git a/core/parachain/validator/impl/parachain_processor.cpp b/core/parachain/validator/impl/parachain_processor.cpp index 4148072397..1472c509b7 100644 --- a/core/parachain/validator/impl/parachain_processor.cpp +++ b/core/parachain/validator/impl/parachain_processor.cpp @@ -7,9 +7,9 @@ #include "parachain/validator/parachain_processor.hpp" #include -#include #include +#include "common/final_action.hpp" #include "crypto/hasher.hpp" #include "crypto/sr25519_provider.hpp" #include "dispute_coordinator/impl/runtime_info.hpp" @@ -309,7 +309,7 @@ namespace kagome::parachain { ParachainProcessorImpl::initNewBackingTask( const primitives::BlockHash &relay_parent) { bool is_parachain_validator = false; - auto metric_updater = gsl::finally([self{this}, &is_parachain_validator] { + common::FinalAction metric_updater([self{this}, &is_parachain_validator] { self->metric_is_parachain_validator_->set(is_parachain_validator); }); OUTCOME_TRY(validators, parachain_host_->validators(relay_parent)); diff --git a/core/primitives/transcript.hpp b/core/primitives/transcript.hpp index 3ca5db84dc..e9d83d3eb4 100644 --- a/core/primitives/transcript.hpp +++ b/core/primitives/transcript.hpp @@ -95,7 +95,9 @@ namespace kagome::primitives { } bool operator==(const Transcript &other) const { - return other.strobe_.data() == strobe_.data(); + return std::equal(other.strobe_.data().begin(), + other.strobe_.data().end(), + strobe_.data().begin()); } }; diff --git a/core/runtime/runtime_api/impl/block_builder.cpp b/core/runtime/runtime_api/impl/block_builder.cpp index bfa66833b8..80fbc36b13 100644 --- a/core/runtime/runtime_api/impl/block_builder.cpp +++ b/core/runtime/runtime_api/impl/block_builder.cpp @@ -6,6 +6,7 @@ #include "runtime/runtime_api/impl/block_builder.hpp" +#include "common/final_action.hpp" #include "runtime/executor.hpp" #include "runtime/trie_storage_provider.hpp" @@ -23,7 +24,7 @@ namespace kagome::runtime { OUTCOME_TRY(ctx.module_instance->getEnvironment() .storage_provider->startTransaction()); auto should_rollback = true; - auto rollback = gsl::finally([&] { + common::FinalAction rollback([&] { if (should_rollback) { std::ignore = ctx.module_instance->getEnvironment() .storage_provider->rollbackTransaction(); @@ -58,7 +59,7 @@ namespace kagome::runtime { // `env.storage_provider`s `PersistentTrieBatch`. OUTCOME_TRY(ctx.module_instance->getEnvironment() .storage_provider->startTransaction()); - auto rollback = gsl::finally([&] { + common::FinalAction rollback([&] { std::ignore = ctx.module_instance->getEnvironment() .storage_provider->rollbackTransaction(); }); diff --git a/core/runtime/wavm/module_instance.cpp b/core/runtime/wavm/module_instance.cpp index 2d908c2d3c..c89f01655e 100644 --- a/core/runtime/wavm/module_instance.cpp +++ b/core/runtime/wavm/module_instance.cpp @@ -9,6 +9,7 @@ #include #include +#include "common/final_action.hpp" #include "host_api/host_api.hpp" #include "log/profiling_logger.hpp" #include "runtime/common/runtime_transaction_error.hpp" @@ -143,7 +144,7 @@ namespace kagome::runtime::wavm { std::array untaggedInvokeResults; pushBorrowedRuntimeInstance( std::const_pointer_cast(shared_from_this())); - const auto pop = gsl::finally(&popBorrowedRuntimeInstance); + common::FinalAction pop(&popBorrowedRuntimeInstance); try { WAVM::Runtime::unwindSignalsAsExceptions( [&context, diff --git a/test/core/consensus/babe/babe_test.cpp b/test/core/consensus/babe/babe_test.cpp index 645d26de55..a5e82a6e18 100644 --- a/test/core/consensus/babe/babe_test.cpp +++ b/test/core/consensus/babe/babe_test.cpp @@ -46,6 +46,7 @@ using kagome::blockchain::BlockTreeMock; using kagome::blockchain::DigestTrackerMock; using kagome::clock::SystemClockMock; using kagome::common::Buffer; +using kagome::common::BufferView; using kagome::consensus::BlockProductionError; using kagome::consensus::EpochLength; using kagome::consensus::EpochNumber; From f2e38d45d689631fe07e525dc995d1b2add730cc Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Wed, 25 Oct 2023 21:59:49 +0300 Subject: [PATCH 03/12] refactor: gst to std Signed-off-by: Dmitriy Khaustov aka xDimon --- core/api/service/author/requests/has_key.hpp | 2 +- .../author/requests/has_session_keys.hpp | 2 +- .../service/author/requests/insert_key.hpp | 5 ++- .../requests/submit_and_watch_extrinsic.hpp | 3 +- .../author/requests/submit_extrinsic.hpp | 3 +- .../service/chain/requests/get_block_hash.cpp | 2 +- core/api/service/mmr/rpc.cpp | 15 +++++---- .../service/payment/requests/query_info.hpp | 3 +- core/blockchain/impl/digest_tracker_impl.cpp | 8 ++--- core/common/buffer.hpp | 2 +- core/common/buffer_or_view.hpp | 3 +- .../consensus/babe/impl/babe_digests_util.cpp | 4 +-- core/crypto/bip39/bip39_types.hpp | 3 +- .../crypto/crypto_store/crypto_store_impl.cpp | 9 ++---- core/crypto/sha/sha256.cpp | 6 ++-- .../impl/prioritized_selection.cpp | 2 +- core/primitives/ss58_codec.cpp | 10 +++--- core/runtime/wavm/module_cache.cpp | 3 +- core/storage/rocksdb/rocksdb_util.hpp | 5 ++- .../trie/polkadot_trie/polkadot_trie_impl.cpp | 3 +- .../api/service/author/author_api_test.cpp | 31 +++++++------------ 21 files changed, 51 insertions(+), 73 deletions(-) diff --git a/core/api/service/author/requests/has_key.hpp b/core/api/service/author/requests/has_key.hpp index 57b47d30bc..5bb879aeb6 100644 --- a/core/api/service/author/requests/has_key.hpp +++ b/core/api/service/author/requests/has_key.hpp @@ -23,7 +23,7 @@ namespace kagome::api::author::request { outcome::result execute() override { OUTCOME_TRY(public_key, common::unhexWith0x(getParam<0>())); - return api_->hasKey(std::span(public_key.data(), public_key.size()), + return api_->hasKey(public_key, crypto::decodeKeyTypeFromStr(getParam<1>())); } diff --git a/core/api/service/author/requests/has_session_keys.hpp b/core/api/service/author/requests/has_session_keys.hpp index 6af9318d1f..5fee8581b9 100644 --- a/core/api/service/author/requests/has_session_keys.hpp +++ b/core/api/service/author/requests/has_session_keys.hpp @@ -23,7 +23,7 @@ namespace kagome::api::author::request { outcome::result execute() override { OUTCOME_TRY(keys, common::unhexWith0x(getParam<0>())); - return api_->hasSessionKeys(std::span(keys.data(), keys.size())); + return api_->hasSessionKeys(keys); } private: diff --git a/core/api/service/author/requests/insert_key.hpp b/core/api/service/author/requests/insert_key.hpp index 0298d196fb..22ca6f465e 100644 --- a/core/api/service/author/requests/insert_key.hpp +++ b/core/api/service/author/requests/insert_key.hpp @@ -25,9 +25,8 @@ namespace kagome::api::author::request { outcome::result execute() override { OUTCOME_TRY(seed, common::unhexWith0x(getParam<1>())); OUTCOME_TRY(public_key, common::unhexWith0x(getParam<2>())); - return api_->insertKey(crypto::decodeKeyTypeFromStr(getParam<0>()), - std::span(seed.data(), seed.size()), - std::span(public_key.data(), public_key.size())); + return api_->insertKey( + crypto::decodeKeyTypeFromStr(getParam<0>()), seed, public_key); } private: diff --git a/core/api/service/author/requests/submit_and_watch_extrinsic.hpp b/core/api/service/author/requests/submit_and_watch_extrinsic.hpp index 257c7d182b..24df06372b 100644 --- a/core/api/service/author/requests/submit_and_watch_extrinsic.hpp +++ b/core/api/service/author/requests/submit_and_watch_extrinsic.hpp @@ -24,8 +24,7 @@ namespace kagome::api::author::request { outcome::result execute() override { auto ext_hex = getParam<0>(); OUTCOME_TRY(buffer, common::unhexWith0x(ext_hex)); - OUTCOME_TRY(extrinsic, - scale::decode(std::span(buffer))); + OUTCOME_TRY(extrinsic, scale::decode(buffer)); return api_->submitAndWatchExtrinsic(extrinsic); } diff --git a/core/api/service/author/requests/submit_extrinsic.hpp b/core/api/service/author/requests/submit_extrinsic.hpp index baeb1ba3fc..d2f9429d98 100644 --- a/core/api/service/author/requests/submit_extrinsic.hpp +++ b/core/api/service/author/requests/submit_extrinsic.hpp @@ -24,8 +24,7 @@ namespace kagome::api::author::request { outcome::result execute() override { auto ext_hex = getParam<0>(); OUTCOME_TRY(buffer, common::unhexWith0x(ext_hex)); - OUTCOME_TRY(extrinsic, - scale::decode(std::span(buffer))); + OUTCOME_TRY(extrinsic, scale::decode(buffer)); return api_->submitExtrinsic(primitives::TransactionSource::External, extrinsic); } diff --git a/core/api/service/chain/requests/get_block_hash.cpp b/core/api/service/chain/requests/get_block_hash.cpp index f88e93d60e..073fa12baa 100644 --- a/core/api/service/chain/requests/get_block_hash.cpp +++ b/core/api/service/chain/requests/get_block_hash.cpp @@ -80,7 +80,7 @@ namespace kagome::api::chain::request { }, [this]( const std::vector &v) -> outcome::result { - OUTCOME_TRY(rr, api_->getBlockHash(std::span(v))); + OUTCOME_TRY(rr, api_->getBlockHash(v)); std::vector results{}; results.reserve(v.size()); for (const auto &it : rr) { diff --git a/core/api/service/mmr/rpc.cpp b/core/api/service/mmr/rpc.cpp index d7b0ba9a03..128d70b6c3 100644 --- a/core/api/service/mmr/rpc.cpp +++ b/core/api/service/mmr/rpc.cpp @@ -120,12 +120,11 @@ namespace kagome::api { [](std::shared_ptr self, primitives::MmrLeavesProof proof_raw) -> outcome::result { auto &at = proof_raw.block_hash; - OUTCOME_TRY(leaves, - scale::decode( - proof_raw.leaves.view())); OUTCOME_TRY( - proof, - scale::decode(proof_raw.proof.view())); + leaves, + scale::decode(proof_raw.leaves)); + OUTCOME_TRY(proof, + scale::decode(proof_raw.proof)); auto offchain = self->withOffchain(at); OUTCOME_TRY(r, self->mmr_api_.get()->verifyProof(at, leaves, proof)); @@ -141,9 +140,9 @@ namespace kagome::api { primitives::BlockHash mmr_root, primitives::MmrLeavesProof proof_raw) -> outcome::result { auto &at = proof_raw.block_hash; - OUTCOME_TRY(leaves, - scale::decode( - proof_raw.leaves.view())); + OUTCOME_TRY( + leaves, + scale::decode(proof_raw.leaves)); OUTCOME_TRY( proof, scale::decode(proof_raw.proof.view())); diff --git a/core/api/service/payment/requests/query_info.hpp b/core/api/service/payment/requests/query_info.hpp index d796879b1f..b1489c1a41 100644 --- a/core/api/service/payment/requests/query_info.hpp +++ b/core/api/service/payment/requests/query_info.hpp @@ -30,8 +30,7 @@ namespace kagome::api::payment::request { auto ext_hex = getParam<0>(); OUTCOME_TRY(ext_bytes, common::unhexWith0x(ext_hex)); - OUTCOME_TRY(extrinsic, - scale::decode(std::span(ext_bytes))); + OUTCOME_TRY(extrinsic, scale::decode(ext_bytes)); auto at_hex = getParam<1>(); if (at_hex.empty()) { diff --git a/core/blockchain/impl/digest_tracker_impl.cpp b/core/blockchain/impl/digest_tracker_impl.cpp index 7f921b2ac5..b1f03f46e4 100644 --- a/core/blockchain/impl/digest_tracker_impl.cpp +++ b/core/blockchain/impl/digest_tracker_impl.cpp @@ -71,15 +71,13 @@ namespace kagome::blockchain { const primitives::BlockContext &context, const primitives::Consensus &message) { if (message.consensus_engine_id == primitives::kBabeEngineId) { - OUTCOME_TRY(digest, - scale::decode(message.data.view())); + OUTCOME_TRY(digest, scale::decode(message.data)); return outcome::success(); } else if (message.consensus_engine_id == primitives::kGrandpaEngineId) { - OUTCOME_TRY( - digest, - scale::decode(message.data.view())); + OUTCOME_TRY(digest, + scale::decode(message.data)); return grandpa_digest_observer_->onDigest(context, digest); diff --git a/core/common/buffer.hpp b/core/common/buffer.hpp index bf2fe86ad5..2614a4db46 100644 --- a/core/common/buffer.hpp +++ b/core/common/buffer.hpp @@ -157,7 +157,7 @@ namespace kagome::common { } BufferView view(size_t offset = 0, size_t length = -1) const { - return BufferView{std::span(*this).subspan(offset, length)}; + return std::span(*this).subspan(offset, length); } /** diff --git a/core/common/buffer_or_view.hpp b/core/common/buffer_or_view.hpp index 0180c84792..ee8f36eaa4 100644 --- a/core/common/buffer_or_view.hpp +++ b/core/common/buffer_or_view.hpp @@ -28,8 +28,7 @@ namespace kagome::common { BufferOrView(const BufferView &view) : variant{view} {} template - BufferOrView(const std::array &array) - : variant{std::span(array)} {} + BufferOrView(const std::array &array) : variant{array} {} BufferOrView(const std::vector &vector) = delete; BufferOrView(std::vector &&vector) diff --git a/core/consensus/babe/impl/babe_digests_util.cpp b/core/consensus/babe/impl/babe_digests_util.cpp index ee58d4caf7..915826ecbd 100644 --- a/core/consensus/babe/impl/babe_digests_util.cpp +++ b/core/consensus/babe/impl/babe_digests_util.cpp @@ -45,7 +45,7 @@ namespace kagome::consensus::babe { auto pre_runtime_opt = getFromVariant(digest); if (pre_runtime_opt.has_value()) { auto babe_block_header_res = - scale::decode(pre_runtime_opt->get().data.view()); + scale::decode(pre_runtime_opt->get().data); if (babe_block_header_res.has_value()) { // found the BabeBlockHeader digest; return return babe_block_header_res.value(); @@ -72,7 +72,7 @@ namespace kagome::consensus::babe { return DigestError::NO_TRAILING_SEAL_DIGEST; } - OUTCOME_TRY(seal_digest, scale::decode(seal_opt->get().data.view())); + OUTCOME_TRY(seal_digest, scale::decode(seal_opt->get().data)); return seal_digest; } diff --git a/core/crypto/bip39/bip39_types.hpp b/core/crypto/bip39/bip39_types.hpp index 794e84eb40..3396ebc5bd 100644 --- a/core/crypto/bip39/bip39_types.hpp +++ b/core/crypto/bip39/bip39_types.hpp @@ -27,8 +27,7 @@ namespace kagome::crypto::bip39 { template outcome::result as() const { - return T::fromSpan( - std::span(seed).first(std::min(seed.size(), T::size()))); + return T::fromSpan(seed.view(0, std::min(seed.size(), T::size()))); } }; } // namespace kagome::crypto::bip39 diff --git a/core/crypto/crypto_store/crypto_store_impl.cpp b/core/crypto/crypto_store/crypto_store_impl.cpp index 9242a1b5f2..64a51c958e 100644 --- a/core/crypto/crypto_store/crypto_store_impl.cpp +++ b/core/crypto/crypto_store/crypto_store_impl.cpp @@ -128,8 +128,7 @@ namespace kagome::crypto { if (kp_opt) { return kp_opt.value(); } - OUTCOME_TRY(phrase, - file_storage_->searchForPhrase(key_type, std::span(pk))); + OUTCOME_TRY(phrase, file_storage_->searchForPhrase(key_type, pk)); if (not phrase) { return CryptoStoreError::KEY_NOT_FOUND; } @@ -143,8 +142,7 @@ namespace kagome::crypto { if (kp_opt) { return kp_opt.value(); } - OUTCOME_TRY(phrase, - file_storage_->searchForPhrase(key_type, std::span(pk))); + OUTCOME_TRY(phrase, file_storage_->searchForPhrase(key_type, pk)); if (not phrase) { return CryptoStoreError::KEY_NOT_FOUND; } @@ -158,8 +156,7 @@ namespace kagome::crypto { if (kp_opt) { return kp_opt.value(); } - OUTCOME_TRY(phrase, - file_storage_->searchForPhrase(key_type, std::span(pk))); + OUTCOME_TRY(phrase, file_storage_->searchForPhrase(key_type, pk)); if (not phrase) { return CryptoStoreError::KEY_NOT_FOUND; } diff --git a/core/crypto/sha/sha256.cpp b/core/crypto/sha/sha256.cpp index fd6e3665e7..d24f379faa 100644 --- a/core/crypto/sha/sha256.cpp +++ b/core/crypto/sha/sha256.cpp @@ -10,9 +10,9 @@ namespace kagome::crypto { common::Hash256 sha256(std::string_view input) { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - const auto *bytes_ptr = reinterpret_cast(input.data()); - return sha256(std::span(bytes_ptr, input.length())); + return sha256( + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + {reinterpret_cast(input.data()), input.size()}); } common::Hash256 sha256(std::span input) { diff --git a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp index 6f475a939e..3e30e1e0d7 100644 --- a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp +++ b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp @@ -148,7 +148,7 @@ namespace kagome::dispute { for (size_t i = 0; i < disputes.size();) { auto batch_size = std::min(kVotesSelectionBatchSize, disputes.size() - i); - auto batch = std::span(&disputes[i], batch_size); + auto batch = std::span(disputes).first(batch_size); i += batch_size; // Filter votes which are already onchain diff --git a/core/primitives/ss58_codec.cpp b/core/primitives/ss58_codec.cpp index e2d48af281..3ca08b8a53 100644 --- a/core/primitives/ss58_codec.cpp +++ b/core/primitives/ss58_codec.cpp @@ -30,7 +30,7 @@ namespace kagome::primitives { constexpr auto PREFIX = "SS58PRE"; auto preimage = common::Buffer{}.put(PREFIX).put(ss58_address); auto checksum = hasher.blake2b_512(preimage); - return common::Buffer{std::span(checksum).subspan(0, kSs58ChecksumLength)}; + return {std::span(checksum).first()}; } outcome::result decodeSs58(std::string_view account_address, @@ -40,10 +40,10 @@ namespace kagome::primitives { OUTCOME_TRY(ss58_account_id, libp2p::multi::detail::decodeBase58(account_address)); - auto ss58_no_checksum = std::span( - ss58_account_id.data(), ss58_account_id.size() - kSs58ChecksumLength); - auto checksum = std::span( - ss58_account_id.data() + ss58_no_checksum.size(), kSs58ChecksumLength); + auto ss58_no_checksum = + std::span(ss58_account_id) + .first(ss58_account_id.size() - kSs58ChecksumLength); + auto checksum = std::span(ss58_account_id).last(); auto calculated_checksum = calculateChecksum(ss58_no_checksum, hasher); diff --git a/core/runtime/wavm/module_cache.cpp b/core/runtime/wavm/module_cache.cpp index d41ff4a5a2..0464707c63 100644 --- a/core/runtime/wavm/module_cache.cpp +++ b/core/runtime/wavm/module_cache.cpp @@ -26,8 +26,7 @@ namespace kagome::runtime::wavm { const WAVM::U8 *wasmBytes, WAVM::Uptr numWASMBytes, std::function()> &&compileThunk) { - auto runtime_hash = - hasher_->twox_64(std::span(wasmBytes, numWASMBytes)).toHex(); + auto runtime_hash = hasher_->twox_64({wasmBytes, numWASMBytes}).toHex(); auto filepath = cache_dir_ / runtime_hash; if (!exists(filepath) and !exists(cache_dir_) and !fs::createDirectoryRecursive(cache_dir_)) { diff --git a/core/storage/rocksdb/rocksdb_util.hpp b/core/storage/rocksdb/rocksdb_util.hpp index 713124db9f..3e468249bc 100644 --- a/core/storage/rocksdb/rocksdb_util.hpp +++ b/core/storage/rocksdb/rocksdb_util.hpp @@ -46,14 +46,13 @@ namespace kagome::storage { inline std::span make_span(const rocksdb::Slice &s) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - const auto *ptr = reinterpret_cast(s.data()); - return std::span(ptr, s.size()); + return {reinterpret_cast(s.data()), s.size()}; } inline common::Buffer make_buffer(const rocksdb::Slice &s) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) const auto *ptr = reinterpret_cast(s.data()); // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - return common::Buffer{ptr, ptr + s.size()}; + return {ptr, ptr + s.size()}; } } // namespace kagome::storage diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp index 799b384933..15b61eb12a 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp @@ -546,8 +546,7 @@ namespace kagome::storage::trie { return outcome::success(); } auto common_length = getCommonPrefixLength(parent->getKeyNibbles(), path); - auto common_nibbles = - std::span(parent->getKeyNibbles().data(), common_length); + auto common_nibbles = parent->getKeyNibbles().view(0, common_length); // path is even less than the parent key (path is the prefix of the // parent key) if (path == common_nibbles diff --git a/test/core/api/service/author/author_api_test.cpp b/test/core/api/service/author/author_api_test.cpp index 94bb1076fa..7d0764ef76 100644 --- a/test/core/api/service/author/author_api_test.cpp +++ b/test/core/api/service/author/author_api_test.cpp @@ -143,10 +143,10 @@ struct AuthorApiTest : public ::testing::Test { store = std::make_shared(); key_store = KeyFileStorage::createAt("test_chain_43/keystore").value(); key_pair = generateSr25519Keypair(); - ASSERT_OUTCOME_SUCCESS_TRY(key_store->saveKeyPair( - KeyTypes::BABE, - std::span(key_pair.public_key.data(), 32), - std::span(std::array({1}).begin(), 1))); + ASSERT_OUTCOME_SUCCESS_TRY( + key_store->saveKeyPair(KeyTypes::BABE, + std::span(key_pair.public_key).first<32>(), + std::array{1})); role.flags.authority = 1; EXPECT_CALL(*config, roles()).WillOnce(Return(role)); keys = std::make_shared(store, *config); @@ -266,8 +266,7 @@ TEST_F(AuthorApiTest, InsertKeyGran) { */ TEST_F(AuthorApiTest, HasSessionKeysEmpty) { Buffer keys; - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), false); } @@ -280,8 +279,7 @@ TEST_F(AuthorApiTest, HasSessionKeysEmpty) { TEST_F(AuthorApiTest, HasSessionKeysLessThanOne) { Buffer keys; keys.resize(31); - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), false); } @@ -294,8 +292,7 @@ TEST_F(AuthorApiTest, HasSessionKeysLessThanOne) { TEST_F(AuthorApiTest, HasSessionKeysOverload) { Buffer keys; keys.resize(32 * 6 + 1); - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), false); } @@ -308,8 +305,7 @@ TEST_F(AuthorApiTest, HasSessionKeysOverload) { TEST_F(AuthorApiTest, HasSessionKeysNotEqualKeys) { Buffer keys; keys.resize(32 * 5 + 1); - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), false); } @@ -342,8 +338,7 @@ TEST_F(AuthorApiTest, HasSessionKeysSuccess6Keys) { EXPECT_CALL(*store, findSr25519Keypair(KeyTypes::AUTHORITY_DISCOVERY, _)) .Times(1) .WillOnce(Return(srOk)); - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), true); } @@ -359,8 +354,7 @@ TEST_F(AuthorApiTest, HasSessionKeysSuccess1Keys) { EXPECT_CALL(*store, findEd25519Keypair(KeyTypes::GRANDPA, _)) .Times(1) .WillOnce(Return(edOk)); - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), true); } @@ -378,8 +372,7 @@ TEST_F(AuthorApiTest, HasSessionKeysFailureNotFound) { EXPECT_CALL(*store, findSr25519Keypair(_, _)) .Times(1) .WillOnce(Return(srErr)); - EXPECT_OUTCOME_SUCCESS( - res, author_api->hasSessionKeys(std::span(keys.data(), keys.size()))); + EXPECT_OUTCOME_SUCCESS(res, author_api->hasSessionKeys(keys)); EXPECT_EQ(res.value(), false); } @@ -391,7 +384,7 @@ TEST_F(AuthorApiTest, HasSessionKeysFailureNotFound) { TEST_F(AuthorApiTest, HasKeySuccess) { EXPECT_OUTCOME_SUCCESS( res, - author_api->hasKey(std::span(key_pair.public_key.data(), 32), + author_api->hasKey(std::span(key_pair.public_key).first<32>(), KeyTypes::BABE)); EXPECT_EQ(res.value(), true); } From 9ee762a6e54245e2bd06a4d9740df32cbfff806d Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Thu, 26 Oct 2023 17:20:36 +0300 Subject: [PATCH 04/12] refactor: gst to std Signed-off-by: Dmitriy Khaustov aka xDimon --- core/api/service/author/author_api.hpp | 17 +++++------ .../service/author/impl/author_api_impl.cpp | 14 ++++----- .../service/author/impl/author_api_impl.hpp | 12 ++++---- .../publisher/address_publisher.cpp | 3 +- core/authority_discovery/query/query_impl.cpp | 1 + core/common/blob.hpp | 5 ++-- core/common/buffer.hpp | 2 +- core/common/buffer_back_insert_iterator.hpp | 2 +- core/common/buffer_or_view.hpp | 2 +- core/common/buffer_view.hpp | 29 +++++++++++++++++-- core/common/bytestr.hpp | 17 +++++++---- core/common/int_serialization.cpp | 20 +++++-------- core/common/int_serialization.hpp | 15 ++++++---- .../consensus/babe/impl/babe_digests_util.cpp | 3 +- core/crypto/bip39/bip39_provider.hpp | 2 +- .../crypto/bip39/impl/bip39_provider_impl.cpp | 2 +- .../crypto/bip39/impl/bip39_provider_impl.hpp | 5 ++-- core/crypto/crypto_store/crypto_suites.hpp | 16 +++++----- core/crypto/crypto_store/key_file_storage.cpp | 11 ++++--- core/crypto/crypto_store/key_file_storage.hpp | 11 ++++--- core/crypto/ecdsa/ecdsa_provider_impl.cpp | 4 +-- core/crypto/ecdsa/ecdsa_provider_impl.hpp | 5 ++-- core/crypto/ecdsa_provider.hpp | 4 +-- core/crypto/ed25519/ed25519_provider_impl.cpp | 4 +-- core/crypto/ed25519/ed25519_provider_impl.hpp | 4 +-- core/crypto/ed25519_provider.hpp | 5 ++-- .../pbkdf2/impl/pbkdf2_provider_impl.cpp | 4 +-- .../pbkdf2/impl/pbkdf2_provider_impl.hpp | 4 +-- core/crypto/pbkdf2/pbkdf2_provider.hpp | 5 ++-- core/crypto/sha/sha256.cpp | 2 +- core/crypto/sha/sha256.hpp | 2 +- core/crypto/sr25519/sr25519_provider_impl.cpp | 6 ++-- core/crypto/sr25519/sr25519_provider_impl.hpp | 6 ++-- core/crypto/sr25519_provider.hpp | 7 ++--- core/crypto/twox/twox.cpp | 6 ++-- core/crypto/twox/twox.hpp | 6 ++-- .../host_api/impl/child_storage_extension.cpp | 4 +-- core/host_api/impl/storage_extension.cpp | 4 +-- .../adapters/protobuf_block_response.hpp | 3 +- core/network/helpers/stream_proxy_base.hpp | 8 ++--- core/network/helpers/stream_read_buffer.hpp | 8 ++--- core/network/notifications/handshake.hpp | 2 +- core/primitives/block_header.hpp | 2 +- .../binaryen/module/module_instance_impl.cpp | 2 +- core/runtime/wavm/core_api_factory_impl.cpp | 4 +-- core/runtime/wavm/module.cpp | 2 +- core/runtime/wavm/module.hpp | 2 +- core/storage/rocksdb/rocksdb_util.hpp | 2 +- .../polkadot_trie_cursor_impl.cpp | 2 +- .../polkadot_trie_cursor_impl.hpp | 4 +-- .../trie/polkadot_trie/polkadot_trie_impl.cpp | 6 ++-- .../trie/serialization/buffer_stream.hpp | 12 ++++---- core/utils/storage_explorer.cpp | 2 +- .../api/service/payment/payment_api_test.cpp | 3 +- test/core/common/buffer_view_test.cpp | 2 +- test/core/host_api/crypto_extension_test.cpp | 5 ++-- .../core/host_api/offchain_extension_test.cpp | 16 +++++----- test/core/parachain/pvf_test.cpp | 3 +- .../runtime/storage_code_provider_test.cpp | 4 +-- .../api/service/author/author_api_mock.hpp | 8 ++--- test/mock/core/crypto/ecdsa_provider_mock.hpp | 6 ++-- .../core/crypto/ed25519_provider_mock.hpp | 4 +-- .../core/crypto/sr25519_provider_mock.hpp | 6 ++-- test/mock/libp2p/basic/read_writer_mock.hpp | 4 +-- 64 files changed, 200 insertions(+), 193 deletions(-) diff --git a/core/api/service/author/author_api.hpp b/core/api/service/author/author_api.hpp index 6fdfd8e4c9..f00e85f033 100644 --- a/core/api/service/author/author_api.hpp +++ b/core/api/service/author/author_api.hpp @@ -8,6 +8,7 @@ #include "common/blob.hpp" #include "common/buffer.hpp" +#include "common/buffer_view.hpp" #include "crypto/crypto_store/key_type.hpp" #include "primitives/author_api_primitives.hpp" #include "primitives/transaction_validity.hpp" @@ -25,6 +26,7 @@ namespace kagome::api { protected: using Hash256 = common::Hash256; using Buffer = common::Buffer; + using BufferView = common::BufferView; using Extrinsic = primitives::Extrinsic; using SubscriptionId = primitives::SubscriptionId; using ExtrinsicKey = primitives::ExtrinsicKey; @@ -50,10 +52,9 @@ namespace kagome::api { * @param seed The seed (suri) in binary * @param public_key The public key in binary */ - virtual outcome::result insertKey( - crypto::KeyType key_type, - const std::span &seed, - const std::span &public_key) = 0; + virtual outcome::result insertKey(crypto::KeyType key_type, + const BufferView &seed, + const BufferView &public_key) = 0; /** * @brief Generate new session keys and @@ -69,8 +70,7 @@ namespace kagome::api { * @return returns true if all private keys could be found, false if * otherwise */ - virtual outcome::result hasSessionKeys( - const std::span &keys) = 0; + virtual outcome::result hasSessionKeys(const BufferView &keys) = 0; /** * @brief checks if the keystore has private keys for the given public @@ -78,9 +78,8 @@ namespace kagome::api { * @param public_key The public key in binary * @param key_type The key type */ - virtual outcome::result hasKey( - const std::span &public_key, - crypto::KeyType key_type) = 0; + virtual outcome::result hasKey(const BufferView &public_key, + crypto::KeyType key_type) = 0; /** * @return collection of pending extrinsics diff --git a/core/api/service/author/impl/author_api_impl.cpp b/core/api/service/author/impl/author_api_impl.cpp index fa7b2a9188..572bafa25b 100644 --- a/core/api/service/author/impl/author_api_impl.cpp +++ b/core/api/service/author/impl/author_api_impl.cpp @@ -61,10 +61,9 @@ namespace kagome::api { return pool_->submitExtrinsic(source, extrinsic); } - outcome::result AuthorApiImpl::insertKey( - crypto::KeyType key_type_id, - const std::span &seed, - const std::span &public_key) { + outcome::result AuthorApiImpl::insertKey(crypto::KeyType key_type_id, + const BufferView &seed, + const BufferView &public_key) { if (std::find(kKeyTypes.begin(), kKeyTypes.end(), key_type_id) == kKeyTypes.end()) { std::string types; @@ -112,8 +111,7 @@ namespace kagome::api { // logic here is polkadot specific only! // it could be extended by reading config from chainspec palletSession/keys // value - outcome::result AuthorApiImpl::hasSessionKeys( - const std::span &keys) { + outcome::result AuthorApiImpl::hasSessionKeys(const BufferView &keys) { scale::ScaleDecoderStream stream(keys); std::array key; if (keys.size() < 32 || keys.size() > 32 * 6 || (keys.size() % 32) != 0) { @@ -142,8 +140,8 @@ namespace kagome::api { return false; } - outcome::result AuthorApiImpl::hasKey( - const std::span &public_key, crypto::KeyType key_type) { + outcome::result AuthorApiImpl::hasKey(const BufferView &public_key, + crypto::KeyType key_type) { auto res = key_store_->searchForPhrase(key_type, public_key); if (not res) { return res.error(); diff --git a/core/api/service/author/impl/author_api_impl.hpp b/core/api/service/author/impl/author_api_impl.hpp index 9607f0675c..dc0a2a6bb3 100644 --- a/core/api/service/author/impl/author_api_impl.hpp +++ b/core/api/service/author/impl/author_api_impl.hpp @@ -82,17 +82,15 @@ namespace kagome::api { TransactionSource source, const primitives::Extrinsic &extrinsic) override; - outcome::result insertKey( - crypto::KeyType key_type, - const std::span &seed, - const std::span &public_key) override; + outcome::result insertKey(crypto::KeyType key_type, + const BufferView &seed, + const BufferView &public_key) override; outcome::result rotateKeys() override; - outcome::result hasSessionKeys( - const std::span &keys) override; + outcome::result hasSessionKeys(const BufferView &keys) override; - outcome::result hasKey(const std::span &public_key, + outcome::result hasKey(const BufferView &public_key, crypto::KeyType key_type) override; outcome::result> pendingExtrinsics() diff --git a/core/authority_discovery/publisher/address_publisher.cpp b/core/authority_discovery/publisher/address_publisher.cpp index 65ccb7a55b..506760c496 100644 --- a/core/authority_discovery/publisher/address_publisher.cpp +++ b/core/authority_discovery/publisher/address_publisher.cpp @@ -10,7 +10,8 @@ #include "crypto/sha/sha256.hpp" -#define _PB_SPAN(f) [&](std::span a) { (f)(a.data(), a.size()); } +#define _PB_SPAN(f) \ + [&](::kagome::common::BufferView a) { (f)(a.data(), a.size()); } #define PB_SPAN_SET(a, b, c) _PB_SPAN((a).set_##b)(c) #define PB_SPAN_ADD(a, b, c) _PB_SPAN((a).add_##b)(c) diff --git a/core/authority_discovery/query/query_impl.cpp b/core/authority_discovery/query/query_impl.cpp index 2560497fe9..ae45dbb121 100644 --- a/core/authority_discovery/query/query_impl.cpp +++ b/core/authority_discovery/query/query_impl.cpp @@ -7,6 +7,7 @@ #include "authority_discovery/query/query_impl.hpp" #include "authority_discovery/protobuf/authority_discovery.v2.pb.h" +#include "common/buffer_view.hpp" #include "common/bytestr.hpp" #include "crypto/sha/sha256.hpp" diff --git a/core/common/blob.hpp b/core/common/blob.hpp index 069e707ca8..eab9be6335 100644 --- a/core/common/blob.hpp +++ b/core/common/blob.hpp @@ -59,7 +59,7 @@ } \ \ static ::outcome::result fromSpan( \ - const std::span &span) { \ + const common::BufferView &span) { \ OUTCOME_TRY(blob, Base::fromSpan(span)); \ return class_name{std::move(blob)}; \ } \ @@ -202,8 +202,7 @@ namespace kagome::common { * @param buffer * @return */ - static outcome::result> fromSpan( - const std::span &span) { + static outcome::result> fromSpan(const BufferView &span) { if (span.size() != size_) { return BlobError::INCORRECT_LENGTH; } diff --git a/core/common/buffer.hpp b/core/common/buffer.hpp index 2614a4db46..02ba3b8fb7 100644 --- a/core/common/buffer.hpp +++ b/core/common/buffer.hpp @@ -209,7 +209,7 @@ namespace kagome::common { template bool startsWith(const Prefix &prefix) const { if (this->size() >= prefix.size()) { - auto this_view = view().subspan(0, prefix.size()); + auto this_view = view().first(prefix.size()); return std::equal(this_view.begin(), this_view.end(), std::cbegin(prefix), diff --git a/core/common/buffer_back_insert_iterator.hpp b/core/common/buffer_back_insert_iterator.hpp index 06c845b5b8..830677f97b 100644 --- a/core/common/buffer_back_insert_iterator.hpp +++ b/core/common/buffer_back_insert_iterator.hpp @@ -43,7 +43,7 @@ class std::back_insert_iterator> { return *this; } - back_insert_iterator &operator=(std::span s) { + back_insert_iterator &operator=(kagome::common::BufferView s) { buf_.put(s); return *this; } diff --git a/core/common/buffer_or_view.hpp b/core/common/buffer_or_view.hpp index ee8f36eaa4..19b64dd78e 100644 --- a/core/common/buffer_or_view.hpp +++ b/core/common/buffer_or_view.hpp @@ -15,7 +15,7 @@ namespace kagome::common { /// Moved owned buffer or readonly view. class BufferOrView { - using Span = std::span; + using Span = BufferView; template using AsSpan = std::enable_if_t>; diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index e1b555ed07..06991cd583 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -8,7 +8,6 @@ #include -#include "common/bytestr.hpp" #include "common/hexutil.hpp" #include "common/lexicographical_compare_three_way.hpp" #include "macro/endianness_utils.hpp" @@ -38,23 +37,47 @@ namespace kagome::common { BufferView(const span &other) noexcept : span(other) {} + template + requires std::is_integral_v> and (sizeof(T) == 1) + BufferView(std::span other) noexcept + : span(reinterpret_cast(other.data()), other.size()) {} + template decltype(auto) operator=(T &&t) { 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 { - return byte2str(*this); + // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) + return {reinterpret_cast(data()), size()}; } template bool startsWith(const Prefix &prefix) const { if (this->size() >= prefix.size()) { - auto this_view = subspan(0, prefix.size()); + auto this_view = first(prefix.size()); return std::equal(this_view.begin(), this_view.end(), std::cbegin(prefix), diff --git a/core/common/bytestr.hpp b/core/common/bytestr.hpp index 38d8e50b19..30be0639d1 100644 --- a/core/common/bytestr.hpp +++ b/core/common/bytestr.hpp @@ -6,21 +6,28 @@ #pragma once -#include #include #include +#include "common/buffer.hpp" +#include "common/buffer_view.hpp" + namespace kagome { - inline std::span str2byte(const std::span &s) { + + 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 std::span &s) { + inline std::string_view byte2str(const common::BufferView &s) { // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) return {reinterpret_cast(s.data()), s.size()}; } - inline std::vector bytestr_copy(std::span s) { - return {s.begin(), s.end()}; + 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/int_serialization.cpp b/core/common/int_serialization.cpp index d4a916e4ad..8457a9cb8c 100644 --- a/core/common/int_serialization.cpp +++ b/core/common/int_serialization.cpp @@ -28,7 +28,7 @@ namespace kagome::common { } template - inline uint le_bytes_to_uint(std::span bytes) { + inline uint le_bytes_to_uint(BufferView bytes) { BOOST_ASSERT(bytes.size() >= size); uint result; import_bits(result, bytes.begin(), bytes.end(), 8, false); @@ -36,7 +36,7 @@ namespace kagome::common { } template - inline uint be_bytes_to_uint(std::span bytes) { + inline uint be_bytes_to_uint(BufferView bytes) { BOOST_ASSERT(bytes.size() >= size); uint result; import_bits(result, bytes.rbegin(), bytes.rend(), 8, false); @@ -50,7 +50,7 @@ namespace kagome::common { return result; } - uint64_t le_bytes_to_uint64(std::span bytes) { + uint64_t le_bytes_to_uint64(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 8); uint64_t number; memcpy(&number, bytes.data(), 8); @@ -63,7 +63,7 @@ namespace kagome::common { return result; } - uint64_t be_bytes_to_uint64(std::span bytes) { + uint64_t be_bytes_to_uint64(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 8); uint64_t number; memcpy(&number, bytes.data(), 8); @@ -75,8 +75,7 @@ namespace kagome::common { return uint_to_le_bytes<16>(i); } - boost::multiprecision::uint128_t le_bytes_to_uint128( - std::span bytes) { + boost::multiprecision::uint128_t le_bytes_to_uint128(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 16); return le_bytes_to_uint<16, boost::multiprecision::uint128_t>(bytes); } @@ -86,8 +85,7 @@ namespace kagome::common { return uint_to_be_bytes<16>(i); } - boost::multiprecision::uint128_t be_bytes_to_uint128( - std::span bytes) { + boost::multiprecision::uint128_t be_bytes_to_uint128(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 16); return be_bytes_to_uint<16, boost::multiprecision::uint128_t>(bytes); } @@ -97,8 +95,7 @@ namespace kagome::common { return uint_to_le_bytes<32>(i); } - boost::multiprecision::uint256_t le_bytes_to_uint256( - std::span bytes) { + boost::multiprecision::uint256_t le_bytes_to_uint256(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 32); return le_bytes_to_uint<32, boost::multiprecision::uint256_t>(bytes); } @@ -108,8 +105,7 @@ namespace kagome::common { return uint_to_be_bytes<32>(i); } - boost::multiprecision::uint256_t be_bytes_to_uint256( - std::span bytes) { + boost::multiprecision::uint256_t be_bytes_to_uint256(BufferView bytes) { BOOST_ASSERT(bytes.size() >= 32); return be_bytes_to_uint<32, boost::multiprecision::uint256_t>(bytes); } diff --git a/core/common/int_serialization.hpp b/core/common/int_serialization.hpp index 8d97e25d3a..94198338bf 100644 --- a/core/common/int_serialization.hpp +++ b/core/common/int_serialization.hpp @@ -7,29 +7,32 @@ #pragma once #include + #include +#include "common/buffer_view.hpp" + namespace kagome::common { using uint128_t = boost::multiprecision::uint128_t; using uint256_t = boost::multiprecision::uint256_t; std::array uint64_to_le_bytes(uint64_t number); - uint64_t le_bytes_to_uint64(std::span bytes); + uint64_t le_bytes_to_uint64(BufferView bytes); std::array uint64_to_be_bytes(uint64_t number); - uint64_t be_bytes_to_uint64(std::span bytes); + uint64_t be_bytes_to_uint64(BufferView bytes); std::array uint128_to_le_bytes(const uint128_t &i); - uint128_t le_bytes_to_uint128(std::span bytes); + uint128_t le_bytes_to_uint128(BufferView bytes); std::array uint128_to_be_bytes(const uint128_t &i); - uint128_t be_bytes_to_uint128(std::span bytes); + uint128_t be_bytes_to_uint128(BufferView bytes); std::array uint256_to_le_bytes(const uint256_t &i); - uint256_t le_bytes_to_uint256(std::span bytes); + uint256_t le_bytes_to_uint256(BufferView bytes); std::array uint256_to_be_bytes(const uint256_t &i); - uint256_t be_bytes_to_uint256(std::span bytes); + uint256_t be_bytes_to_uint256(BufferView bytes); } // namespace kagome::common diff --git a/core/consensus/babe/impl/babe_digests_util.cpp b/core/consensus/babe/impl/babe_digests_util.cpp index 915826ecbd..8a09505762 100644 --- a/core/consensus/babe/impl/babe_digests_util.cpp +++ b/core/consensus/babe/impl/babe_digests_util.cpp @@ -40,8 +40,7 @@ namespace kagome::consensus::babe { } const auto &digests = block_header.digest; - for (const auto &digest : - std::span(digests).subspan(0, digests.size() - 1)) { + for (const auto &digest : std::span(digests).first(digests.size() - 1)) { auto pre_runtime_opt = getFromVariant(digest); if (pre_runtime_opt.has_value()) { auto babe_block_header_res = diff --git a/core/crypto/bip39/bip39_provider.hpp b/core/crypto/bip39/bip39_provider.hpp index 74c53b7d51..fbbc26ee55 100644 --- a/core/crypto/bip39/bip39_provider.hpp +++ b/core/crypto/bip39/bip39_provider.hpp @@ -32,7 +32,7 @@ namespace kagome::crypto { * @return seed bytes */ virtual outcome::result makeSeed( - std::span entropy, std::string_view password) const = 0; + common::BufferView entropy, std::string_view password) const = 0; virtual outcome::result generateSeed( std::string_view mnemonic_phrase) const = 0; diff --git a/core/crypto/bip39/impl/bip39_provider_impl.cpp b/core/crypto/bip39/impl/bip39_provider_impl.cpp index be003804a0..6cbf673b12 100644 --- a/core/crypto/bip39/impl/bip39_provider_impl.cpp +++ b/core/crypto/bip39/impl/bip39_provider_impl.cpp @@ -61,7 +61,7 @@ namespace kagome::crypto { } outcome::result Bip39ProviderImpl::makeSeed( - std::span entropy, std::string_view password) const { + common::BufferView entropy, std::string_view password) const { constexpr size_t iterations_count = 2048u; constexpr auto default_salt = "mnemonic"; diff --git a/core/crypto/bip39/impl/bip39_provider_impl.hpp b/core/crypto/bip39/impl/bip39_provider_impl.hpp index 3ae03f8bf2..cc7bb0fb30 100644 --- a/core/crypto/bip39/impl/bip39_provider_impl.hpp +++ b/core/crypto/bip39/impl/bip39_provider_impl.hpp @@ -7,8 +7,8 @@ #pragma once #include "crypto/bip39/bip39_provider.hpp" -#include "crypto/bip39/dictionary.hpp" +#include "crypto/bip39/dictionary.hpp" #include "crypto/hasher.hpp" #include "crypto/pbkdf2/pbkdf2_provider.hpp" #include "log/logger.hpp" @@ -25,8 +25,7 @@ namespace kagome::crypto { const std::vector &word_list) const override; outcome::result makeSeed( - std::span entropy, - std::string_view password) const override; + common::BufferView entropy, std::string_view password) const override; outcome::result generateSeed( std::string_view mnemonic_phrase) const override; diff --git a/core/crypto/crypto_store/crypto_suites.hpp b/core/crypto/crypto_store/crypto_suites.hpp index feb4be7aee..369b06ceea 100644 --- a/core/crypto/crypto_store/crypto_suites.hpp +++ b/core/crypto/crypto_store/crypto_suites.hpp @@ -65,13 +65,13 @@ namespace kagome::crypto { * Create a public key from its bytes */ virtual outcome::result toPublicKey( - std::span bytes) const noexcept = 0; + common::BufferView bytes) const noexcept = 0; /** * Create a seed from its bytes */ virtual outcome::result toSeed( - std::span bytes) const noexcept = 0; + common::BufferView bytes) const noexcept = 0; }; class EcdsaSuite : public CryptoSuite toPublicKey( - std::span bytes) const noexcept override { + common::BufferView bytes) const noexcept override { OUTCOME_TRY(blob, EcdsaPublicKey::fromSpan(bytes)); return EcdsaPublicKey{blob}; } outcome::result toSeed( - std::span bytes) const noexcept override { + common::BufferView bytes) const noexcept override { return EcdsaSeed::fromSpan(bytes); } @@ -146,13 +146,13 @@ namespace kagome::crypto { } outcome::result toPublicKey( - std::span bytes) const noexcept override { + common::BufferView bytes) const noexcept override { OUTCOME_TRY(blob, Ed25519PublicKey::fromSpan(bytes)); return Ed25519PublicKey{blob}; } outcome::result toSeed( - std::span bytes) const noexcept override { + common::BufferView bytes) const noexcept override { return Ed25519Seed::fromSpan(bytes); } @@ -189,13 +189,13 @@ namespace kagome::crypto { } outcome::result toPublicKey( - std::span bytes) const noexcept override { + common::BufferView bytes) const noexcept override { OUTCOME_TRY(blob, Sr25519PublicKey::fromSpan(bytes)); return Sr25519PublicKey{std::move(blob)}; } outcome::result toSeed( - std::span bytes) const noexcept override { + common::BufferView bytes) const noexcept override { return Sr25519Seed::fromSpan(bytes); } diff --git a/core/crypto/crypto_store/key_file_storage.cpp b/core/crypto/crypto_store/key_file_storage.cpp index 807bf53931..97958c830d 100644 --- a/core/crypto/crypto_store/key_file_storage.cpp +++ b/core/crypto/crypto_store/key_file_storage.cpp @@ -62,14 +62,14 @@ namespace kagome::crypto { } KeyFileStorage::Path KeyFileStorage::composeKeyPath( - KeyType key_type, std::span public_key) const { + KeyType key_type, common::BufferView public_key) const { return keystore_path_ / encodeKeyFileName(key_type, public_key); } outcome::result KeyFileStorage::saveKeyPair( KeyType type, - std::span public_key, - std::span seed) const { + common::BufferView public_key, + common::BufferView seed) const { auto &&path = composeKeyPath(type, public_key); OUTCOME_TRY(saveKeyHexAtPath(seed, path)); SL_TRACE(logger_, @@ -110,8 +110,7 @@ namespace kagome::crypto { } outcome::result KeyFileStorage::saveKeyHexAtPath( - std::span private_key, - const KeyFileStorage::Path &path) const { + common::BufferView private_key, const KeyFileStorage::Path &path) const { std::ofstream file; file.open(path.native(), std::ios::out | std::ios::trunc); if (!file.is_open()) { @@ -154,7 +153,7 @@ namespace kagome::crypto { } outcome::result> KeyFileStorage::searchForPhrase( - KeyType type, std::span public_key_bytes) const { + KeyType type, common::BufferView public_key_bytes) const { auto key_path = composeKeyPath(type, public_key_bytes); namespace fs = filesystem; std::error_code ec{}; diff --git a/core/crypto/crypto_store/key_file_storage.hpp b/core/crypto/crypto_store/key_file_storage.hpp index ceec895ba0..a787bfef40 100644 --- a/core/crypto/crypto_store/key_file_storage.hpp +++ b/core/crypto/crypto_store/key_file_storage.hpp @@ -55,15 +55,15 @@ namespace kagome::crypto { * returns its content if it's a valid hex blob or mnemonic phrase json. */ outcome::result> searchForPhrase( - KeyType type, std::span public_key_bytes) const; + KeyType type, common::BufferView public_key_bytes) const; /** * Stores the \param seed that generates the \param public_key to the key * storage */ outcome::result saveKeyPair(KeyType type, - std::span public_key, - std::span seed) const; + common::BufferView public_key, + common::BufferView seed) const; /** * Save key as hex to the specific path. @@ -72,7 +72,7 @@ namespace kagome::crypto { * @param file_path - user-provided path to create the file * @return an error if any */ - outcome::result saveKeyHexAtPath(std::span private_key, + outcome::result saveKeyHexAtPath(common::BufferView private_key, const Path &path) const; private: @@ -83,8 +83,7 @@ namespace kagome::crypto { outcome::result> parseKeyFileName( std::string_view file_name) const; - Path composeKeyPath(KeyType key_type, - std::span public_key) const; + Path composeKeyPath(KeyType key_type, common::BufferView public_key) const; Path keystore_path_; log::Logger logger_; diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.cpp b/core/crypto/ecdsa/ecdsa_provider_impl.cpp index 6c8a623cf5..f92d53cc3d 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.cpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.cpp @@ -65,7 +65,7 @@ namespace kagome::crypto { } outcome::result EcdsaProviderImpl::sign( - std::span message, const EcdsaPrivateKey &key) const { + common::BufferView message, const EcdsaPrivateKey &key) const { return signPrehashed(hasher_->blake2b_256(message), key); } @@ -93,7 +93,7 @@ namespace kagome::crypto { } outcome::result EcdsaProviderImpl::verify( - std::span message, + common::BufferView message, const EcdsaSignature &signature, const EcdsaPublicKey &publicKey) const { return verifyPrehashed(hasher_->blake2b_256(message), signature, publicKey); diff --git a/core/crypto/ecdsa/ecdsa_provider_impl.hpp b/core/crypto/ecdsa/ecdsa_provider_impl.hpp index 03979ddde2..515d3c04ad 100644 --- a/core/crypto/ecdsa/ecdsa_provider_impl.hpp +++ b/core/crypto/ecdsa/ecdsa_provider_impl.hpp @@ -31,15 +31,14 @@ namespace kagome::crypto { const EcdsaSeed &seed, Junctions junctions) const override; outcome::result sign( - std::span message, - const EcdsaPrivateKey &key) const override; + common::BufferView message, const EcdsaPrivateKey &key) const override; outcome::result signPrehashed( const EcdsaPrehashedMessage &message, const EcdsaPrivateKey &key) const override; outcome::result verify( - std::span message, + common::BufferView message, const EcdsaSignature &signature, const EcdsaPublicKey &publicKey) const override; diff --git a/core/crypto/ecdsa_provider.hpp b/core/crypto/ecdsa_provider.hpp index c70cff8757..415797f40a 100644 --- a/core/crypto/ecdsa_provider.hpp +++ b/core/crypto/ecdsa_provider.hpp @@ -21,14 +21,14 @@ namespace kagome::crypto { const EcdsaSeed &seed, Junctions junctions) const = 0; virtual outcome::result sign( - std::span message, const EcdsaPrivateKey &key) const = 0; + common::BufferView message, const EcdsaPrivateKey &key) const = 0; virtual outcome::result signPrehashed( const EcdsaPrehashedMessage &message, const EcdsaPrivateKey &key) const = 0; virtual outcome::result verify( - std::span message, + common::BufferView message, const EcdsaSignature &signature, const EcdsaPublicKey &publicKey) const = 0; diff --git a/core/crypto/ed25519/ed25519_provider_impl.cpp b/core/crypto/ed25519/ed25519_provider_impl.cpp index 50706af5cc..a2835c50b4 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.cpp +++ b/core/crypto/ed25519/ed25519_provider_impl.cpp @@ -53,7 +53,7 @@ namespace kagome::crypto { } outcome::result Ed25519ProviderImpl::sign( - const Ed25519Keypair &keypair, std::span message) const { + const Ed25519Keypair &keypair, common::BufferView message) const { Ed25519Signature sig; std::array keypair_bytes; std::copy(keypair.secret_key.begin(), @@ -74,7 +74,7 @@ namespace kagome::crypto { } outcome::result Ed25519ProviderImpl::verify( const Ed25519Signature &signature, - std::span message, + common::BufferView message, const Ed25519PublicKey &public_key) const { auto res = ed25519_verify(signature.data(), public_key.data(), diff --git a/core/crypto/ed25519/ed25519_provider_impl.hpp b/core/crypto/ed25519/ed25519_provider_impl.hpp index deed896b17..01f029a6e2 100644 --- a/core/crypto/ed25519/ed25519_provider_impl.hpp +++ b/core/crypto/ed25519/ed25519_provider_impl.hpp @@ -28,11 +28,11 @@ namespace kagome::crypto { outcome::result sign( const Ed25519Keypair &keypair, - std::span message) const override; + common::BufferView message) const override; outcome::result verify( const Ed25519Signature &signature, - std::span message, + common::BufferView message, const Ed25519PublicKey &public_key) const override; private: diff --git a/core/crypto/ed25519_provider.hpp b/core/crypto/ed25519_provider.hpp index 7cd2ba96b6..021234a76d 100644 --- a/core/crypto/ed25519_provider.hpp +++ b/core/crypto/ed25519_provider.hpp @@ -34,8 +34,7 @@ namespace kagome::crypto { * @return signed message */ virtual outcome::result sign( - const Ed25519Keypair &keypair, - std::span message) const = 0; + const Ed25519Keypair &keypair, common::BufferView message) const = 0; /** * Verifies that \param message was derived using \param public_key on @@ -43,7 +42,7 @@ namespace kagome::crypto { */ virtual outcome::result verify( const Ed25519Signature &signature, - std::span message, + common::BufferView message, const Ed25519PublicKey &public_key) const = 0; }; } // namespace kagome::crypto diff --git a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp index bc61b4fee7..1ddb5d59e7 100644 --- a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp +++ b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.cpp @@ -11,8 +11,8 @@ namespace kagome::crypto { outcome::result Pbkdf2ProviderImpl::deriveKey( - std::span data, - std::span salt, + common::BufferView data, + common::BufferView salt, size_t iterations, size_t key_length) const { common::Buffer out(key_length, 0); diff --git a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp index e2dc10faf0..c16c1e0ea7 100644 --- a/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp +++ b/core/crypto/pbkdf2/impl/pbkdf2_provider_impl.hpp @@ -14,8 +14,8 @@ namespace kagome::crypto { public: ~Pbkdf2ProviderImpl() override = default; - outcome::result deriveKey(std::span data, - std::span salt, + outcome::result deriveKey(common::BufferView data, + common::BufferView salt, size_t iterations, size_t key_length) const override; }; diff --git a/core/crypto/pbkdf2/pbkdf2_provider.hpp b/core/crypto/pbkdf2/pbkdf2_provider.hpp index eb96600645..e9f021fb3b 100644 --- a/core/crypto/pbkdf2/pbkdf2_provider.hpp +++ b/core/crypto/pbkdf2/pbkdf2_provider.hpp @@ -8,6 +8,7 @@ #include #include "common/buffer.hpp" +#include "common/buffer_view.hpp" #include "outcome/outcome.hpp" namespace kagome::crypto { @@ -30,8 +31,8 @@ namespace kagome::crypto { * @return derived key */ virtual outcome::result deriveKey( - std::span data, - std::span salt, + common::BufferView data, + common::BufferView salt, size_t iterations, size_t key_length) const = 0; }; diff --git a/core/crypto/sha/sha256.cpp b/core/crypto/sha/sha256.cpp index d24f379faa..31b53d3a00 100644 --- a/core/crypto/sha/sha256.cpp +++ b/core/crypto/sha/sha256.cpp @@ -15,7 +15,7 @@ namespace kagome::crypto { {reinterpret_cast(input.data()), input.size()}); } - common::Hash256 sha256(std::span input) { + common::Hash256 sha256(common::BufferView input) { common::Hash256 out; SHA256_CTX ctx; SHA256_Init(&ctx); diff --git a/core/crypto/sha/sha256.hpp b/core/crypto/sha/sha256.hpp index 1e077a675a..d68934040a 100644 --- a/core/crypto/sha/sha256.hpp +++ b/core/crypto/sha/sha256.hpp @@ -24,5 +24,5 @@ namespace kagome::crypto { * @param input to be hashed * @return hashed bytes */ - common::Hash256 sha256(std::span input); + common::Hash256 sha256(common::BufferView input); } // namespace kagome::crypto diff --git a/core/crypto/sr25519/sr25519_provider_impl.cpp b/core/crypto/sr25519/sr25519_provider_impl.cpp index c89eb80b08..c77457a2c6 100644 --- a/core/crypto/sr25519/sr25519_provider_impl.cpp +++ b/core/crypto/sr25519/sr25519_provider_impl.cpp @@ -33,7 +33,7 @@ namespace kagome::crypto { } outcome::result Sr25519ProviderImpl::sign( - const Sr25519Keypair &keypair, std::span message) const { + const Sr25519Keypair &keypair, common::BufferView message) const { Sr25519Signature signature{}; try { @@ -51,7 +51,7 @@ namespace kagome::crypto { outcome::result Sr25519ProviderImpl::verify_deprecated( const Sr25519Signature &signature, - std::span message, + common::BufferView message, const Sr25519PublicKey &public_key) const { bool result = false; try { @@ -65,7 +65,7 @@ namespace kagome::crypto { outcome::result Sr25519ProviderImpl::verify( const Sr25519Signature &signature, - std::span message, + common::BufferView message, const Sr25519PublicKey &public_key) const { bool result = false; try { diff --git a/core/crypto/sr25519/sr25519_provider_impl.hpp b/core/crypto/sr25519/sr25519_provider_impl.hpp index 272332801f..2f5f5161bf 100644 --- a/core/crypto/sr25519/sr25519_provider_impl.hpp +++ b/core/crypto/sr25519/sr25519_provider_impl.hpp @@ -17,16 +17,16 @@ namespace kagome::crypto { outcome::result sign( const Sr25519Keypair &keypair, - std::span message) const override; + common::BufferView message) const override; outcome::result verify_deprecated( const Sr25519Signature &signature, - std::span message, + common::BufferView message, const Sr25519PublicKey &public_key) const override; outcome::result verify( const Sr25519Signature &signature, - std::span message, + common::BufferView message, const Sr25519PublicKey &public_key) const override; }; diff --git a/core/crypto/sr25519_provider.hpp b/core/crypto/sr25519_provider.hpp index dab4768a63..5d7cb049e5 100644 --- a/core/crypto/sr25519_provider.hpp +++ b/core/crypto/sr25519_provider.hpp @@ -42,8 +42,7 @@ namespace kagome::crypto { * @return signed message */ virtual outcome::result sign( - const Sr25519Keypair &keypair, - std::span message) const = 0; + const Sr25519Keypair &keypair, common::BufferView message) const = 0; /** * Verifies that \param message was derived using \param public_key on @@ -51,12 +50,12 @@ namespace kagome::crypto { */ virtual outcome::result verify( const Sr25519Signature &signature, - std::span message, + common::BufferView message, const Sr25519PublicKey &public_key) const = 0; virtual outcome::result verify_deprecated( const Sr25519Signature &signature, - std::span message, + common::BufferView message, const Sr25519PublicKey &public_key) const = 0; }; } // namespace kagome::crypto diff --git a/core/crypto/twox/twox.cpp b/core/crypto/twox/twox.cpp index f386390900..6ecb3272cb 100644 --- a/core/crypto/twox/twox.cpp +++ b/core/crypto/twox/twox.cpp @@ -17,7 +17,7 @@ namespace kagome::crypto { ptr[0] = XXH64(in, len, 0); } - common::Hash64 make_twox64(std::span buf) { + common::Hash64 make_twox64(common::BufferView buf) { common::Hash64 hash{}; make_twox64(buf.data(), buf.size(), hash.data()); return hash; @@ -32,7 +32,7 @@ namespace kagome::crypto { ptr[1] = XXH64(in, len, 1); } - common::Hash128 make_twox128(std::span buf) { + common::Hash128 make_twox128(common::BufferView buf) { common::Hash128 hash{}; make_twox128(buf.data(), buf.size(), hash.data()); return hash; @@ -51,7 +51,7 @@ namespace kagome::crypto { ptr[3] = XXH64(in, len, 3); } - common::Hash256 make_twox256(std::span buf) { + common::Hash256 make_twox256(common::BufferView buf) { common::Hash256 hash{}; make_twox256(buf.data(), buf.size(), hash.data()); return hash; diff --git a/core/crypto/twox/twox.hpp b/core/crypto/twox/twox.hpp index 86f028ad51..f10508fcf5 100644 --- a/core/crypto/twox/twox.hpp +++ b/core/crypto/twox/twox.hpp @@ -12,10 +12,10 @@ namespace kagome::crypto { // TODO(warchant): PRE-357 refactor to span - common::Hash64 make_twox64(std::span buf); + common::Hash64 make_twox64(common::BufferView buf); - common::Hash128 make_twox128(std::span buf); + common::Hash128 make_twox128(common::BufferView buf); - common::Hash256 make_twox256(std::span buf); + common::Hash256 make_twox256(common::BufferView buf); } // namespace kagome::crypto diff --git a/core/host_api/impl/child_storage_extension.cpp b/core/host_api/impl/child_storage_extension.cpp index b61f39657b..5ad3f4e338 100644 --- a/core/host_api/impl/child_storage_extension.cpp +++ b/core/host_api/impl/child_storage_extension.cpp @@ -340,14 +340,14 @@ namespace kagome::host_api { common::BufferView data = data_opt.value(); data = data.subspan(std::min(offset, data.size())); auto written = std::min(data.size(), value_size); - memory.storeBuffer(value_ptr, data.subspan(0, written)); + memory.storeBuffer(value_ptr, data.first(written)); res = data.size(); SL_TRACE_FUNC_CALL(logger_, data, child_key_buffer, key, - common::Buffer{data.subspan(0, written)}); + common::Buffer{data.first(written)}); } else { SL_TRACE_FUNC_CALL(logger_, std::string_view{"none"}, diff --git a/core/host_api/impl/storage_extension.cpp b/core/host_api/impl/storage_extension.cpp index cdfa4aeddf..96e5a2e8b1 100644 --- a/core/host_api/impl/storage_extension.cpp +++ b/core/host_api/impl/storage_extension.cpp @@ -68,11 +68,11 @@ namespace kagome::host_api { common::BufferView data = *data_opt; data = data.subspan(std::min(offset, data.size())); auto written = std::min(data.size(), value.size); - memory.storeBuffer(value.ptr, data.subspan(0, written)); + memory.storeBuffer(value.ptr, data.first(written)); res = data.size(); SL_TRACE_FUNC_CALL( - logger_, data, key, common::Buffer{data.subspan(0, written)}); + logger_, data, key, common::Buffer{data.first(written)}); } else { SL_TRACE_FUNC_CALL( logger_, std::string_view{"none"}, key, value_out, offset); diff --git a/core/network/adapters/protobuf_block_response.hpp b/core/network/adapters/protobuf_block_response.hpp index b1329e90ea..fd488b75a5 100644 --- a/core/network/adapters/protobuf_block_response.hpp +++ b/core/network/adapters/protobuf_block_response.hpp @@ -8,6 +8,7 @@ #include "network/adapters/protobuf.hpp" +#include "common/bytestr.hpp" #include "network/protobuf/api.v1.pb.h" #include "network/types/blocks_response.hpp" #include "scale/scale.hpp" @@ -157,7 +158,7 @@ namespace kagome::network { if (const auto &buffer = std::forward(f)(); !buffer.empty()) { OUTCOME_TRY( decoded, - scale::decode(std::span( + scale::decode(common::BufferView( reinterpret_cast(buffer.data()), // NOLINT buffer.size()))); return decoded; diff --git a/core/network/helpers/stream_proxy_base.hpp b/core/network/helpers/stream_proxy_base.hpp index 277a4bf895..52da382250 100644 --- a/core/network/helpers/stream_proxy_base.hpp +++ b/core/network/helpers/stream_proxy_base.hpp @@ -34,14 +34,10 @@ namespace libp2p::connection { stream->deferReadCallback(res, std::move(cb)); } - void write(std::span in, - size_t bytes, - WriteCallbackFunc cb) override { + void write(BytesIn in, size_t bytes, WriteCallbackFunc cb) override { stream->write(in, bytes, std::move(cb)); } - void writeSome(std::span in, - size_t bytes, - WriteCallbackFunc cb) override { + void writeSome(BytesIn in, size_t bytes, WriteCallbackFunc cb) override { stream->writeSome(in, bytes, std::move(cb)); } void deferWriteCallback(std::error_code ec, WriteCallbackFunc cb) override { diff --git a/core/network/helpers/stream_read_buffer.hpp b/core/network/helpers/stream_read_buffer.hpp index 0ede2ca11e..814c697568 100644 --- a/core/network/helpers/stream_read_buffer.hpp +++ b/core/network/helpers/stream_read_buffer.hpp @@ -157,16 +157,12 @@ namespace kagome::network { stream_->deferReadCallback(std::move(res), std::move(cb)); } - void write(std::span in, - size_t bytes, - WriteCallbackFunc cb) { + void write(libp2p::BytesIn in, size_t bytes, WriteCallbackFunc cb) { check(); stream_->write(in, bytes, std::move(cb)); } - void writeSome(std::span in, - size_t bytes, - WriteCallbackFunc cb) { + void writeSome(libp2p::BytesIn in, size_t bytes, WriteCallbackFunc cb) { check(); stream_->writeSome(in, bytes, std::move(cb)); } diff --git a/core/network/notifications/handshake.hpp b/core/network/notifications/handshake.hpp index f8106d1b50..2fa4837649 100644 --- a/core/network/notifications/handshake.hpp +++ b/core/network/notifications/handshake.hpp @@ -17,7 +17,7 @@ namespace kagome::network::notifications { template void handshakeRaw(std::shared_ptr stream, std::shared_ptr frame_stream, - std::span handshake, + common::BufferView handshake, OnHandhake on_handshake) { auto cb = [stream = std::move(stream), frame_stream, diff --git a/core/primitives/block_header.hpp b/core/primitives/block_header.hpp index 35ab1b7766..7e05543681 100644 --- a/core/primitives/block_header.hpp +++ b/core/primitives/block_header.hpp @@ -82,7 +82,7 @@ namespace kagome::primitives { : BlockHeaderReflection(origin) { BOOST_ASSERT_MSG(number == 0 or not digest.empty(), "Non-genesis block must have at least Seal digest"); - digest = digest.subspan(0, digest.size() - 1); + digest = digest.first(digest.size() - 1); } explicit UnsealedBlockHeaderReflection(const BlockHeader &origin) : UnsealedBlockHeaderReflection(BlockHeaderReflection(origin)) {} diff --git a/core/runtime/binaryen/module/module_instance_impl.cpp b/core/runtime/binaryen/module/module_instance_impl.cpp index 0216f685b7..9dd93d6ae1 100644 --- a/core/runtime/binaryen/module/module_instance_impl.cpp +++ b/core/runtime/binaryen/module/module_instance_impl.cpp @@ -173,7 +173,7 @@ namespace kagome::runtime::binaryen { throw std::runtime_error("invalid offset when initializing memory"); } callback(offset, - std::span( + common::BufferView( reinterpret_cast(segment.data.data()), segment.data.size())); } diff --git a/core/runtime/wavm/core_api_factory_impl.cpp b/core/runtime/wavm/core_api_factory_impl.cpp index 0a6ed94d38..2b34fd8260 100644 --- a/core/runtime/wavm/core_api_factory_impl.cpp +++ b/core/runtime/wavm/core_api_factory_impl.cpp @@ -31,7 +31,7 @@ namespace kagome::runtime::wavm { std::shared_ptr module_params, std::shared_ptr intrinsic_module, std::shared_ptr instance_env_factory, - std::span code, + common::BufferView code, const common::Hash256 &code_hash, std::shared_ptr last_compiled_module) : instance_env_factory_{std::move(instance_env_factory)}, @@ -69,7 +69,7 @@ namespace kagome::runtime::wavm { std::shared_ptr compartment_; std::shared_ptr module_params_; std::shared_ptr intrinsic_module_; - std::span code_; + common::BufferView code_; const common::Hash256 code_hash_; std::shared_ptr last_compiled_module_; }; diff --git a/core/runtime/wavm/module.cpp b/core/runtime/wavm/module.cpp index 547f3decc0..1f3dda225c 100644 --- a/core/runtime/wavm/module.cpp +++ b/core/runtime/wavm/module.cpp @@ -26,7 +26,7 @@ namespace kagome::runtime::wavm { ModuleParams &module_params, std::shared_ptr intrinsic_module, std::shared_ptr env_factory, - std::span code, + common::BufferView code, const common::Hash256 &code_hash) { std::shared_ptr module = nullptr; WAVM::WASM::LoadError loadError; diff --git a/core/runtime/wavm/module.hpp b/core/runtime/wavm/module.hpp index 2a33f5de13..70c172d3a3 100644 --- a/core/runtime/wavm/module.hpp +++ b/core/runtime/wavm/module.hpp @@ -36,7 +36,7 @@ namespace kagome::runtime::wavm { ModuleParams &module_params, std::shared_ptr intrinsic_module, std::shared_ptr env_factory, - std::span code, + common::BufferView code, const common::Hash256 &code_hash); outcome::result> instantiate() diff --git a/core/storage/rocksdb/rocksdb_util.hpp b/core/storage/rocksdb/rocksdb_util.hpp index 3e468249bc..162fbc9120 100644 --- a/core/storage/rocksdb/rocksdb_util.hpp +++ b/core/storage/rocksdb/rocksdb_util.hpp @@ -44,7 +44,7 @@ namespace kagome::storage { return rocksdb::Slice{ptr, n}; } - inline std::span make_span(const rocksdb::Slice &s) { + inline BufferView make_span(const rocksdb::Slice &s) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) return {reinterpret_cast(s.data()), s.size()}; } 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 64841940a4..a36bf4a60e 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp @@ -121,7 +121,7 @@ namespace kagome::storage::trie { } outcome::result PolkadotTrieCursorImpl::seekLowerBoundInternal( - const TrieNode ¤t, std::span sought_nibbles) { + const TrieNode ¤t, BufferView sought_nibbles) { BOOST_ASSERT(isValid()); auto [sought_nibbles_mismatch, current_mismatch] = std::mismatch(sought_nibbles.begin(), 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 219cdd5b29..e72b9c4838 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.hpp @@ -67,8 +67,8 @@ namespace kagome::storage::trie { [[nodiscard]] std::optional value() const override; private: - outcome::result seekLowerBoundInternal( - const TrieNode ¤t, std::span left_nibbles); + outcome::result seekLowerBoundInternal(const TrieNode ¤t, + BufferView left_nibbles); outcome::result nextNodeWithValueInOuterTree(); outcome::result nextNodeWithValueInSubTree( const TrieNode &subtree_root); diff --git a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp index 15b61eb12a..6ab7f59bd8 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_impl.cpp @@ -400,7 +400,7 @@ namespace kagome::storage::trie { return node; } - br->setKeyNibbles(KeyNibbles{key_nibbles.subspan(0, length)}); + br->setKeyNibbles(KeyNibbles{key_nibbles.first(length)}); auto parentKey = parent->getKeyNibbles(); // value goes at this branch @@ -455,8 +455,8 @@ namespace kagome::storage::trie { parent->children.at(key_nibbles[length]) = node; return parent; } - auto br = std::make_shared( - KeyNibbles{key_nibbles.subspan(0, length)}); + auto br = + std::make_shared(KeyNibbles{key_nibbles.first(length)}); auto parentIdx = parent->getKeyNibbles()[length]; OUTCOME_TRY( new_branch, diff --git a/core/storage/trie/serialization/buffer_stream.hpp b/core/storage/trie/serialization/buffer_stream.hpp index 6f82546938..5d1d8a09dc 100644 --- a/core/storage/trie/serialization/buffer_stream.hpp +++ b/core/storage/trie/serialization/buffer_stream.hpp @@ -17,12 +17,10 @@ namespace kagome::storage::trie { * future, when one appears */ class BufferStream { - using index_type = std::span::size_type; - public: - explicit BufferStream(std::span buf) : data_{buf} {} + explicit BufferStream(common::BufferView buf) : data_{buf} {} - bool hasMore(index_type num_bytes) const { + bool hasMore(size_t num_bytes) const { return data_.size() >= num_bytes; } @@ -31,15 +29,15 @@ namespace kagome::storage::trie { throw std::out_of_range("Data is out"); } auto byte = data_[0]; - data_ = data_.last(data_.size() - 1); + data_.dropFirst(1); return byte; } - std::span leftBytes() const { + common::BufferView leftBytes() const { return data_; } private: - std::span data_; + common::BufferView data_; }; } // namespace kagome::storage::trie diff --git a/core/utils/storage_explorer.cpp b/core/utils/storage_explorer.cpp index c1928dbc62..21a710c245 100644 --- a/core/utils/storage_explorer.cpp +++ b/core/utils/storage_explorer.cpp @@ -574,7 +574,7 @@ int storage_explorer_main(int argc, const char **argv) { parser.addCommand(std::make_unique( block_storage, trie_storage, authority_manager, hasher)); - parser.invoke(args.subspan(0, kagome_args_start)); + parser.invoke(args.first(kagome_args_start)); return 0; } diff --git a/test/core/api/service/payment/payment_api_test.cpp b/test/core/api/service/payment/payment_api_test.cpp index 51b91dec38..2acb0dd62f 100644 --- a/test/core/api/service/payment/payment_api_test.cpp +++ b/test/core/api/service/payment/payment_api_test.cpp @@ -17,6 +17,7 @@ using kagome::api::PaymentApi; using kagome::api::PaymentApiImpl; using kagome::blockchain::BlockTreeMock; using kagome::common::Buffer; +using kagome::common::BufferView; using kagome::primitives::BlockInfo; using kagome::primitives::Extrinsic; using kagome::primitives::OldWeight; @@ -95,7 +96,7 @@ TEST_F(PaymentApiTest, DecodeRuntimeDispatchInfo) { // partialFee: 15.7681 mDOT (157681946) // } TEST_F(PaymentApiTest, DecodeRuntimeDispatchInfoWithFee) { - std::span data{{ + BufferView data{{ 0x42, 0xae, 0x2b, 0x22, 0x00, 0x00, 0x1a, 0x09, 0x66, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }}; diff --git a/test/core/common/buffer_view_test.cpp b/test/core/common/buffer_view_test.cpp index 2e58cb44c4..527a942eaf 100644 --- a/test/core/common/buffer_view_test.cpp +++ b/test/core/common/buffer_view_test.cpp @@ -9,7 +9,7 @@ #include using namespace kagome::common; -using Span = std::span; +using Span = BufferView; TEST(BufferView, Constructor_default) { BufferView v; diff --git a/test/core/host_api/crypto_extension_test.cpp b/test/core/host_api/crypto_extension_test.cpp index c1f5c928b5..50b3c7dd88 100644 --- a/test/core/host_api/crypto_extension_test.cpp +++ b/test/core/host_api/crypto_extension_test.cpp @@ -796,9 +796,8 @@ TEST_F(CryptoExtensionTest, Sr25519SignSuccess) { EXPECT_CALL( *memory_, - storeBuffer(VerifySr25519Signature(sr25519_provider_, - std::span(input), - sr25519_keypair.public_key))) + storeBuffer(VerifySr25519Signature( + sr25519_provider_, BufferView(input), sr25519_keypair.public_key))) .WillOnce(Return(res)); ASSERT_EQ( diff --git a/test/core/host_api/offchain_extension_test.cpp b/test/core/host_api/offchain_extension_test.cpp index c328ca1865..58203d0a3a 100644 --- a/test/core/host_api/offchain_extension_test.cpp +++ b/test/core/host_api/offchain_extension_test.cpp @@ -229,7 +229,7 @@ TEST_F(OffchainExtensionTest, RandomSeed) { EXPECT_CALL(*offchain_worker_, timestamp()).WillOnce(Return(result)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_result = scale::decode(data).value(); return actual_result == result; }; @@ -333,7 +333,7 @@ TEST_P(TernaryParametrizedTest, LocalStorageGet) { .WillOnce(Return(result)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_result = scale::decode>(data).value(); return actual_result == result_opt; }; @@ -384,7 +384,7 @@ TEST_P(HttpMethodsParametrizedTest, HttpRequestStart) { .WillOnce(Return(result)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_result = scale::decode>(data).value(); return actual_result.isSuccess(); @@ -435,7 +435,7 @@ TEST_F(OffchainExtensionTest, HttpRequestAddHeader) { .WillOnce(Return(result)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_result = scale::decode>(data).value(); return actual_result.isSuccess(); @@ -481,7 +481,7 @@ TEST_F(OffchainExtensionTest, HttpRequestWriteBody) { .WillOnce(Return(result)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_result = scale::decode>(data).value(); return actual_result.isSuccess(); @@ -526,7 +526,7 @@ TEST_F(OffchainExtensionTest, HttpResponseWait) { .WillOnce(Return(result)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_result = scale::decode>(data).value(); return std::equal( actual_result.begin(), actual_result.end(), result.begin()); @@ -556,7 +556,7 @@ TEST_F(OffchainExtensionTest, HttpResponseHeaders) { .WillOnce(Return(headers)); { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_headers = scale::decode>>(data) .value(); @@ -600,7 +600,7 @@ TEST_P(HttpResultParametrizedTest, HttpResponseReadBody) { } { - auto matcher = [&](const std::span &data) { + auto matcher = [&](const BufferView &data) { auto actual_response = scale::decode>(data).value(); return actual_response.isSuccess() == response.isSuccess(); diff --git a/test/core/parachain/pvf_test.cpp b/test/core/parachain/pvf_test.cpp index 7005780285..44bbbb9122 100644 --- a/test/core/parachain/pvf_test.cpp +++ b/test/core/parachain/pvf_test.cpp @@ -27,6 +27,7 @@ #include "testutil/prepare_loggers.hpp" using kagome::common::Buffer; +using kagome::common::BufferView; using kagome::common::Hash256; using kagome::parachain::ParachainRuntime; using kagome::parachain::Pvf; @@ -95,7 +96,7 @@ class PvfTest : public testing::Test { } outcome::result> make_module_mock( - std::span code, const Hash256 &code_hash) { + BufferView code, const Hash256 &code_hash) { auto module = std::make_shared(); auto instance = std::make_shared(); ON_CALL(*module, instantiate()).WillByDefault(Return(instance)); diff --git a/test/core/runtime/storage_code_provider_test.cpp b/test/core/runtime/storage_code_provider_test.cpp index 2c564ba6b0..34a14e61e8 100644 --- a/test/core/runtime/storage_code_provider_test.cpp +++ b/test/core/runtime/storage_code_provider_test.cpp @@ -73,7 +73,7 @@ TEST_F(StorageCodeProviderTest, GetCodeWhenNoStorageUpdates) { wasm_provider->getCodeAt(first_state_root)); // then - ASSERT_TRUE(obtained_state_code == std::span(state_code_)); + ASSERT_TRUE(obtained_state_code == common::BufferView(state_code_)); } /** @@ -120,5 +120,5 @@ TEST_F(StorageCodeProviderTest, DISABLED_GetCodeWhenStorageUpdates) { wasm_provider->getCodeAt(second_state_root)); // then - ASSERT_EQ(obtained_state_code, std::span(state_code_)); + ASSERT_EQ(obtained_state_code, common::BufferView(state_code_)); } diff --git a/test/mock/core/api/service/author/author_api_mock.hpp b/test/mock/core/api/service/author/author_api_mock.hpp index b1cb2b3f1f..2a71390833 100644 --- a/test/mock/core/api/service/author/author_api_mock.hpp +++ b/test/mock/core/api/service/author/author_api_mock.hpp @@ -23,21 +23,19 @@ namespace kagome::api { MOCK_METHOD(outcome::result, insertKey, - (crypto::KeyType, - const std::span &, - const std::span &), + (crypto::KeyType, const BufferView &, const BufferView &), (override)); MOCK_METHOD(outcome::result, rotateKeys, (), (override)); MOCK_METHOD(outcome::result, hasSessionKeys, - (const std::span &), + (const BufferView &), (override)); MOCK_METHOD(outcome::result, hasKey, - (const std::span &, crypto::KeyType), + (const BufferView &, crypto::KeyType), (override)); MOCK_METHOD(outcome::result, diff --git a/test/mock/core/crypto/ecdsa_provider_mock.hpp b/test/mock/core/crypto/ecdsa_provider_mock.hpp index 49a0498e95..333d2d4efd 100644 --- a/test/mock/core/crypto/ecdsa_provider_mock.hpp +++ b/test/mock/core/crypto/ecdsa_provider_mock.hpp @@ -25,14 +25,12 @@ namespace kagome::crypto { MOCK_METHOD(outcome::result, sign, - (std::span, const EcdsaPrivateKey &), + (BufferView, const EcdsaPrivateKey &), (const, override)); MOCK_METHOD(outcome::result, verify, - (std::span, - const EcdsaSignature &, - const EcdsaPublicKey &), + (BufferView, const EcdsaSignature &, const EcdsaPublicKey &), (const, override)); }; diff --git a/test/mock/core/crypto/ed25519_provider_mock.hpp b/test/mock/core/crypto/ed25519_provider_mock.hpp index 57ffcfd2c7..2bf41ed05d 100644 --- a/test/mock/core/crypto/ed25519_provider_mock.hpp +++ b/test/mock/core/crypto/ed25519_provider_mock.hpp @@ -19,13 +19,13 @@ namespace kagome::crypto { MOCK_METHOD(outcome::result, sign, - (const Ed25519Keypair &, std::span), + (const Ed25519Keypair &, common::BufferView), (const, override)); MOCK_METHOD(outcome::result, verify, (const Ed25519Signature &, - std::span, + common::BufferView, const Ed25519PublicKey &), (const, override)); }; diff --git a/test/mock/core/crypto/sr25519_provider_mock.hpp b/test/mock/core/crypto/sr25519_provider_mock.hpp index ec267c8cb0..d7e7384e2b 100644 --- a/test/mock/core/crypto/sr25519_provider_mock.hpp +++ b/test/mock/core/crypto/sr25519_provider_mock.hpp @@ -18,20 +18,20 @@ namespace kagome::crypto { MOCK_METHOD(outcome::result, sign, - (const Sr25519Keypair &, std::span), + (const Sr25519Keypair &, common::BufferView), (const, override)); MOCK_METHOD(outcome::result, verify, (const Sr25519Signature &, - std::span, + common::BufferView, const Sr25519PublicKey &), (const, override)); MOCK_METHOD(outcome::result, verify_deprecated, (const Sr25519Signature &, - std::span, + common::BufferView, const Sr25519PublicKey &), (const, override)); }; diff --git a/test/mock/libp2p/basic/read_writer_mock.hpp b/test/mock/libp2p/basic/read_writer_mock.hpp index b056757a88..477b84610e 100644 --- a/test/mock/libp2p/basic/read_writer_mock.hpp +++ b/test/mock/libp2p/basic/read_writer_mock.hpp @@ -25,12 +25,12 @@ namespace libp2p::basic { MOCK_METHOD(void, write, - (std::span, size_t, Writer::WriteCallbackFunc), + (BytesIn, size_t, Writer::WriteCallbackFunc), (override)); MOCK_METHOD(void, writeSome, - (std::span, size_t, Writer::WriteCallbackFunc), + (BytesIn, size_t, Writer::WriteCallbackFunc), (override)); MOCK_METHOD(void, From ba9db2ff8bc25bc369a6e550a6938ca5b2f3cdfc Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Thu, 26 Oct 2023 17:21:19 +0300 Subject: [PATCH 05/12] update: hunter Signed-off-by: Dmitriy Khaustov aka xDimon --- cmake/Hunter/config.cmake | 13 ++++--------- cmake/Hunter/hunter-gate-url.cmake | 4 ++-- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/cmake/Hunter/config.cmake b/cmake/Hunter/config.cmake index 88a0324633..e3e3c9d48c 100644 --- a/cmake/Hunter/config.cmake +++ b/cmake/Hunter/config.cmake @@ -38,15 +38,10 @@ hunter_config( KEEP_PACKAGE_SOURCES ) -#hunter_config( -# libp2p -# VERSION 0.1.16 -# KEEP_PACKAGE_SOURCES -#) hunter_config( libp2p - URL https://github.com/libp2p/cpp-libp2p/archive/b581ee763c893feb84ebeea4f03e8d3667fbbaf4.tar.gz - SHA1 6be0e175200e13decfe4395bcda5ff311c6c9e5b + VERSION 0.1.17 + KEEP_PACKAGE_SOURCES ) hunter_config( @@ -71,8 +66,8 @@ hunter_config( hunter_config( scale - URL https://github.com/qdrvm/scale-codec-cpp/archive/2a223956d9cc0c78a95848da2fd1be35b2a4bd2d.tar.gz - SHA1 12879475cc5a00f23ad9e660ee8ecbd74b6e16a0 + VERSION 1.1.0 + KEEP_PACKAGE_SOURCES ) # Fix for Apple clang (or clang from brew) of versions 15 and higher diff --git a/cmake/Hunter/hunter-gate-url.cmake b/cmake/Hunter/hunter-gate-url.cmake index c084d305f7..14ea3c1954 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-qdrvm10.tar.gz - SHA1 72b446a4424ba28ea90f9a68a9134b0f8e44b5b2 + URL https://github.com/qdrvm/hunter/archive/refs/tags/v0.23.257-qdrvm11.tar.gz + SHA1 b2a69ae501bdc99006fb86e55930640004468556 LOCAL ) From 8b063c2182769e291a277c63be43701d8d989239 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Wed, 25 Oct 2023 21:24:06 +0300 Subject: [PATCH 06/12] fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon --- .../service/author/impl/author_api_impl.cpp | 3 +- core/api/service/mmr/rpc.cpp | 5 +- .../api/service/state/impl/state_api_impl.cpp | 6 +- core/consensus/sassafras/impl/sassafras.cpp | 547 ------------------ core/network/helpers/stream_proxy_base.hpp | 8 +- core/network/helpers/stream_read_buffer.hpp | 12 +- core/primitives/ss58_codec.cpp | 2 +- core/scale/tie.hpp | 2 + test/mock/libp2p/basic/read_writer_mock.hpp | 4 +- 9 files changed, 16 insertions(+), 573 deletions(-) delete mode 100644 core/consensus/sassafras/impl/sassafras.cpp diff --git a/core/api/service/author/impl/author_api_impl.cpp b/core/api/service/author/impl/author_api_impl.cpp index 572bafa25b..cae39c3827 100644 --- a/core/api/service/author/impl/author_api_impl.cpp +++ b/core/api/service/author/impl/author_api_impl.cpp @@ -126,8 +126,7 @@ namespace kagome::api { crypto::KeyTypes::GRANDPA, crypto::Ed25519PublicKey(common::Blob<32>(key)))) { unsigned count = 1; - while (stream.currentIndex() - < static_cast(keys.size())) { + while (stream.currentIndex() < keys.size()) { stream >> key; if (not store_->findSr25519Keypair( crypto::polkadot_key_order[count++], diff --git a/core/api/service/mmr/rpc.cpp b/core/api/service/mmr/rpc.cpp index 128d70b6c3..2043a8a553 100644 --- a/core/api/service/mmr/rpc.cpp +++ b/core/api/service/mmr/rpc.cpp @@ -143,9 +143,8 @@ namespace kagome::api { OUTCOME_TRY( leaves, scale::decode(proof_raw.leaves)); - OUTCOME_TRY( - proof, - scale::decode(proof_raw.proof.view())); + OUTCOME_TRY(proof, + scale::decode(proof_raw.proof)); OUTCOME_TRY(r, self->mmr_api_.get()->verifyProofStateless( at, mmr_root, leaves, proof)); diff --git a/core/api/service/state/impl/state_api_impl.cpp b/core/api/service/state/impl/state_api_impl.cpp index ed3cee9171..488ed98103 100644 --- a/core/api/service/state/impl/state_api_impl.cpp +++ b/core/api/service/state/impl/state_api_impl.cpp @@ -102,11 +102,7 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!std::equal( - key.value().begin(), - key.value().begin() + std::min(key.value().size(), prefix.size()), - prefix.begin(), - prefix.end())) { + if (!key->startsWith(prefix)) { break; } result.push_back(cursor->key().value()); diff --git a/core/consensus/sassafras/impl/sassafras.cpp b/core/consensus/sassafras/impl/sassafras.cpp deleted file mode 100644 index daf4792517..0000000000 --- a/core/consensus/sassafras/impl/sassafras.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "consensus/sassafras/impl/sassafras.hpp" - -#include -#include - -#include "application/app_configuration.hpp" -#include "blockchain/block_tree.hpp" -#include "consensus/babe/babe_config_repository.hpp" -#include "consensus/sassafras/impl/sassafras_digests_util.hpp" -#include "consensus/sassafras/impl/sassafras_error.hpp" -#include "consensus/sassafras/impl/threshold_util.hpp" -#include "consensus/sassafras/sassafras_config_repository.hpp" -#include "consensus/sassafras/sassafras_lottery.hpp" -#include "consensus/sassafras/types/seal.hpp" -#include "consensus/sassafras/types/slot_claim.hpp" -#include "consensus/timeline/backoff.hpp" -#include "consensus/timeline/impl/block_production_error.hpp" -#include "consensus/timeline/slots_util.hpp" -#include "crypto/crypto_store/session_keys.hpp" -#include "dispute_coordinator/dispute_coordinator.hpp" -#include "metrics/histogram_timer.hpp" -#include "parachain/availability/bitfield/store.hpp" -#include "parachain/backing/store.hpp" -#include "parachain/parachain_inherent_data.hpp" -#include "primitives/digest.hpp" -#include "primitives/inherent_data.hpp" -#include "scale.hpp" - -using namespace std::chrono_literals; - -namespace { - inline const auto kTimestampId = - kagome::primitives::InherentIdentifier::fromString("timstap0").value(); - inline const auto kSlotId = - kagome::primitives::InherentIdentifier::fromString("sassslot").value(); - inline const auto kParachainId = - kagome::primitives::InherentIdentifier::fromString("parachn0").value(); - - /// The maximum allowed number of slots past the expected slot as a delay for - /// block production. This is an intentional relaxation of block dropping algo - // static constexpr auto kMaxBlockSlotsOvertime = 2 - constexpr const char *kIsRelayChainValidator = - "kagome_node_is_active_validator"; - - kagome::metrics::HistogramTimer metric_block_proposal_time{ - "kagome_proposer_block_constructed", - "Time taken to construct new block", - {0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10}, - }; -} // namespace - -namespace kagome::consensus::sassafras { - - Sassafras::Sassafras( - const application::AppConfiguration &app_config, - const clock::SystemClock &clock, - std::shared_ptr block_tree, - LazySPtr slots_util, - std::shared_ptr sassafras_config_repo, - std::shared_ptr session_keys, - std::shared_ptr lottery, - std::shared_ptr bitfield_store, - std::shared_ptr backing_store, - std::shared_ptr dispute_coordinator) - : log_(log::createLogger("Sassafras", "sassafras")), - clock_(clock), - block_tree_(std::move(block_tree)), - slots_util_(std::move(slots_util)), - sassafras_config_repo_(std::move(sassafras_config_repo)), - session_keys_(std::move(session_keys)), - lottery_(std::move(lottery)), - bitfield_store_(std::move(bitfield_store)), - backing_store_(std::move(backing_store)), - dispute_coordinator_(std::move(dispute_coordinator)), - is_validator_by_config_(app_config.roles().flags.authority != 0), - telemetry_{telemetry::createTelemetryService()} { - BOOST_ASSERT(sassafras_config_repo_); - BOOST_ASSERT(session_keys_); - BOOST_ASSERT(lottery_); - BOOST_ASSERT(bitfield_store_); - BOOST_ASSERT(backing_store_); - BOOST_ASSERT(dispute_coordinator_); - - // Register metrics - metrics_registry_->registerGaugeFamily( - kIsRelayChainValidator, - "Tracks if the validator is in the active set. Updates at session " - "boundary."); - metric_is_relaychain_validator_ = - metrics_registry_->registerGaugeMetric(kIsRelayChainValidator); - metric_is_relaychain_validator_->set(false); - } - - ValidatorStatus Sassafras::getValidatorStatus( - const primitives::BlockInfo &block, EpochNumber epoch) const { - auto config = sassafras_config_repo_->config(block, epoch); - if (not config) { - SL_CRITICAL( - log_, - "Can't obtain digest of epoch {} from block tree for block {}", - epoch, - block); - return ValidatorStatus::NonValidator; - } - - const auto &authorities = config.value()->authorities; - if (session_keys_->getSassafrasKeyPair(authorities)) { - if (authorities.size() > 1) { - return ValidatorStatus::Validator; - } - return ValidatorStatus::SingleValidator; - } - - return ValidatorStatus::NonValidator; - } - - std::tuple Sassafras::getTimings() const { - return {sassafras_config_repo_->slotDuration(), - sassafras_config_repo_->epochLength()}; - } - - outcome::result Sassafras::getSlot( - const primitives::BlockHeader &header) const { - return sassafras::getSlot(header); - } - - outcome::result Sassafras::processSlot( - SlotNumber slot, const primitives::BlockInfo &best_block) { - auto slot_timestamp = clock_.now(); - - if (slot != slots_util_.get()->timeToSlot(slot_timestamp)) { - SL_DEBUG(log_, "Slot processing skipped: chance has missed"); - return outcome::success(); - } - OUTCOME_TRY(epoch_number, slots_util_.get()->slotToEpoch(best_block, slot)); - - auto config_res = sassafras_config_repo_->config(best_block, epoch_number); - [[unlikely]] if (not config_res.has_value()) { - SL_ERROR(log_, - "Can not get epoch: {}; Skipping slot processing", - config_res.error()); - return config_res.as_failure(); - } - auto &config = *config_res.value(); - - auto keypair = session_keys_->getBabeKeyPair(config.authorities); - if (not keypair) { - metric_is_relaychain_validator_->set(false); - if (is_validator_by_config_) { - SL_VERBOSE(log_, - "Authority not known, skipping slot processing. " - "Probably authority list has changed."); - } - return BlockProductionError::NO_VALIDATOR; - } - - Context ctx{.parent = best_block, - .epoch = epoch_number, - .slot = slot, - .slot_timestamp = slot_timestamp, - .keypair = std::move(keypair->first)}; - - metric_is_relaychain_validator_->set(true); - const auto &authority_index = keypair->second; - - // If epoch changed, generate and submit their candidate tickets along with - // validity proofs to the blockchain - if (lottery_->getEpoch() != epoch_number) { - // TODO Generate and submit tickets here - changeLotteryEpoch(ctx, epoch_number, authority_index, config); - } - - auto slot_leadership = - lottery_->getSlotLeadership(ctx.parent.hash, ctx.slot); - - if (slot_leadership.has_value()) { - const auto &vrf_result = slot_leadership.value(); - SL_DEBUG(log_, - "Babe author {} is primary slot-leader " - "(vrfOutput: {}, proof: {})", - ctx.keypair->public_key, - common::Buffer(vrf_result.output), - common::Buffer(vrf_result.proof)); - - return processSlotLeadership( - ctx, slot_timestamp, std::cref(vrf_result), authority_index); - } - - SL_TRACE(log_, - "Validator {} is not slot leader in current slot", - ctx.keypair->public_key); - - return BlockProductionError::NO_SLOT_LEADER; - } - - outcome::result Sassafras::calculatePreDigest( - const Context &ctx, - std::optional> output, - primitives::AuthorityIndex authority_index) const { - SlotClaim slot_claim{ - .authority_index = authority_index, - .slot_number = ctx.slot, - .signature = {}, // FIXME - .ticket_claim = {}, // FIXME - }; - - // if (slot_claim.needVRFCheck()) { - // if (not output.has_value()) { - // SL_ERROR( - // log_, - // "VRF proof is required to build block header but was not passed"); - // return BabeError::MISSING_PROOF; - // } - // slot_claim.vrf_output = output.value(); - // } - - auto encoded_slot_claim_res = scale::encode(slot_claim); - if (encoded_slot_claim_res.has_error()) { - SL_ERROR( - log_, "cannot encode SlotClaim: {}", encoded_slot_claim_res.error()); - return encoded_slot_claim_res.error(); - } - common::Buffer encoded_slot_claim{encoded_slot_claim_res.value()}; - - // clang-format on - return primitives::PreRuntime{ - {primitives::kBabeEngineId, encoded_slot_claim}}; - } - - outcome::result Sassafras::sealBlock( - const Context &ctx, const primitives::Block &block) const { - // BOOST_ASSERT(ctx.keypair != nullptr); - // - // // Calculate and save hash, 'cause it's new produced block - // // Note: it is temporary hash significant for signing - // primitives::calculateBlockHash( - // const_cast(block.header), *hasher_); - // - // auto signature_res = - // sr25519_provider_->sign(*ctx.keypair, block.header.hash()); - // if (signature_res.has_value()) { - // Seal seal{.signature = signature_res.value()}; - // auto encoded_seal = common::Buffer(scale::encode(seal).value()); - // return primitives::Seal{{primitives::kBabeEngineId, encoded_seal}}; - // } - // - // SL_ERROR(log_, "Error signing a block seal: {}", signature_res.error()); - // return signature_res.as_failure(); - return primitives::Seal{}; - } - - outcome::result Sassafras::processSlotLeadership( - const Context &ctx, - TimePoint slot_timestamp, - std::optional> output, - primitives::AuthorityIndex authority_index) { - auto parent_header_res = block_tree_->getBlockHeader(ctx.parent.hash); - BOOST_ASSERT_MSG(parent_header_res.has_value(), - "The best block is always known"); - auto &parent_header = parent_header_res.value(); - - if (backoff(*this, - parent_header, - block_tree_->getLastFinalized().number, - ctx.slot)) { - SL_INFO(log_, - "Backing off claiming new slot for block authorship: " - "finality is lagging."); - return BlockProductionError::BACKING_OFF; - } - - BOOST_ASSERT(ctx.keypair != nullptr); - - // build a block to be announced - SL_VERBOSE(log_, - "Obtained slot leadership in slot {} epoch {}", - ctx.slot, - ctx.epoch); - - SL_INFO(log_, "Babe builds block on top of block {}", ctx.parent); - - primitives::InherentData inherent_data; - auto now = std::chrono::duration_cast( - slot_timestamp.time_since_epoch()) - .count(); - - if (auto res = inherent_data.putData(kTimestampId, now); - res.has_error()) { - SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); - return SassafrasError::CAN_NOT_PREPARE_BLOCK; - } - - if (auto res = inherent_data.putData(kSlotId, ctx.slot); res.has_error()) { - SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); - return SassafrasError::CAN_NOT_PREPARE_BLOCK; - } - - parachain::ParachainInherentData parachain_inherent_data; - - { - auto &relay_parent = ctx.parent.hash; - parachain_inherent_data.bitfields = - bitfield_store_->getBitfields(relay_parent); - - parachain_inherent_data.backed_candidates = - backing_store_->get(relay_parent); - SL_TRACE(log_, - "Get backed candidates from store.(count={}, relay_parent={})", - parachain_inherent_data.backed_candidates.size(), - relay_parent); - - parachain_inherent_data.parent_header = std::move(parent_header); - - { // Fill disputes - std::latch latch(1); - dispute_coordinator_->getDisputeForInherentData( - ctx.parent, [&](auto res) { - parachain_inherent_data.disputes = std::move(res); - latch.count_down(); - }); - latch.wait(); - } - } - - if (auto res = inherent_data.putData(kParachainId, parachain_inherent_data); - res.has_error()) { - SL_ERROR(log_, "cannot put an inherent data: {}", res.error()); - return SassafrasError::CAN_NOT_PREPARE_BLOCK; - } - - // clang-format off - -// auto proposal_start = std::chrono::steady_clock::now(); -// // calculate babe_pre_digest -// auto babe_pre_digest_res = -// 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; -// } -// const auto &babe_pre_digest = babe_pre_digest_res.value(); -// -// auto propose = [this, -// self{shared_from_this()}, -// inherent_data{std::move(inherent_data)}, -// now, -// proposal_start, -// babe_pre_digest{std::move(babe_pre_digest)}, -// ctx]() mutable { -// auto changes_tracker = -// std::make_shared(); -// -// // create new block -// auto res = proposer_->propose(ctx.parent, -// slots_util_.get()->slotFinishTime(ctx.slot) -// - -// babe_config_repo_->slotDuration() -// / 3, -// inherent_data, -// {babe_pre_digest}, -// changes_tracker); -// if (not res) { -// SL_ERROR(log_, "Cannot propose a block: {}", res.error()); -// return; -// } -// auto &unsealed_block = res.value(); -// auto proposed = [self, -// now, -// proposal_start, -// changes_tracker{std::move(changes_tracker)}, -// unsealed_block{std::move(unsealed_block)}, -// ctx]() mutable { -// auto res = -// self->processSlotLeadershipProposed(ctx, -// now, -// proposal_start, -// std::move(changes_tracker), -// std::move(unsealed_block)); -// if (res.has_error()) { -// SL_ERROR(self->log_, "Cannot propose a block: {}", res.error()); -// return; -// } -// }; -// main_thread_->post(std::move(proposed)); -// }; -// -// io_context_->post(std::move(propose)); - - // clang-format on - return outcome::success(); - } - - // outcome::result Sassafras::processSlotLeadershipProposed( - // const Context &ctx, - // uint64_t now, - // clock::SteadyClock::TimePoint proposal_start, - // std::shared_ptr - // &&changes_tracker, - // primitives::Block &&block) { - // auto duration_ms = - // metric_block_proposal_time.observe(proposal_start).count(); - // SL_DEBUG(log_, "Block has been built in {} ms", duration_ms); - // - // // Ensure block's extrinsics root matches extrinsics in block's body - // BOOST_ASSERT_MSG( - // [&block]() { - // using boost::adaptors::transformed; - // const auto &ext_root_res = - // storage::trie::calculateOrderedTrieHash( - // storage::trie::StateVersion::V0, - // block.body | transformed([](const auto &ext) { - // return common::Buffer{scale::encode(ext).value()}; - // })); - // return ext_root_res.has_value() - // and (ext_root_res.value() == block.header.extrinsics_root); - // }(), - // "Extrinsics root does not match extrinsics in the block"); - // - // // seal the block - // 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; - // } - // - // // add seal digest item - // block.header.digest.emplace_back(seal_res.value()); - // - // // Calculate and save hash, 'cause seal digest was added - // primitives::calculateBlockHash(block.header, *hasher_); - // - // if (clock_.now() > slots_util_.get()->slotFinishTime( - // ctx.slot + kMaxBlockSlotsOvertime)) { - // SL_WARN(log_, - // "Block was not built on time. " - // "Allowed slots ({}) have passed. " - // "If you are executing in debug mode, consider to rebuild in " - // "release", - // kMaxBlockSlotsOvertime); - // return BabeError::WAS_NOT_BUILD_ON_TIME; - // } - // - // const auto block_info = block.header.blockInfo(); - // - // auto previous_best_block = block_tree_->bestBlock(); - // - // // 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()); auto removal_res = - // block_tree_->removeLeaf(block_info.hash); if (removal_res.has_error() - // and removal_res - // != outcome::failure( - // blockchain::BlockTreeError::BLOCK_IS_NOT_LEAF)) { - // SL_WARN(log_, - // "Rolling back of block {} is failed: {}", - // block_info, - // removal_res.error()); - // } - // return BabeError::CAN_NOT_SAVE_BLOCK; - // } - // - // changes_tracker->onBlockAdded( - // block_info.hash, storage_sub_engine_, chain_sub_engine_); - // - // telemetry_->notifyBlockImported(block_info, - // telemetry::BlockOrigin::kOwn); telemetry_->pushBlockStats(); - // - // // observe digest of block - // // (must be done strictly after block will be added) - // auto digest_tracking_res = digest_tracker_->onDigest( - // {.block_info = block_info, .header = block.header}, - // block.header.digest); - // - // if (digest_tracking_res.has_error()) { - // SL_WARN(log_, - // "Error while tracking digest of block {}: {}", - // block_info, - // digest_tracking_res.error()); - // return outcome::success(); - // } - // - // // finally, broadcast the sealed block - // announce_transmitter_->blockAnnounce(network::BlockAnnounce{ - // block.header, - // block_info == block_tree_->bestBlock() ? network::BlockState::Best - // : - // network::BlockState::Normal, - // common::Buffer{}, - // }); - // SL_DEBUG( - // log_, - // "Announced block number {} in slot {} (epoch {}) with timestamp {}", - // block.header.number, - // ctx.slot, - // ctx.epoch, - // now); - // - // auto current_best_block = block_tree_->bestBlock(); - // - // // Create new offchain worker for block if it is best only - // if (current_best_block.number > previous_best_block.number) { - // auto ocw_res = offchain_worker_api_->offchain_worker( - // block.header.parent_hash, block.header); - // if (ocw_res.has_failure()) { - // log_->error("Can't spawn offchain worker for block {}: {}", - // block_info, - // ocw_res.error()); - // } - // } - // - // return outcome::success(); - // } - - void Sassafras::changeLotteryEpoch(const Context &ctx, - const EpochNumber &epoch, - primitives::AuthorityIndex authority_index, - const Epoch &sassafras_config) const { - BOOST_ASSERT(ctx.keypair != nullptr); - - Threshold ticket_threshold = - ticket_id_threshold(sassafras_config.config.redundancy_factor, - sassafras_config.epoch_length, - sassafras_config.config.attempts_number, - sassafras_config.authorities.size()) - .number; - - Threshold threshold; // FIXME - // = calculateThreshold(sassafras_config.leadership_rate, - // sassafras_config.authorities, - // authority_index); - - lottery_->changeEpoch(epoch, - sassafras_config.randomness, - ticket_threshold, - threshold, - *ctx.keypair); - } - -} // namespace kagome::consensus::sassafras diff --git a/core/network/helpers/stream_proxy_base.hpp b/core/network/helpers/stream_proxy_base.hpp index 52da382250..13eac061fa 100644 --- a/core/network/helpers/stream_proxy_base.hpp +++ b/core/network/helpers/stream_proxy_base.hpp @@ -19,14 +19,10 @@ namespace libp2p::connection { explicit StreamProxyBase(std::shared_ptr stream) : stream{std::move(stream)} {} - void read(std::span out, - size_t bytes, - ReadCallbackFunc cb) override { + void read(BytesOut out, size_t bytes, ReadCallbackFunc cb) override { stream->read(out, bytes, std::move(cb)); } - void readSome(std::span out, - size_t bytes, - ReadCallbackFunc cb) override { + void readSome(BytesOut out, size_t bytes, ReadCallbackFunc cb) override { stream->readSome(out, bytes, std::move(cb)); } void deferReadCallback(outcome::result res, diff --git a/core/network/helpers/stream_read_buffer.hpp b/core/network/helpers/stream_read_buffer.hpp index 814c697568..3c31bd2d83 100644 --- a/core/network/helpers/stream_read_buffer.hpp +++ b/core/network/helpers/stream_read_buffer.hpp @@ -36,7 +36,7 @@ namespace libp2p::connection { return end - begin; } - void read(std::span out, size_t n, ReadCallbackFunc cb) override { + void read(BytesOut out, size_t n, ReadCallbackFunc cb) override { libp2p::ambigousSize(out, n); libp2p::readReturnSize(shared_from_this(), out, std::move(cb)); } @@ -44,7 +44,7 @@ namespace libp2p::connection { /** * Read from buffer. */ - size_t readFromBuffer(std::span out) { + size_t readFromBuffer(BytesOut out) { // can't read more bytes than available auto n = std::min(out.size(), size()); BOOST_ASSERT(n != 0); @@ -55,9 +55,7 @@ namespace libp2p::connection { return n; } - void readSome(std::span out, - size_t n, - ReadCallbackFunc cb) override { + void readSome(BytesOut out, size_t n, ReadCallbackFunc cb) override { libp2p::ambigousSize(out, n); if (out.empty()) { return deferReadCallback(out.size(), std::move(cb)); @@ -143,12 +141,12 @@ namespace kagome::network { return stream_->remoteMultiaddr(); } - void read(std::span out, size_t bytes, ReadCallbackFunc cb) { + void read(BytesOut out, size_t bytes, ReadCallbackFunc cb) { check(); stream_->read(out, bytes, std::move(cb)); } - void readSome(std::span out, size_t bytes, ReadCallbackFunc cb) { + void readSome(BytesOut out, size_t bytes, ReadCallbackFunc cb) { check(); stream_->readSome(out, bytes, std::move(cb)); } diff --git a/core/primitives/ss58_codec.cpp b/core/primitives/ss58_codec.cpp index 3ca08b8a53..3dc71d854a 100644 --- a/core/primitives/ss58_codec.cpp +++ b/core/primitives/ss58_codec.cpp @@ -25,7 +25,7 @@ OUTCOME_CPP_DEFINE_CATEGORY(kagome::primitives, Ss58Error, e) { namespace kagome::primitives { - static common::Buffer calculateChecksum(std::span ss58_address, + static common::Buffer calculateChecksum(common::BufferView ss58_address, const crypto::Hasher &hasher) { constexpr auto PREFIX = "SS58PRE"; auto preimage = common::Buffer{}.put(PREFIX).put(ss58_address); diff --git a/core/scale/tie.hpp b/core/scale/tie.hpp index a7987e7f19..3be974af85 100644 --- a/core/scale/tie.hpp +++ b/core/scale/tie.hpp @@ -6,6 +6,8 @@ #pragma once +#include +#include #include #define SCALE_TIE_EQ \ diff --git a/test/mock/libp2p/basic/read_writer_mock.hpp b/test/mock/libp2p/basic/read_writer_mock.hpp index 477b84610e..c3d02babb2 100644 --- a/test/mock/libp2p/basic/read_writer_mock.hpp +++ b/test/mock/libp2p/basic/read_writer_mock.hpp @@ -15,12 +15,12 @@ namespace libp2p::basic { struct ReadWriterMock : public ReadWriter { MOCK_METHOD(void, read, - (std::span, size_t, Reader::ReadCallbackFunc), + (BytesOut, size_t, Reader::ReadCallbackFunc), (override)); MOCK_METHOD(void, readSome, - (std::span, size_t, Reader::ReadCallbackFunc), + (BytesOut, size_t, Reader::ReadCallbackFunc), (override)); MOCK_METHOD(void, From 540dbb531a0f039667a550f196185319214ef3ac Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Fri, 27 Oct 2023 12:28:04 +0300 Subject: [PATCH 07/12] fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon --- core/common/buffer_back_insert_iterator.hpp | 70 ------------------- core/common/buffer_or_view.hpp | 9 +-- core/common/buffer_view.hpp | 5 -- core/crypto/bip39/mnemonic.cpp | 2 +- .../impl/prioritized_selection.cpp | 2 +- .../adapters/protobuf_block_response.hpp | 6 +- core/network/helpers/stream_read_buffer.hpp | 12 ++-- .../polkadot_trie_cursor_impl.cpp | 1 - 8 files changed, 15 insertions(+), 92 deletions(-) delete mode 100644 core/common/buffer_back_insert_iterator.hpp diff --git a/core/common/buffer_back_insert_iterator.hpp b/core/common/buffer_back_insert_iterator.hpp deleted file mode 100644 index 830677f97b..0000000000 --- a/core/common/buffer_back_insert_iterator.hpp +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "common/buffer.hpp" - -/* - * std::back_insert_iterator is an output iterator - * that appends to a container for which it was constructed. - */ -template -class std::back_insert_iterator> { - using Container = kagome::common::SLBuffer; - - public: - using value_type = typename Container::value_type; - using difference_type = typename Container::difference_type; - using pointer = typename Container::pointer; - using reference = typename Container::reference; - using iterator_category = std::random_access_iterator_tag; - - constexpr explicit back_insert_iterator(Container &c) : buf_{c} {} - - back_insert_iterator &operator=(uint8_t value) { - buf_.putUint8(value); - return *this; - } - - back_insert_iterator &operator=(uint32_t value) { - buf_.putUint32(value); - return *this; - } - - back_insert_iterator &operator=(uint64_t value) { - buf_.putUint64(value); - return *this; - } - - back_insert_iterator &operator=(std::string_view value) { - buf_.put(value); - return *this; - } - - back_insert_iterator &operator=(kagome::common::BufferView s) { - buf_.put(s); - return *this; - } - - back_insert_iterator &operator=(const std::vector &v) { - buf_.put(v); - return *this; - } - - constexpr back_insert_iterator &operator*() { - return *this; - } - - constexpr back_insert_iterator &operator++() { - return *this; - } - - constexpr back_insert_iterator &operator++(int) { - return *this; - } - - private: - Container &buf_; -}; diff --git a/core/common/buffer_or_view.hpp b/core/common/buffer_or_view.hpp index 19b64dd78e..b8d1b71f0e 100644 --- a/core/common/buffer_or_view.hpp +++ b/core/common/buffer_or_view.hpp @@ -15,7 +15,7 @@ namespace kagome::common { /// Moved owned buffer or readonly view. class BufferOrView { - using Span = BufferView; + using Span = std::span; template using AsSpan = std::enable_if_t>; @@ -28,7 +28,8 @@ namespace kagome::common { BufferOrView(const BufferView &view) : variant{view} {} template - BufferOrView(const std::array &array) : variant{array} {} + BufferOrView(const std::array &array) + : variant{BufferView(array)} {} BufferOrView(const std::vector &vector) = delete; BufferOrView(std::vector &&vector) @@ -102,11 +103,11 @@ namespace kagome::common { template > friend bool operator==(const BufferOrView &l, const T &r) { - return std::equal(l.view().begin(), l.view().end(), Span{r}.begin()); + return l.view() == Span{r}; } template > friend bool operator==(const T &l, const BufferOrView &r) { - return std::equal(r.view().begin(), r.view().end(), Span{l}.begin()); + return Span{l} == r.view(); } }; } // namespace kagome::common diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index 06991cd583..de654e5d29 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -15,11 +15,6 @@ #include #include -template -concept RangeOfBytes = - std::ranges::sized_range and std::ranges::contiguous_range - and std::is_same_v, uint8_t>; - inline auto operator""_bytes(const char *s, std::size_t size) { return std::span(reinterpret_cast(s), size); } diff --git a/core/crypto/bip39/mnemonic.cpp b/core/crypto/bip39/mnemonic.cpp index ab5c7ae170..d7a4e0518a 100644 --- a/core/crypto/bip39/mnemonic.cpp +++ b/core/crypto/bip39/mnemonic.cpp @@ -93,7 +93,7 @@ namespace kagome::crypto::bip39 { } } - if (seed.substr(0, 2) == "0x") { + if (seed.starts_with("0x")) { OUTCOME_TRY(bytes, common::unhexWith0x(seed)); mnemonic.seed = common::Buffer{std::move(bytes)}; } else { diff --git a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp index 3e30e1e0d7..42c98b4692 100644 --- a/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp +++ b/core/dispute_coordinator/provisioner/impl/prioritized_selection.cpp @@ -148,7 +148,7 @@ namespace kagome::dispute { for (size_t i = 0; i < disputes.size();) { auto batch_size = std::min(kVotesSelectionBatchSize, disputes.size() - i); - auto batch = std::span(disputes).first(batch_size); + auto batch = std::span(disputes).subspan(i, batch_size); i += batch_size; // Filter votes which are already onchain diff --git a/core/network/adapters/protobuf_block_response.hpp b/core/network/adapters/protobuf_block_response.hpp index fd488b75a5..df534538b5 100644 --- a/core/network/adapters/protobuf_block_response.hpp +++ b/core/network/adapters/protobuf_block_response.hpp @@ -156,11 +156,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(common::BufferView( - reinterpret_cast(buffer.data()), // NOLINT - buffer.size()))); + OUTCOME_TRY(decoded, scale::decode(str2byte(buffer))); return decoded; } return AdaptersError::EMPTY_DATA; diff --git a/core/network/helpers/stream_read_buffer.hpp b/core/network/helpers/stream_read_buffer.hpp index 3c31bd2d83..0168926190 100644 --- a/core/network/helpers/stream_read_buffer.hpp +++ b/core/network/helpers/stream_read_buffer.hpp @@ -36,7 +36,7 @@ namespace libp2p::connection { return end - begin; } - void read(BytesOut out, size_t n, ReadCallbackFunc cb) override { + void read(libp2p::BytesOut out, size_t n, ReadCallbackFunc cb) override { libp2p::ambigousSize(out, n); libp2p::readReturnSize(shared_from_this(), out, std::move(cb)); } @@ -44,7 +44,7 @@ namespace libp2p::connection { /** * Read from buffer. */ - size_t readFromBuffer(BytesOut out) { + size_t readFromBuffer(libp2p::BytesOut out) { // can't read more bytes than available auto n = std::min(out.size(), size()); BOOST_ASSERT(n != 0); @@ -55,7 +55,9 @@ namespace libp2p::connection { return n; } - void readSome(BytesOut out, size_t n, ReadCallbackFunc cb) override { + void readSome(libp2p::BytesOut out, + size_t n, + ReadCallbackFunc cb) override { libp2p::ambigousSize(out, n); if (out.empty()) { return deferReadCallback(out.size(), std::move(cb)); @@ -141,12 +143,12 @@ namespace kagome::network { return stream_->remoteMultiaddr(); } - void read(BytesOut out, size_t bytes, ReadCallbackFunc cb) { + void read(libp2p::BytesOut out, size_t bytes, ReadCallbackFunc cb) { check(); stream_->read(out, bytes, std::move(cb)); } - void readSome(BytesOut out, size_t bytes, ReadCallbackFunc cb) { + void readSome(libp2p::BytesOut out, size_t bytes, ReadCallbackFunc cb) { check(); stream_->readSome(out, bytes, std::move(cb)); } 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 a36bf4a60e..f47c4b1f81 100644 --- a/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp +++ b/core/storage/trie/polkadot_trie/polkadot_trie_cursor_impl.cpp @@ -8,7 +8,6 @@ #include -#include "common/buffer_back_insert_iterator.hpp" #include "macro/unreachable.hpp" #include "storage/trie/polkadot_trie/polkadot_trie.hpp" #include "storage/trie/polkadot_trie/trie_error.hpp" From 2e4b3562b52b9967a99dd264d5818488c59b45d3 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Fri, 27 Oct 2023 12:50:04 +0300 Subject: [PATCH 08/12] fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon --- .../child_state/impl/child_state_api_impl.cpp | 4 ++-- .../api/service/state/impl/state_api_impl.cpp | 2 +- core/application/chain_spec.hpp | 2 +- .../impl/app_configuration_impl.cpp | 2 +- core/common/buffer.hpp | 12 ---------- core/common/buffer_view.hpp | 23 +++++++++---------- .../impl/state_protocol_observer_impl.cpp | 8 +++---- core/storage/map_prefix/prefix.cpp | 2 +- .../trie/impl/topper_trie_batch_impl.cpp | 4 ++-- .../trie_pruner/impl/trie_pruner_impl.cpp | 4 ++-- core/utils/kagome_db_editor.cpp | 2 +- 11 files changed, 26 insertions(+), 39 deletions(-) diff --git a/core/api/service/child_state/impl/child_state_api_impl.cpp b/core/api/service/child_state/impl/child_state_api_impl.cpp index 845df37953..c9cf24078e 100644 --- a/core/api/service/child_state/impl/child_state_api_impl.cpp +++ b/core/api/service/child_state/impl/child_state_api_impl.cpp @@ -59,7 +59,7 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!key->startsWith(prefix)) { + if (not startsWith(key.value(), prefix)) { break; } result.push_back(cursor->key().value()); @@ -106,7 +106,7 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!key->startsWith(prefix)) { + if (not startsWith(key.value(), prefix)) { break; } result.push_back(cursor->key().value()); diff --git a/core/api/service/state/impl/state_api_impl.cpp b/core/api/service/state/impl/state_api_impl.cpp index 488ed98103..3742cfaec9 100644 --- a/core/api/service/state/impl/state_api_impl.cpp +++ b/core/api/service/state/impl/state_api_impl.cpp @@ -102,7 +102,7 @@ namespace kagome::api { BOOST_ASSERT(key.has_value()); // make sure our key begins with prefix - if (!key->startsWith(prefix)) { + if (not startsWith(key.value(), prefix)) { break; } result.push_back(cursor->key().value()); diff --git a/core/application/chain_spec.hpp b/core/application/chain_spec.hpp index b19917dfd2..006d9893f0 100644 --- a/core/application/chain_spec.hpp +++ b/core/application/chain_spec.hpp @@ -77,7 +77,7 @@ namespace kagome::application { const = 0; bool idStartsWith(std::string_view prefix) const { - return id().rfind(prefix, 0) == 0; + return id().starts_with(prefix); } bool isKusama() const { diff --git a/core/application/impl/app_configuration_impl.cpp b/core/application/impl/app_configuration_impl.cpp index c07d1c7554..8f4af9f3ec 100644 --- a/core/application/impl/app_configuration_impl.cpp +++ b/core/application/impl/app_configuration_impl.cpp @@ -1165,7 +1165,7 @@ namespace kagome::application { auto replace = [&](std::string_view prefix, std::string_view replacement, std::string_view str) { - if (str.substr(0, prefix.size()) == prefix) { + if (str.starts_with(prefix)) { std::string replaced{replacement}; replaced += str.substr(prefix.size()); public_addresses_.emplace_back( diff --git a/core/common/buffer.hpp b/core/common/buffer.hpp index 02ba3b8fb7..fb956e2cdf 100644 --- a/core/common/buffer.hpp +++ b/core/common/buffer.hpp @@ -205,18 +205,6 @@ namespace kagome::common { static SLBuffer fromString(const std::string_view &src) { return {src.begin(), src.end()}; } - - template - bool startsWith(const Prefix &prefix) const { - if (this->size() >= prefix.size()) { - auto this_view = view().first(prefix.size()); - return std::equal(this_view.begin(), - this_view.end(), - std::cbegin(prefix), - std::cend(prefix)); - } - return false; - } }; template diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index de654e5d29..5c21f420e4 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -69,18 +69,6 @@ namespace kagome::common { return {reinterpret_cast(data()), size()}; } - template - bool startsWith(const Prefix &prefix) const { - if (this->size() >= prefix.size()) { - auto this_view = first(prefix.size()); - return std::equal(this_view.begin(), - this_view.end(), - std::cbegin(prefix), - std::cend(prefix)); - } - return false; - } - auto operator<=>(const BufferView &other) const noexcept { return cxx20::lexicographical_compare_three_way( span::begin(), span::end(), other.begin(), other.end()); @@ -95,6 +83,17 @@ namespace kagome::common { return os << view.toHex(); } + template + bool startsWith(const Super &super, const Prefix &prefix) { + if (std::size(super) >= std::size(prefix)) { + auto beginning = std::span(super).first(std::size(prefix)); + return std::equal(beginning.begin(), + beginning.end(), + std::begin(prefix), + std::end(prefix)); + } + return false; + } } // namespace kagome::common template <> diff --git a/core/network/impl/state_protocol_observer_impl.cpp b/core/network/impl/state_protocol_observer_impl.cpp index 2a4fe28116..81737b7b69 100644 --- a/core/network/impl/state_protocol_observer_impl.cpp +++ b/core/network/impl/state_protocol_observer_impl.cpp @@ -107,7 +107,7 @@ namespace kagome::network { return Error::INVALID_CHILD_ROOTHASH; } if (request.start.size() == 2 - and not request.start[0].startsWith(storage::kChildStoragePrefix)) { + and not startsWith(request.start[0], storage::kChildStoragePrefix)) { return Error::INVALID_CHILD_ROOTHASH; } OUTCOME_TRY(header, blocks_headers_->getBlockHeader(request.hash)); @@ -118,7 +118,7 @@ namespace kagome::network { OUTCOME_TRY(batch, storage_->getEphemeralBatchAt(header.state_root)); auto cursor = batch->trieCursor(); - // if key is not empty continue iteration from place where left + // if key is not empty, continue iteration from place where left auto res = (request.start.empty() || request.start[0].empty() ? cursor->next() : cursor->seekUpperBound(request.start[0])); @@ -160,7 +160,7 @@ namespace kagome::network { size += entry.entries.back().key.size() + entry.entries.back().value.size(); // if key is child state storage hash iterate child storage keys - if (cursor->key()->startsWith(child_prefix)) { + if (startsWith(cursor->key().value(), child_prefix)) { OUTCOME_TRY(hash, storage::trie::RootHash::fromSpan(*value_res.value())); OUTCOME_TRY(entry_res, @@ -233,7 +233,7 @@ namespace kagome::network { } auto key = cursor->key().value(); if (stack.size() == 1 - and key.startsWith(storage::kChildStoragePrefix)) { + and startsWith(key, storage::kChildStoragePrefix)) { OUTCOME_TRY(root, common::Hash256::fromSpan(*value)); if (child_roots.emplace(root).second) { OUTCOME_TRY(batch, get_batch(root)); diff --git a/core/storage/map_prefix/prefix.cpp b/core/storage/map_prefix/prefix.cpp index 09dd5d5ab9..2482edf97e 100644 --- a/core/storage/map_prefix/prefix.cpp +++ b/core/storage/map_prefix/prefix.cpp @@ -51,7 +51,7 @@ namespace kagome::storage { bool MapPrefix::Cursor::isValid() const { if (cursor->isValid()) { - return cursor->key()->startsWith(map.prefix); + return startsWith(cursor->key().value(), map.prefix); } return false; } diff --git a/core/storage/trie/impl/topper_trie_batch_impl.cpp b/core/storage/trie/impl/topper_trie_batch_impl.cpp index efddcb713b..33440157a7 100644 --- a/core/storage/trie/impl/topper_trie_batch_impl.cpp +++ b/core/storage/trie/impl/topper_trie_batch_impl.cpp @@ -118,7 +118,7 @@ namespace kagome::storage::trie { outcome::result> TopperTrieBatchImpl::clearPrefix( const BufferView &prefix, std::optional) { for (auto it = cache_.lower_bound(prefix); - it != cache_.end() && it->first.startsWith(prefix); + it != cache_.end() && startsWith(it->first, prefix); ++it) { it->second = std::nullopt; } @@ -158,7 +158,7 @@ namespace kagome::storage::trie { bool TopperTrieBatchImpl::wasClearedByPrefix(const BufferView &key) const { for (const auto &prefix : cleared_prefixes_) { - if (key.startsWith(prefix)) { + if (startsWith(key, prefix)) { return true; } } diff --git a/core/storage/trie_pruner/impl/trie_pruner_impl.cpp b/core/storage/trie_pruner/impl/trie_pruner_impl.cpp index 8ef05f7e52..a46be49891 100644 --- a/core/storage/trie_pruner/impl/trie_pruner_impl.cpp +++ b/core/storage/trie_pruner/impl/trie_pruner_impl.cpp @@ -49,8 +49,8 @@ namespace kagome::storage::trie_pruner { auto child_tries = parent.trieCursor(); OUTCOME_TRY(child_tries->seekLowerBound(storage::kChildStoragePrefix)); while (child_tries->isValid() - && child_tries->key().value().startsWith( - storage::kChildStoragePrefix)) { + && startsWith(child_tries->key().value(), + storage::kChildStoragePrefix)) { auto child_key = child_tries->value().value(); OUTCOME_TRY(child_hash, trie::RootHash::fromSpan(child_key)); OUTCOME_TRY(f(child_key.view(), child_hash)); diff --git a/core/utils/kagome_db_editor.cpp b/core/utils/kagome_db_editor.cpp index 39e5b2eda7..46cd22f547 100644 --- a/core/utils/kagome_db_editor.cpp +++ b/core/utils/kagome_db_editor.cpp @@ -188,7 +188,7 @@ void child_storage_root_hashes(const std::unique_ptr &batch, auto res = cursor->seekUpperBound(child_prefix); if (res.has_value()) { auto key = cursor->key(); - while (key.has_value() && key->startsWith(child_prefix)) { + while (key.has_value() && startsWith(key.value(), child_prefix)) { if (auto value_res = batch->tryGet(key.value()); value_res.has_value() && value_res.value().has_value()) { auto &value_opt = value_res.value(); From 371d1cd7b99793ca4f13673b690b0f98a0993240 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Fri, 27 Oct 2023 12:56:14 +0300 Subject: [PATCH 09/12] fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon --- core/common/final_action.hpp | 51 +++--------------------------------- 1 file changed, 3 insertions(+), 48 deletions(-) diff --git a/core/common/final_action.hpp b/core/common/final_action.hpp index a19ecd150f..664d5824e1 100644 --- a/core/common/final_action.hpp +++ b/core/common/final_action.hpp @@ -6,59 +6,14 @@ #pragma once -#include +#include namespace kagome::common { template - struct FinalAction { - FinalAction() = delete; - FinalAction(FinalAction &&func) = delete; - FinalAction(const FinalAction &func) = delete; - FinalAction &operator=(FinalAction &&func) = delete; - FinalAction &operator=(const FinalAction &func) = delete; - - FinalAction(F &&func) : func(std::forward(func)) {} - - ~FinalAction() { - func(); - } - - public: - // To prevent an object being created on the heap - void *operator new(std::size_t) = delete; // standard new - void *operator new(std::size_t, void *) = delete; // placement new - void *operator new[](std::size_t) = delete; // array new - void *operator new[](std::size_t, void *) = delete; // placement array new - - private: - F func; - }; - - template - FinalAction(F &&) -> FinalAction; - - template - struct MovableFinalAction { - MovableFinalAction() = delete; - MovableFinalAction(MovableFinalAction &&func) = default; - MovableFinalAction(const MovableFinalAction &func) = delete; - MovableFinalAction &operator=(MovableFinalAction &&func) = default; - MovableFinalAction &operator=(const MovableFinalAction &func) = delete; - - MovableFinalAction(F &&func) : func(std::forward(func)) {} - - ~MovableFinalAction() { - if (func.has_value()) { - func->operator()(); - } - } - - private: - std::optional func; - }; + using FinalAction = libp2p::common::FinalAction; template - MovableFinalAction(F &&) -> MovableFinalAction; + using MovableFinalAction = libp2p::common::MovableFinalAction; } // namespace kagome::common From 5c564542d3e81a0be89ecdb625698ae302bc9cb0 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Fri, 27 Oct 2023 13:56:22 +0300 Subject: [PATCH 10/12] fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon --- core/api/service/mmr/rpc.cpp | 5 +++-- core/blockchain/impl/block_tree_impl.hpp | 17 +++++++++-------- core/common/final_action.hpp | 19 ------------------- core/consensus/grandpa/impl/grandpa_impl.cpp | 4 ++-- core/metrics/histogram_timer.hpp | 5 +++-- core/network/impl/synchronizer_impl.cpp | 9 +++++---- core/network/warp/cache.cpp | 4 ++-- core/network/warp/sync.cpp | 5 +++-- core/offchain/impl/offchain_worker_impl.cpp | 6 +++--- core/offchain/impl/runner.hpp | 5 +++-- core/parachain/pvf/precheck.cpp | 5 +++-- .../validator/impl/parachain_processor.cpp | 10 ++++++---- .../runtime_api/impl/block_builder.cpp | 7 ++++--- core/runtime/wavm/module_instance.cpp | 5 +++-- 14 files changed, 49 insertions(+), 57 deletions(-) delete mode 100644 core/common/final_action.hpp diff --git a/core/api/service/mmr/rpc.cpp b/core/api/service/mmr/rpc.cpp index 2043a8a553..e8f9726d0e 100644 --- a/core/api/service/mmr/rpc.cpp +++ b/core/api/service/mmr/rpc.cpp @@ -6,10 +6,11 @@ #include "api/service/mmr/rpc.hpp" +#include + #include "api/jrpc/jrpc_server_impl.hpp" #include "api/service/jrpc_fn.hpp" #include "blockchain/block_tree.hpp" -#include "common/final_action.hpp" #include "offchain/offchain_worker_factory.hpp" #include "offchain/offchain_worker_pool.hpp" #include "runtime/runtime_api/mmr.hpp" @@ -63,7 +64,7 @@ namespace kagome::api { auto MmrRpc::withOffchain(const primitives::BlockHash &at) { // TODO(turuslan): simplify offchain - common::MovableFinalAction remove( + ::libp2p::common::MovableFinalAction remove( [&] { offchain_worker_pool_.get()->removeWorker(); }); outcome::result result{std::move(remove)}; if (auto r = block_tree_.get()->getBlockHeader(at)) { diff --git a/core/blockchain/impl/block_tree_impl.hpp b/core/blockchain/impl/block_tree_impl.hpp index 32084123f1..4a56f3663e 100644 --- a/core/blockchain/impl/block_tree_impl.hpp +++ b/core/blockchain/impl/block_tree_impl.hpp @@ -10,16 +10,16 @@ #include #include +#include #include #include -#include +#include #include "application/app_configuration.hpp" #include "blockchain/block_header_repository.hpp" #include "blockchain/block_storage.hpp" #include "blockchain/block_tree_error.hpp" -#include "common/final_action.hpp" #include "consensus/timeline/types.hpp" #include "crypto/hasher.hpp" #include "log/logger.hpp" @@ -225,12 +225,13 @@ namespace kagome::blockchain { == std::this_thread::get_id()) { return f(block_tree_data_.unsafeGet()); } - return block_tree_data_.exclusiveAccess([&f, - this](BlockTreeData &data) { - exclusive_owner_ = std::this_thread::get_id(); - common::FinalAction reset([&] { exclusive_owner_ = std::nullopt; }); - return f(data); - }); + return block_tree_data_.exclusiveAccess( + [&f, this](BlockTreeData &data) { + exclusive_owner_ = std::this_thread::get_id(); + ::libp2p::common::FinalAction reset( + [&] { exclusive_owner_ = std::nullopt; }); + return f(data); + }); } template diff --git a/core/common/final_action.hpp b/core/common/final_action.hpp deleted file mode 100644 index 664d5824e1..0000000000 --- a/core/common/final_action.hpp +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include - -namespace kagome::common { - - template - using FinalAction = libp2p::common::FinalAction; - - template - using MovableFinalAction = libp2p::common::MovableFinalAction; - -} // namespace kagome::common diff --git a/core/consensus/grandpa/impl/grandpa_impl.cpp b/core/consensus/grandpa/impl/grandpa_impl.cpp index 8800848b5c..9b0d6d90f3 100644 --- a/core/consensus/grandpa/impl/grandpa_impl.cpp +++ b/core/consensus/grandpa/impl/grandpa_impl.cpp @@ -10,10 +10,10 @@ #include #include +#include #include "application/app_state_manager.hpp" #include "blockchain/block_tree.hpp" -#include "common/final_action.hpp" #include "common/tagged.hpp" #include "consensus/grandpa/authority_manager.hpp" #include "consensus/grandpa/environment.hpp" @@ -777,7 +777,7 @@ namespace kagome::consensus::grandpa { need_cleanup_when_exiting_scope = true; } - common::FinalAction cleanup([&] { + ::libp2p::common::FinalAction cleanup([&] { if (need_cleanup_when_exiting_scope) { catchup_request_timer_handle_.cancel(); pending_catchup_request_.reset(); diff --git a/core/metrics/histogram_timer.hpp b/core/metrics/histogram_timer.hpp index f91d1fee2d..2e1c386f4b 100644 --- a/core/metrics/histogram_timer.hpp +++ b/core/metrics/histogram_timer.hpp @@ -6,9 +6,10 @@ #pragma once -#include "common/final_action.hpp" #include "metrics/metrics.hpp" +#include + namespace kagome::metrics { inline std::vector exponentialBuckets(double start, double factor, @@ -68,7 +69,7 @@ namespace kagome::metrics { } auto timer() { - return std::make_optional(common::MovableFinalAction(manual())); + return std::make_optional(::libp2p::common::MovableFinalAction(manual())); } }; } // namespace kagome::metrics diff --git a/core/network/impl/synchronizer_impl.cpp b/core/network/impl/synchronizer_impl.cpp index 79c09982e2..5817cb3aaf 100644 --- a/core/network/impl/synchronizer_impl.cpp +++ b/core/network/impl/synchronizer_impl.cpp @@ -8,9 +8,10 @@ #include +#include + #include "application/app_configuration.hpp" #include "blockchain/block_tree_error.hpp" -#include "common/final_action.hpp" #include "consensus/babe/has_babe_consensus_digest.hpp" #include "consensus/grandpa/environment.hpp" #include "consensus/grandpa/has_authority_set_change.hpp" @@ -819,7 +820,7 @@ namespace kagome::network { } busy_peers_.insert(peer_id); - common::FinalAction cleanup([this, peer_id] { + ::libp2p::common::FinalAction cleanup([this, peer_id] { auto peer = busy_peers_.find(peer_id); if (peer != busy_peers_.end()) { busy_peers_.erase(peer); @@ -1071,7 +1072,7 @@ namespace kagome::network { return; } SL_TRACE(log_, "Begin applying"); - common::MovableFinalAction cleanup([weak = weak_from_this()] { + ::libp2p::common::MovableFinalAction cleanup([weak = weak_from_this()] { if (auto self = weak.lock()) { SL_TRACE(self->log_, "End applying"); self->applying_in_progress_ = false; @@ -1290,7 +1291,7 @@ namespace kagome::network { return; } SL_TRACE(log_, "Begin justification applying"); - common::FinalAction cleanup([this] { + ::libp2p::common::FinalAction cleanup([this] { SL_TRACE(log_, "End justification applying"); applying_in_progress_ = false; }); diff --git a/core/network/warp/cache.cpp b/core/network/warp/cache.cpp index a64acd248b..6e65c70e74 100644 --- a/core/network/warp/cache.cpp +++ b/core/network/warp/cache.cpp @@ -8,9 +8,9 @@ #include #include +#include #include "blockchain/impl/storage_util.hpp" -#include "common/final_action.hpp" #include "consensus/grandpa/has_authority_set_change.hpp" #include "storage/predefined_keys.hpp" @@ -136,7 +136,7 @@ namespace kagome::network { if (bool old = false; not caching_.compare_exchange_strong(old, true)) { return outcome::success(); } - common::FinalAction unlock([&] { caching_.store(false); }); + ::libp2p::common::FinalAction unlock([&] { caching_.store(false); }); for (; cache_next_ <= finalized; ++cache_next_) { OUTCOME_TRY(hash, block_repository_->getHashByNumber(cache_next_)); OUTCOME_TRY(header, block_repository_->getBlockHeader(hash)); diff --git a/core/network/warp/sync.cpp b/core/network/warp/sync.cpp index 6eb847a67d..336af9de68 100644 --- a/core/network/warp/sync.cpp +++ b/core/network/warp/sync.cpp @@ -6,9 +6,10 @@ #include "network/warp/sync.hpp" +#include + #include "blockchain/block_storage.hpp" #include "blockchain/block_tree.hpp" -#include "common/final_action.hpp" #include "consensus/babe/babe_config_repository.hpp" #include "consensus/grandpa/authority_manager.hpp" #include "consensus/grandpa/has_authority_set_change.hpp" @@ -64,7 +65,7 @@ namespace kagome::network { return; } std::optional min, max; - common::FinalAction log([&] { + ::libp2p::common::FinalAction log([&] { if (min) { SL_INFO(log_, "finalized {}..{}", *min, *max); } diff --git a/core/offchain/impl/offchain_worker_impl.cpp b/core/offchain/impl/offchain_worker_impl.cpp index 7dd4b1bd8e..faf783a014 100644 --- a/core/offchain/impl/offchain_worker_impl.cpp +++ b/core/offchain/impl/offchain_worker_impl.cpp @@ -8,11 +8,11 @@ #include +#include #include #include "api/service/author/author_api.hpp" #include "application/app_configuration.hpp" -#include "common/final_action.hpp" #include "crypto/hasher.hpp" #include "offchain/impl/offchain_local_storage.hpp" #include "offchain/offchain_worker_pool.hpp" @@ -64,7 +64,7 @@ namespace kagome::offchain { outcome::result OffchainWorkerImpl::run() { BOOST_ASSERT(not ocw_pool_->getWorker()); - common::FinalAction at_end( + ::libp2p::common::FinalAction at_end( [prev_thread_name = soralog::util::getThreadName()] { soralog::util::setThreadName(prev_thread_name); }); @@ -72,7 +72,7 @@ namespace kagome::offchain { soralog::util::setThreadName("ocw.#" + std::to_string(block_.number)); ocw_pool_->addWorker(shared_from_this()); - common::FinalAction remove([&] { ocw_pool_->removeWorker(); }); + ::libp2p::common::FinalAction remove([&] { ocw_pool_->removeWorker(); }); SL_TRACE(log_, "Offchain worker is started for block {}", block_); diff --git a/core/offchain/impl/runner.hpp b/core/offchain/impl/runner.hpp index 4b157ee02a..832cb0a4a8 100644 --- a/core/offchain/impl/runner.hpp +++ b/core/offchain/impl/runner.hpp @@ -9,7 +9,8 @@ #include #include -#include "common/final_action.hpp" +#include + #include "utils/thread_pool.hpp" namespace kagome::offchain { @@ -41,7 +42,7 @@ namespace kagome::offchain { thread_pool_.io_context()->post( [weak{weak_from_this()}, task{std::move(task)}] { if (auto self = weak.lock()) { - common::FinalAction release([&] { + ::libp2p::common::FinalAction release([&] { std::unique_lock lock{self->mutex_}; ++self->free_threads_; }); diff --git a/core/parachain/pvf/precheck.cpp b/core/parachain/pvf/precheck.cpp index dc2234baf2..9b395d4140 100644 --- a/core/parachain/pvf/precheck.cpp +++ b/core/parachain/pvf/precheck.cpp @@ -6,7 +6,8 @@ #include "parachain/pvf/precheck.hpp" -#include "common/final_action.hpp" +#include + #include "metrics/histogram_timer.hpp" #include "offchain/offchain_worker_factory.hpp" #include "offchain/offchain_worker_pool.hpp" @@ -120,7 +121,7 @@ namespace kagome::parachain { OUTCOME_TRY(signature, signer->signRaw(statement.signable())); offchain_worker_pool_->addWorker( offchain_worker_factory_->make(executor_, header)); - common::FinalAction remove( + ::libp2p::common::FinalAction remove( [&] { offchain_worker_pool_->removeWorker(); }); OUTCOME_TRY(parachain_api_->submit_pvf_check_statement( block_hash, statement, signature)); diff --git a/core/parachain/validator/impl/parachain_processor.cpp b/core/parachain/validator/impl/parachain_processor.cpp index 1472c509b7..5cb5b11e32 100644 --- a/core/parachain/validator/impl/parachain_processor.cpp +++ b/core/parachain/validator/impl/parachain_processor.cpp @@ -9,7 +9,8 @@ #include #include -#include "common/final_action.hpp" +#include + #include "crypto/hasher.hpp" #include "crypto/sr25519_provider.hpp" #include "dispute_coordinator/impl/runtime_info.hpp" @@ -309,9 +310,10 @@ namespace kagome::parachain { ParachainProcessorImpl::initNewBackingTask( const primitives::BlockHash &relay_parent) { bool is_parachain_validator = false; - common::FinalAction metric_updater([self{this}, &is_parachain_validator] { - self->metric_is_parachain_validator_->set(is_parachain_validator); - }); + ::libp2p::common::FinalAction metric_updater( + [self{this}, &is_parachain_validator] { + self->metric_is_parachain_validator_->set(is_parachain_validator); + }); OUTCOME_TRY(validators, parachain_host_->validators(relay_parent)); OUTCOME_TRY(groups, parachain_host_->validator_groups(relay_parent)); OUTCOME_TRY(cores, parachain_host_->availability_cores(relay_parent)); diff --git a/core/runtime/runtime_api/impl/block_builder.cpp b/core/runtime/runtime_api/impl/block_builder.cpp index 80fbc36b13..29bdc54325 100644 --- a/core/runtime/runtime_api/impl/block_builder.cpp +++ b/core/runtime/runtime_api/impl/block_builder.cpp @@ -6,7 +6,8 @@ #include "runtime/runtime_api/impl/block_builder.hpp" -#include "common/final_action.hpp" +#include + #include "runtime/executor.hpp" #include "runtime/trie_storage_provider.hpp" @@ -24,7 +25,7 @@ namespace kagome::runtime { OUTCOME_TRY(ctx.module_instance->getEnvironment() .storage_provider->startTransaction()); auto should_rollback = true; - common::FinalAction rollback([&] { + ::libp2p::common::FinalAction rollback([&] { if (should_rollback) { std::ignore = ctx.module_instance->getEnvironment() .storage_provider->rollbackTransaction(); @@ -59,7 +60,7 @@ namespace kagome::runtime { // `env.storage_provider`s `PersistentTrieBatch`. OUTCOME_TRY(ctx.module_instance->getEnvironment() .storage_provider->startTransaction()); - common::FinalAction rollback([&] { + ::libp2p::common::FinalAction rollback([&] { std::ignore = ctx.module_instance->getEnvironment() .storage_provider->rollbackTransaction(); }); diff --git a/core/runtime/wavm/module_instance.cpp b/core/runtime/wavm/module_instance.cpp index c89f01655e..2e7c760ab0 100644 --- a/core/runtime/wavm/module_instance.cpp +++ b/core/runtime/wavm/module_instance.cpp @@ -6,10 +6,11 @@ #include "runtime/wavm/module_instance.hpp" +#include + #include #include -#include "common/final_action.hpp" #include "host_api/host_api.hpp" #include "log/profiling_logger.hpp" #include "runtime/common/runtime_transaction_error.hpp" @@ -144,7 +145,7 @@ namespace kagome::runtime::wavm { std::array untaggedInvokeResults; pushBorrowedRuntimeInstance( std::const_pointer_cast(shared_from_this())); - common::FinalAction pop(&popBorrowedRuntimeInstance); + ::libp2p::common::FinalAction pop(&popBorrowedRuntimeInstance); try { WAVM::Runtime::unwindSignalsAsExceptions( [&context, From d3cc1901562708ece849e4e7bba13b3795d5fdee Mon Sep 17 00:00:00 2001 From: kamilsa Date: Fri, 27 Oct 2023 17:57:11 +0600 Subject: [PATCH 11/12] Switch to Macos-13 --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4d63e69474..10dfd06d03 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,7 +30,7 @@ env: jobs: MacOS: - runs-on: macos-latest + runs-on: macos-13 steps: - uses: actions/checkout@dc323e67f16fb5f7663d20ff7941f27f5809e9b6 - uses: actions/cache@937d24475381cd9c75ae6db12cb4e79714b926ed From cc9213c2c250a340799cd8aeb4b8f3db825da619 Mon Sep 17 00:00:00 2001 From: Dmitriy Khaustov aka xDimon Date: Fri, 27 Oct 2023 15:05:26 +0300 Subject: [PATCH 12/12] fix: review issues Signed-off-by: Dmitriy Khaustov aka xDimon --- core/common/buffer_view.hpp | 7 ++----- core/network/helpers/stream_read_buffer.hpp | 14 ++++++-------- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/core/common/buffer_view.hpp b/core/common/buffer_view.hpp index 5c21f420e4..37943d813d 100644 --- a/core/common/buffer_view.hpp +++ b/core/common/buffer_view.hpp @@ -86,11 +86,8 @@ namespace kagome::common { template bool startsWith(const Super &super, const Prefix &prefix) { if (std::size(super) >= std::size(prefix)) { - auto beginning = std::span(super).first(std::size(prefix)); - return std::equal(beginning.begin(), - beginning.end(), - std::begin(prefix), - std::end(prefix)); + return std::equal( + std::begin(prefix), std::end(prefix), std::begin(super)); } return false; } diff --git a/core/network/helpers/stream_read_buffer.hpp b/core/network/helpers/stream_read_buffer.hpp index 0168926190..861023bc4b 100644 --- a/core/network/helpers/stream_read_buffer.hpp +++ b/core/network/helpers/stream_read_buffer.hpp @@ -36,15 +36,15 @@ namespace libp2p::connection { return end - begin; } - void read(libp2p::BytesOut out, size_t n, ReadCallbackFunc cb) override { - libp2p::ambigousSize(out, n); - libp2p::readReturnSize(shared_from_this(), out, std::move(cb)); + void read(BytesOut out, size_t n, ReadCallbackFunc cb) override { + ambigousSize(out, n); + readReturnSize(shared_from_this(), out, std::move(cb)); } /** * Read from buffer. */ - size_t readFromBuffer(libp2p::BytesOut out) { + size_t readFromBuffer(BytesOut out) { // can't read more bytes than available auto n = std::min(out.size(), size()); BOOST_ASSERT(n != 0); @@ -55,10 +55,8 @@ namespace libp2p::connection { return n; } - void readSome(libp2p::BytesOut out, - size_t n, - ReadCallbackFunc cb) override { - libp2p::ambigousSize(out, n); + void readSome(BytesOut out, size_t n, ReadCallbackFunc cb) override { + ambigousSize(out, n); if (out.empty()) { return deferReadCallback(out.size(), std::move(cb)); }