diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8833ab834..2fa6bb9c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -9,43 +9,36 @@ on: - master jobs: - build: - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - # 3 jobs in total - os: [ubuntu-latest, macos-latest] - compiler: [{ - "cc": "gcc", - "cxx": "g++" - }, { - "cc": "clang", - "cxx": "clang++" - }] - exclude: - - os: macos-latest - compiler: - cc: gcc + MacOS: + runs-on: macos-14 steps: - - uses: actions/checkout@v1 - name: checkout - with: - submodules: true - clean: true - fetch-depth: 1 - - name: install dependencies + - uses: actions/checkout@dc323e67f16fb5f7663d20ff7941f27f5809e9b6 + - name: venv + run: python3 -m venv --upgrade-deps ~/venv && housekeeping/github_venv.sh $_ + - name: install run: | - set -e - - sudo python3 -m pip install --upgrade pip - sudo pip3 install scikit-build - sudo pip3 install cmake=="3.25.0" requests gitpython gcovr pyyaml + pip3 install scikit-build + pip3 install cmake==3.25 requests gitpython gcovr + brew install ninja - name: cmake env: - CC: ${{ matrix.compiler.cc }} - CXX: ${{ matrix.compiler.cxx }} - run: cmake . -Bbuild + CURL_SSL_BACKEND: SecureTransport + run: cmake -G Ninja -B build . + - name: build + run: cmake --build build -- -j4 + - name: test + env: + CTEST_OUTPUT_ON_FAILURE: 1 + run: cmake --build build --target test + Linux-gcc: + runs-on: ubuntu-latest + container: qdrvm/kagome-dev@sha256:2d70246c32418a3dd45c246d3f5c2dd99bdafde145b903271849affe476c4cfc + steps: + - uses: actions/checkout@dc323e67f16fb5f7663d20ff7941f27f5809e9b6 + - name: venv + run: housekeeping/github_venv.sh /venv + - name: cmake + run: cmake -B build . - name: build run: cmake --build build -- -j4 - name: test diff --git a/.github/workflows/clang-tidy.yml b/.github/workflows/clang-tidy.yml index 27f7033dc..cf6e79b01 100644 --- a/.github/workflows/clang-tidy.yml +++ b/.github/workflows/clang-tidy.yml @@ -10,32 +10,20 @@ on: jobs: build: - runs-on: macOS-latest + runs-on: ubuntu-latest + container: qdrvm/kagome-dev@sha256:2d70246c32418a3dd45c246d3f5c2dd99bdafde145b903271849affe476c4cfc steps: - - uses: actions/checkout@v1 - name: checkout + - uses: actions/checkout@dc323e67f16fb5f7663d20ff7941f27f5809e9b6 with: - submodules: true - clean: true - fetch-depth: 1 - - name: install - run: | - brew install ninja llvm - sudo python3 -m pip install --upgrade pip - sudo python3 -m pip install scikit-build - sudo python3 -m pip install cmake requests gitpython gcovr pyyaml + fetch-depth: 0 + - name: venv + run: housekeeping/github_venv.sh /venv - name: run checks + env: + BUILD_DIR: build run: | - #!/bin/bash - LLVM_DIR=/usr/local/Cellar/llvm - test -d $LLVM_DIR || echo $(echo "llvm is absent, cannot continue" && exit 1) - VER_COUNT=$(ls -1 ${LLVM_DIR} | wc -l) - test ${VER_COUNT} -eq 0 && echo "no llvm version detected" && exit 1 - test $VER_COUNT -gt 1 && echo "wrong llvm installation" && exit 1 - LLVM_VER=$(ls -1 ${LLVM_DIR}) - export LLVM_ROOT=${LLVM_DIR}/${LLVM_VER} - export PATH=${LLVM_ROOT}/bin:${LLVM_ROOT}/share/clang:${PATH} - cmake . -GNinja -Bbuild - cmake --build build --target generated - housekeeping/clang-tidy.sh build + cmake -B $BUILD_DIR . + cmake --build $BUILD_DIR --target generated + git config --global --add safe.directory $PWD + housekeeping/clang-tidy-diff.sh diff --git a/cmake/Hunter/init.cmake b/cmake/Hunter/init.cmake index 318d312d0..6cbda90e7 100644 --- a/cmake/Hunter/init.cmake +++ b/cmake/Hunter/init.cmake @@ -31,7 +31,7 @@ set( include(${CMAKE_CURRENT_LIST_DIR}/HunterGate.cmake) 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.25.3-qdrvm6.zip + SHA1 5a911c0b567aba49a7140c1d2fe0e4b6769d070f LOCAL ) diff --git a/cmake/functions.cmake b/cmake/functions.cmake index 350d30598..8a930d58f 100644 --- a/cmake/functions.cmake +++ b/cmake/functions.cmake @@ -29,9 +29,6 @@ function(addtest_part test_name) target_sources(${test_name} PUBLIC ${ARGN} ) - target_link_libraries(${test_name} - GTest::gtest - ) endfunction() # conditionally applies flag. If flag is supported by current compiler, it will be added to compile options. diff --git a/cmake/toolchain/clang-15_cxx17.cmake b/cmake/toolchain/clang-15_cxx17.cmake deleted file mode 100644 index ec14ed678..000000000 --- a/cmake/toolchain/clang-15_cxx17.cmake +++ /dev/null @@ -1,3 +0,0 @@ -include(${CMAKE_CURRENT_LIST_DIR}/../print.cmake) -include(${CMAKE_CURRENT_LIST_DIR}/compiler/clang-15.cmake) -include(${CMAKE_CURRENT_LIST_DIR}/cxx20.cmake) diff --git a/example/01-echo/libp2p_echo_client.cpp b/example/01-echo/libp2p_echo_client.cpp index 0fd542096..6adbc54fb 100644 --- a/example/01-echo/libp2p_echo_client.cpp +++ b/example/01-echo/libp2p_echo_client.cpp @@ -52,8 +52,7 @@ int main(int argc, char *argv[]) { auto sz = static_cast(n); jumbo_message.reserve(sz + 9); while (jumbo_message.size() < sz) { - jumbo_message.append( - fmt::format("[{:08}]", jumbo_message.size() + 10)); + jumbo_message.append(fmt::format("[{:08}]", jumbo_message.size() + 10)); } jumbo_message.resize(sz); message.swap(jumbo_message); @@ -106,14 +105,17 @@ int main(int argc, char *argv[]) { auto sch = injector.create>(); context->post( - [log, host{std::move(host)}, &echo, &message, + [log, + host{std::move(host)}, + &echo, + &message, argv, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) sch] { auto server_ma_res = libp2p::multi::Multiaddress::create(argv[1]); // NOLINT if (!server_ma_res) { log->error("unable to create server multiaddress: {}", - server_ma_res.error().message()); + server_ma_res.error()); std::exit(EXIT_FAILURE); } const auto &server_ma = server_ma_res.value(); @@ -128,7 +130,7 @@ int main(int argc, char *argv[]) { libp2p::peer::PeerId::fromBase58(*server_peer_id_str); if (!server_peer_id_res) { log->error("Unable to decode peer id from base 58: {}", - server_peer_id_res.error().message()); + server_peer_id_res.error()); std::exit(EXIT_FAILURE); } @@ -138,11 +140,11 @@ int main(int argc, char *argv[]) { // create Host object and open a stream through it host->newStream( - peer_info, {echo.getProtocolId()}, + peer_info, + {echo.getProtocolId()}, [log, &echo, &message, sch](auto &&stream_res) { if (!stream_res) { - log->error("Cannot connect to server: {}", - stream_res.error().message()); + log->error("Cannot connect to server: {}", stream_res.error()); std::exit(EXIT_FAILURE); } @@ -164,7 +166,7 @@ int main(int argc, char *argv[]) { stream = std::move(stream)](auto &&response_result) { if (response_result.has_error()) { log->info("Error happened: {}", - response_result.error().message()); + response_result.error()); stream->close( [log](auto &&) { std::exit(EXIT_SUCCESS); }); return; diff --git a/example/01-echo/libp2p_echo_server.cpp b/example/01-echo/libp2p_echo_server.cpp index 0be951613..2648a0e86 100644 --- a/example/01-echo/libp2p_echo_server.cpp +++ b/example/01-echo/libp2p_echo_server.cpp @@ -49,7 +49,8 @@ struct SecureAdaptorProxy : libp2p::security::SecurityAdaptor { void secureOutbound( std::shared_ptr outbound, - const libp2p::peer::PeerId &p, SecConnCallbackFunc cb) override { + const libp2p::peer::PeerId &p, + SecConnCallbackFunc cb) override { return impl->secureOutbound(outbound, p, cb); } @@ -176,7 +177,7 @@ dPtse4GVRA2swbXcZX5iFVi/V8poIpdVrgn5iMadkQnYf9APWJuGcebK auto listen_res = host->listen(ma); if (!listen_res) { log->error("host cannot listen the given multiaddress: {}", - listen_res.error().message()); + listen_res.error()); std::exit(EXIT_FAILURE); } @@ -184,7 +185,8 @@ dPtse4GVRA2swbXcZX5iFVi/V8poIpdVrgn5iMadkQnYf9APWJuGcebK log->info("Server started"); log->info("Listening on: {}", ma.getStringAddress()); log->info("Peer id: {}", host->getPeerInfo().id.toBase58()); - log->info("Connection string: {}/p2p/{}", ma.getStringAddress(), + log->info("Connection string: {}/p2p/{}", + ma.getStringAddress(), host->getPeerInfo().id.toBase58()); }); @@ -193,7 +195,7 @@ dPtse4GVRA2swbXcZX5iFVi/V8poIpdVrgn5iMadkQnYf9APWJuGcebK io_context->run(); std::exit(EXIT_SUCCESS); } catch (const boost::system::error_code &ec) { - log->error("Server cannot run: {}", ec.message()); + log->error("Server cannot run: {}", ec); std::exit(EXIT_FAILURE); } catch (...) { log->error("Unknown error happened"); diff --git a/example/02-kademlia/rendezvous_chat.cpp b/example/02-kademlia/rendezvous_chat.cpp index 9777b837a..0c8736536 100644 --- a/example/02-kademlia/rendezvous_chat.cpp +++ b/example/02-kademlia/rendezvous_chat.cpp @@ -12,12 +12,14 @@ #include #include -#include +#include #include #include #include #include +using libp2p::common::operator""_unhex; + class Session; struct Cmp { @@ -46,7 +48,7 @@ class Session : public std::enable_shared_from_this { stream_->readSome( *incoming_, incoming_->size(), - [self = shared_from_this()](libp2p::outcome::result result) { + [self = shared_from_this()](outcome::result result) { if (not result) { self->close(); std::cout << self->stream_->remotePeerId().value().toBase58() @@ -71,8 +73,7 @@ class Session : public std::enable_shared_from_this { libp2p::writeReturnSize( stream_, *buffer, - [self = shared_from_this(), - buffer](libp2p::outcome::result result) { + [self = shared_from_this(), buffer](outcome::result result) { if (not result) { self->close(); std::cout << self->stream_->remotePeerId().value().toBase58() @@ -129,8 +130,8 @@ void handleIncomingStream(libp2p::StreamAndProtocol stream_and_protocol) { void handleOutgoingStream(libp2p::StreamAndProtocolOrError stream_res) { if (not stream_res) { - std::cerr << " ! outgoing connection failed: " - << stream_res.error().message() << std::endl; + fmt::println( + std::cerr, " ! outgoing connection failed: {}", stream_res.error()); return; } auto &stream = stream_res.value().stream; @@ -198,11 +199,11 @@ int main(int argc, char *argv[]) { // clang-format off .publicKey = {{ .type = libp2p::crypto::Key::Type::Ed25519, - .data = libp2p::common::unhex("48453469c62f4885373099421a7365520b5ffb0d93726c124166be4b81d852e6").value() + .data = "48453469c62f4885373099421a7365520b5ffb0d93726c124166be4b81d852e6"_unhex, }}, .privateKey = {{ .type = libp2p::crypto::Key::Type::Ed25519, - .data = libp2p::common::unhex("4a9361c525840f7086b893d584ebbe475b4ec7069951d2e897e8bceb0a3f35ce").value() + .data = "4a9361c525840f7086b893d584ebbe475b4ec7069951d2e897e8bceb0a3f35ce"_unhex, }}, // clang-format on }; @@ -291,14 +292,12 @@ int main(int argc, char *argv[]) { [[maybe_unused]] auto res1 = kademlia->findProviders( content_id, 0, - [&](libp2p::outcome::result> - res) { + [&](outcome::result> res) { scheduler.schedule(std::function{find_providers}, kademlia_config.randomWalk.interval); if (not res) { - std::cerr << "Cannot find providers: " << res.error().message() - << std::endl; + fmt::println(std::cerr, "Cannot find providers: {}", res.error()); return; } @@ -320,8 +319,10 @@ int main(int argc, char *argv[]) { io->post([&] { auto listen = host->listen(ma); if (not listen) { - std::cerr << "Cannot listen address " << ma.getStringAddress().data() - << ". Error: " << listen.error().message() << std::endl; + fmt::println(std::cerr, + "Cannot listen address {}. Error: {}", + ma.getStringAddress(), + listen.error()); std::exit(EXIT_FAILURE); } diff --git a/example/03-gossip/console_async_reader.cpp b/example/03-gossip/console_async_reader.cpp index 4b45b76d9..4ddca12b3 100644 --- a/example/03-gossip/console_async_reader.cpp +++ b/example/03-gossip/console_async_reader.cpp @@ -21,7 +21,9 @@ namespace libp2p::protocol::example::utility { void ConsoleAsyncReader::read() { input_.consume(input_.data().size()); boost::asio::async_read_until( - in_, input_, "\n", + in_, + input_, + "\n", [this](const boost::system::error_code &e, std::size_t size) { onRead(e, size); }); diff --git a/example/03-gossip/console_async_reader.hpp b/example/03-gossip/console_async_reader.hpp index d79408b87..b137e7c44 100644 --- a/example/03-gossip/console_async_reader.hpp +++ b/example/03-gossip/console_async_reader.hpp @@ -6,8 +6,8 @@ #pragma once -#include #include +#include #include @@ -39,4 +39,4 @@ namespace libp2p::protocol::example::utility { bool stopped_ = false; }; -} //namespace libp2p::protocol::example::utility +} // namespace libp2p::protocol::example::utility diff --git a/example/03-gossip/gossip_chat_example.cpp b/example/03-gossip/gossip_chat_example.cpp index 5b5b51705..ad406ceb9 100644 --- a/example/03-gossip/gossip_chat_example.cpp +++ b/example/03-gossip/gossip_chat_example.cpp @@ -97,9 +97,10 @@ int main(int argc, char *argv[]) { auto host = injector.create>(); // make peer uri of local node - auto local_address_str = - fmt::format("/ip4/{}/tcp/{}/p2p/{}", utility::getLocalIP(*io), - options->port, host->getId().toBase58()); + auto local_address_str = fmt::format("/ip4/{}/tcp/{}/p2p/{}", + utility::getLocalIP(*io), + options->port, + host->getId().toBase58()); // local address -> peer info auto peer_info = utility::str2peerInfo(local_address_str); @@ -113,7 +114,8 @@ int main(int argc, char *argv[]) { // create gossip node auto gossip = libp2p::protocol::gossip::create( - injector.create>(), host, + injector.create>(), + host, injector.create>(), injector.create>(), injector @@ -144,9 +146,10 @@ int main(int argc, char *argv[]) { io->post([&] { auto listen_res = host->listen(peer_info->addresses[0]); if (!listen_res) { - std::cerr << "Cannot listen to multiaddress " - << peer_info->addresses[0].getStringAddress() << ", " - << listen_res.error().message() << "\n"; + fmt::println(std::cerr, + "Cannot listen to multiaddress {}, {}", + peer_info->addresses[0].getStringAddress(), + listen_res.error()); io->stop(); return; } diff --git a/example/04-dnstxt/ares_resolver.cpp b/example/04-dnstxt/ares_resolver.cpp index 93f55af2f..34e9cebb1 100644 --- a/example/04-dnstxt/ares_resolver.cpp +++ b/example/04-dnstxt/ares_resolver.cpp @@ -11,7 +11,6 @@ #include #include #include -#include namespace { const std::string logger_config(R"( @@ -65,10 +64,11 @@ int main(int argc, char *argv[]) { auto work_guard = boost::asio::make_work_guard(*context); context->post([&] { ares.resolveTxt( - "_dnsaddr.bootstrap.libp2p.io", context, - [&](libp2p::outcome::result> result) -> void { + "_dnsaddr.bootstrap.libp2p.io", + context, + [&](outcome::result> result) -> void { if (result.has_error()) { - std::cout << result.error().message() << std::endl; + fmt::println("{}", result.error()); } else { auto &&val = result.value(); for (auto &record : val) { diff --git a/housekeeping/clang-tidy-diff.sh b/housekeeping/clang-tidy-diff.sh new file mode 100755 index 000000000..92ea884ed --- /dev/null +++ b/housekeeping/clang-tidy-diff.sh @@ -0,0 +1,12 @@ +#!/bin/bash -xe +# +# Copyright Quadrivium LLC +# All Rights Reserved +# SPDX-License-Identifier: Apache-2.0 +# + +BUILD_DIR="${BUILD_DIR:?}" + +cd $(dirname $0)/.. +git diff -U0 origin/master | clang-tidy-diff.py -p1 -path $BUILD_DIR -iregex '(include|src)\/.*\.(h|c|hpp|cpp)' | tee clang-tidy.log +! grep ': error:' clang-tidy.log diff --git a/housekeeping/github_venv.sh b/housekeeping/github_venv.sh new file mode 100755 index 000000000..c38889d9c --- /dev/null +++ b/housekeeping/github_venv.sh @@ -0,0 +1,11 @@ +# +# Copyright Quadrivium LLC +# All Rights Reserved +# SPDX-License-Identifier: Apache-2.0 +# + +GITHUB_ENV="${GITHUB_ENV:?}" +export VIRTUAL_ENV="${1:?venv path not set}" +export PATH="$VIRTUAL_ENV/bin:$PATH" +echo "VIRTUAL_ENV=$VIRTUAL_ENV" >> "$GITHUB_ENV" +echo "PATH=$PATH" >> "$GITHUB_ENV" diff --git a/include/libp2p/basic/message_read_writer.hpp b/include/libp2p/basic/message_read_writer.hpp index 571eefe1b..d78061b5e 100644 --- a/include/libp2p/basic/message_read_writer.hpp +++ b/include/libp2p/basic/message_read_writer.hpp @@ -7,11 +7,8 @@ #pragma once #include -#include #include -#include -#include namespace libp2p::basic { /** diff --git a/include/libp2p/basic/message_read_writer_bigendian.hpp b/include/libp2p/basic/message_read_writer_bigendian.hpp index 2a8bfa7df..24ff3fdb9 100644 --- a/include/libp2p/basic/message_read_writer_bigendian.hpp +++ b/include/libp2p/basic/message_read_writer_bigendian.hpp @@ -6,13 +6,8 @@ #pragma once -#include -#include - #include #include -#include -#include namespace libp2p::basic { /** diff --git a/include/libp2p/basic/message_read_writer_uvarint.hpp b/include/libp2p/basic/message_read_writer_uvarint.hpp index 4632f1cf4..c0934878c 100644 --- a/include/libp2p/basic/message_read_writer_uvarint.hpp +++ b/include/libp2p/basic/message_read_writer_uvarint.hpp @@ -6,13 +6,8 @@ #pragma once -#include -#include - #include #include -#include -#include namespace libp2p::basic { /** diff --git a/include/libp2p/basic/read.hpp b/include/libp2p/basic/read.hpp index 29a834e7e..24326845b 100644 --- a/include/libp2p/basic/read.hpp +++ b/include/libp2p/basic/read.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include @@ -37,7 +38,7 @@ namespace libp2p { // read remaining bytes auto reader = weak.lock(); if (not reader) { - return cb(std::errc::operation_canceled); + return cb(make_error_code(boost::asio::error::operation_aborted)); } read(reader, out.subspan(n), std::move(cb)); }); diff --git a/include/libp2p/basic/varint_reader.hpp b/include/libp2p/basic/varint_reader.hpp index d21a53790..8daa3e0e5 100644 --- a/include/libp2p/basic/varint_reader.hpp +++ b/include/libp2p/basic/varint_reader.hpp @@ -6,12 +6,10 @@ #pragma once -#include #include #include #include -#include namespace libp2p::basic { class VarintReader { diff --git a/include/libp2p/basic/write.hpp b/include/libp2p/basic/write.hpp index da536d4aa..35f610e4b 100644 --- a/include/libp2p/basic/write.hpp +++ b/include/libp2p/basic/write.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include @@ -37,7 +38,7 @@ namespace libp2p { // write remaining bytes auto writer = weak.lock(); if (not writer) { - return cb(std::errc::operation_canceled); + return cb(make_error_code(boost::asio::error::operation_aborted)); } write(writer, in.subspan(n), std::move(cb)); }); diff --git a/include/libp2p/common/hexutil.hpp b/include/libp2p/common/hexutil.hpp index 91db28b99..b0b309480 100644 --- a/include/libp2p/common/hexutil.hpp +++ b/include/libp2p/common/hexutil.hpp @@ -7,7 +7,6 @@ #pragma once #include -#include #include @@ -21,11 +20,6 @@ namespace libp2p::common { */ enum class UnhexError { NOT_ENOUGH_INPUT = 1, NON_HEX_INPUT, UNKNOWN }; - /** - * @brief Converts an integer to an uppercase hex representation - */ - std::string int_to_hex(uint64_t n, size_t fixed_width = 2) noexcept; - /** * @brief Converts bytes to uppercase hex representation * @param array bytes @@ -63,55 +57,6 @@ namespace libp2p::common { * https://www.boost.org/doc/libs/1_51_0/libs/algorithm/doc/html/the_boost_algorithm_library/Misc/hex.html */ outcome::result> unhex(std::string_view hex); - - /** - * Creates unsigned bytes span out of string, debug purpose helper - * @param str String - * @return Span - */ - inline BytesIn sv2span(const std::string_view &str) { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - return {reinterpret_cast(str.data()), str.size()}; - } - - /** - * sv2span() identity overload, for uniformity - * @param s Span - * @return s - */ - inline BytesIn sv2span(BytesIn s) { - return s; - } - - /** - * Makes printable string out of bytes, for diagnostic purposes - * @tparam Bytes Bytes or char sequence - * @param str Input - * @return String - */ - template - inline std::string dumpBin(const Bytes &str, - bool add_hex_for_non_printable = true) { - std::string ret; - ret.reserve(str.size() + 2); - bool non_printable_detected = false; - for (auto c : str) { - if (std::isprint(c) != 0) { - ret.push_back((char)c); // NOLINT - } else { - ret.push_back('?'); - non_printable_detected = true; - } - } - if (non_printable_detected and add_hex_for_non_printable) { - ret.reserve(ret.size() * 3); - ret += " ("; - ret += hex_lower(sv2span(str)); - ret += ')'; - } - return ret; - } - } // namespace libp2p::common OUTCOME_HPP_DECLARE_ERROR(libp2p::common, UnhexError); diff --git a/include/libp2p/common/types.hpp b/include/libp2p/common/types.hpp index 3ced905b0..cb786a61f 100644 --- a/include/libp2p/common/types.hpp +++ b/include/libp2p/common/types.hpp @@ -14,17 +14,6 @@ #include namespace libp2p::common { - - template - void append(Collection &c, Item &&g) { - c.insert(c.end(), g.begin(), g.end()); - } - - template - void append(Collection &c, char g) { - c.push_back(g); - } - /// Hash160 as a sequence of 20 bytes using Hash160 = std::array; /// Hash256 as a sequence of 32 bytes diff --git a/include/libp2p/connection/loopback_stream.hpp b/include/libp2p/connection/loopback_stream.hpp index 203429bc9..948ecc5df 100644 --- a/include/libp2p/connection/loopback_stream.hpp +++ b/include/libp2p/connection/loopback_stream.hpp @@ -10,7 +10,6 @@ #include #include -#include #include namespace libp2p::connection { diff --git a/include/libp2p/connection/stream.hpp b/include/libp2p/connection/stream.hpp index 58f356ae3..3552edae5 100644 --- a/include/libp2p/connection/stream.hpp +++ b/include/libp2p/connection/stream.hpp @@ -9,7 +9,6 @@ #include #include #include -#include namespace libp2p::peer { class PeerId; diff --git a/include/libp2p/crypto/aes_ctr/aes_ctr_impl.hpp b/include/libp2p/crypto/aes_ctr/aes_ctr_impl.hpp index ebf3e90d0..d5319e6fd 100644 --- a/include/libp2p/crypto/aes_ctr/aes_ctr_impl.hpp +++ b/include/libp2p/crypto/aes_ctr/aes_ctr_impl.hpp @@ -12,7 +12,6 @@ #include #include -#include namespace libp2p::crypto::aes { diff --git a/include/libp2p/crypto/chachapoly.hpp b/include/libp2p/crypto/chachapoly.hpp index b8d0df42f..0e62370cf 100644 --- a/include/libp2p/crypto/chachapoly.hpp +++ b/include/libp2p/crypto/chachapoly.hpp @@ -12,10 +12,8 @@ #include #include #include -#include namespace libp2p::crypto::chachapoly { - using libp2p::Bytes; using Key = std::array; using Nonce = std::array; diff --git a/include/libp2p/crypto/crypto_provider.hpp b/include/libp2p/crypto/crypto_provider.hpp index 6b44befc9..3ba6ebf2c 100644 --- a/include/libp2p/crypto/crypto_provider.hpp +++ b/include/libp2p/crypto/crypto_provider.hpp @@ -12,7 +12,6 @@ #include #include #include -#include namespace libp2p::crypto { /** diff --git a/include/libp2p/crypto/hasher.hpp b/include/libp2p/crypto/hasher.hpp index 42c50f31d..322462576 100644 --- a/include/libp2p/crypto/hasher.hpp +++ b/include/libp2p/crypto/hasher.hpp @@ -8,7 +8,6 @@ #include #include -#include namespace libp2p::crypto { diff --git a/include/libp2p/crypto/hmac_provider.hpp b/include/libp2p/crypto/hmac_provider.hpp index cb34aafbe..6e3ef05e4 100644 --- a/include/libp2p/crypto/hmac_provider.hpp +++ b/include/libp2p/crypto/hmac_provider.hpp @@ -9,8 +9,6 @@ #include #include #include -#include -#include namespace libp2p::crypto::hmac { diff --git a/include/libp2p/crypto/x25519_provider.hpp b/include/libp2p/crypto/x25519_provider.hpp index ed7a40a07..a4bb7c222 100644 --- a/include/libp2p/crypto/x25519_provider.hpp +++ b/include/libp2p/crypto/x25519_provider.hpp @@ -10,7 +10,6 @@ #include #include -#include namespace libp2p::crypto::x25519 { diff --git a/include/libp2p/host/host.hpp b/include/libp2p/host/host.hpp index 90803466a..8009b0f2a 100644 --- a/include/libp2p/host/host.hpp +++ b/include/libp2p/host/host.hpp @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include diff --git a/include/libp2p/injector/network_injector.hpp b/include/libp2p/injector/network_injector.hpp index ab7bec44d..047b086dd 100644 --- a/include/libp2p/injector/network_injector.hpp +++ b/include/libp2p/injector/network_injector.hpp @@ -163,7 +163,7 @@ namespace libp2p::injector { } else { SL_WARN(log::createLogger("libp2p::injector::useWssPem"), "{}", - cert_res.error().message()); + cert_res.error()); } } return boost::di::bind.template to( diff --git a/include/libp2p/layer/layer_adaptor.hpp b/include/libp2p/layer/layer_adaptor.hpp index 1bbbdc1bb..be8c3b751 100644 --- a/include/libp2p/layer/layer_adaptor.hpp +++ b/include/libp2p/layer/layer_adaptor.hpp @@ -9,7 +9,6 @@ #include #include -#include namespace libp2p::layer { /** diff --git a/include/libp2p/multi/content_identifier.hpp b/include/libp2p/multi/content_identifier.hpp index 933c576a6..40004cef2 100644 --- a/include/libp2p/multi/content_identifier.hpp +++ b/include/libp2p/multi/content_identifier.hpp @@ -35,12 +35,6 @@ namespace libp2p::multi { MulticodecType::Code content_type, Multihash content_address); - /** - * @param base is a human-readable multibase prefix - * @returns human readable representation of the CID - */ - std::string toPrettyString(const std::string &base) const; - bool operator==(const ContentIdentifier &c) const; bool operator<(const ContentIdentifier &c) const; diff --git a/include/libp2p/multi/converters/converter_utils.hpp b/include/libp2p/multi/converters/converter_utils.hpp index b425c24dc..4d0bb15f9 100644 --- a/include/libp2p/multi/converters/converter_utils.hpp +++ b/include/libp2p/multi/converters/converter_utils.hpp @@ -6,13 +6,9 @@ #pragma once -#include -#include - #include #include #include -#include namespace libp2p::multi::converters { @@ -24,15 +20,6 @@ namespace libp2p::multi::converters { outcome::result addressToBytes(const Protocol &protocol, std::string_view addr); - /** - * Converts the given address string of the specified protocol - * to a hex string that represents the address, if both - * address and protocol were valid - */ - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - outcome::result - addressToHex(const Protocol &protocol, std::string_view addr); - /** * Converts the given multiaddr string to a byte sequence representing * the multiaddr, if provided multiaddr was valid @@ -40,14 +27,6 @@ namespace libp2p::multi::converters { auto multiaddrToBytes(std::string_view multiaddr_str) -> outcome::result; - /** - * Converts the given byte sequence representing - * a multiaddr to a string containing the multiaddr in a human-readable - * format, if the provided byte sequence was a valid multiaddr - */ - auto bytesToMultiaddrString(const Bytes &bytes) - -> outcome::result; - /** * Converts the given byte sequence representing * a multiaddr to a string containing the multiaddr in a human-readable diff --git a/include/libp2p/multi/converters/dns_converter.hpp b/include/libp2p/multi/converters/dns_converter.hpp index 9f97254d2..36071de09 100644 --- a/include/libp2p/multi/converters/dns_converter.hpp +++ b/include/libp2p/multi/converters/dns_converter.hpp @@ -17,10 +17,6 @@ namespace libp2p::multi::converters { */ class DnsConverter { public: - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - static outcome::result - addressToHex(std::string_view addr); - static outcome::result addressToBytes(std::string_view addr); }; diff --git a/include/libp2p/multi/converters/ip_v4_converter.hpp b/include/libp2p/multi/converters/ip_v4_converter.hpp index 520a42257..97770d137 100644 --- a/include/libp2p/multi/converters/ip_v4_converter.hpp +++ b/include/libp2p/multi/converters/ip_v4_converter.hpp @@ -17,10 +17,6 @@ namespace libp2p::multi::converters { */ class IPv4Converter { public: - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - static outcome::result - addressToHex(std::string_view addr); - static outcome::result addressToBytes(std::string_view addr); }; diff --git a/include/libp2p/multi/converters/ip_v6_converter.hpp b/include/libp2p/multi/converters/ip_v6_converter.hpp index 07345a2b4..2832bf146 100644 --- a/include/libp2p/multi/converters/ip_v6_converter.hpp +++ b/include/libp2p/multi/converters/ip_v6_converter.hpp @@ -17,10 +17,6 @@ namespace libp2p::multi::converters { */ class IPv6Converter { public: - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - static outcome::result - addressToHex(std::string_view addr); - static outcome::result addressToBytes(std::string_view addr); }; diff --git a/include/libp2p/multi/converters/ipfs_converter.hpp b/include/libp2p/multi/converters/ipfs_converter.hpp index abb31166c..65c5a4bbd 100644 --- a/include/libp2p/multi/converters/ipfs_converter.hpp +++ b/include/libp2p/multi/converters/ipfs_converter.hpp @@ -17,10 +17,6 @@ namespace libp2p::multi::converters { */ class IpfsConverter { public: - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - static outcome::result - addressToHex(std::string_view addr); - static outcome::result addressToBytes(std::string_view addr); }; diff --git a/include/libp2p/multi/converters/tcp_converter.hpp b/include/libp2p/multi/converters/tcp_converter.hpp index b79c567fe..780d5472f 100644 --- a/include/libp2p/multi/converters/tcp_converter.hpp +++ b/include/libp2p/multi/converters/tcp_converter.hpp @@ -17,10 +17,6 @@ namespace libp2p::multi::converters { */ class TcpConverter { public: - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - static outcome::result - addressToHex(std::string_view addr); - static outcome::result addressToBytes(std::string_view addr); }; diff --git a/include/libp2p/multi/converters/udp_converter.hpp b/include/libp2p/multi/converters/udp_converter.hpp index 2831b1e60..43228f5d3 100644 --- a/include/libp2p/multi/converters/udp_converter.hpp +++ b/include/libp2p/multi/converters/udp_converter.hpp @@ -17,10 +17,6 @@ namespace libp2p::multi::converters { */ class UdpConverter { public: - [[deprecated("Use `common::hex_lower(addressToBytes(...))` instead")]] // - static outcome::result - addressToHex(std::string_view addr); - static outcome::result addressToBytes(std::string_view addr); }; } // namespace libp2p::multi::converters diff --git a/include/libp2p/multi/multiaddress.hpp b/include/libp2p/multi/multiaddress.hpp index 85920e989..f6c1151e5 100644 --- a/include/libp2p/multi/multiaddress.hpp +++ b/include/libp2p/multi/multiaddress.hpp @@ -17,7 +17,6 @@ #include #include #include -#include namespace libp2p { using ProtoAddrVec = std::vector>; diff --git a/include/libp2p/multi/multiaddress_protocol_list.hpp b/include/libp2p/multi/multiaddress_protocol_list.hpp index 274818308..05bd9cc19 100644 --- a/include/libp2p/multi/multiaddress_protocol_list.hpp +++ b/include/libp2p/multi/multiaddress_protocol_list.hpp @@ -53,9 +53,10 @@ namespace libp2p::multi { P2P_WEBRTC_STAR = 275, P2P_WEBRTC_DIRECT = 276, P2P_CIRCUIT = 290, - // Range for private use: 0x300000 – 0x3FFFFF - X_PARITY_WS = 0x300001, - X_PARITY_WSS = 0x300002, + // https://github.com/multiformats/rust-multiaddr/blob/3c7e813c3b1fdd4187a9ca9ff67e10af0e79231d/src/protocol.rs#L50-L53 + X_PARITY_WS = 4770, + X_PARITY_WSS = 4780, + // Range for private use: 0x300000 – 0x3FFFFF #ifndef NDEBUG _DUMMY_PROTO_1 = 0x3DEAD1, _DUMMY_PROTO_2 = 0x3DEAD2, diff --git a/include/libp2p/multi/multibase_codec/codecs/base16.hpp b/include/libp2p/multi/multibase_codec/codecs/base16.hpp index 76fa250a7..fcb581835 100644 --- a/include/libp2p/multi/multibase_codec/codecs/base16.hpp +++ b/include/libp2p/multi/multibase_codec/codecs/base16.hpp @@ -6,8 +6,6 @@ #pragma once -#include - #include #include @@ -21,13 +19,13 @@ namespace libp2p::multi::detail { * @param bytes to be encoded * @return encoded string */ - std::string encodeBase16Upper(const Bytes &bytes); + std::string encodeBase16Upper(BytesIn bytes); /** * Encode bytes to base16 lowercase string * @param bytes to be encoded * @return encoded string */ - std::string encodeBase16Lower(const Bytes &bytes); + std::string encodeBase16Lower(BytesIn bytes); /** * Decode base16 uppercase to bytes diff --git a/include/libp2p/multi/multibase_codec/codecs/base32.hpp b/include/libp2p/multi/multibase_codec/codecs/base32.hpp index c4b8ac2fe..0aab2f7b0 100644 --- a/include/libp2p/multi/multibase_codec/codecs/base32.hpp +++ b/include/libp2p/multi/multibase_codec/codecs/base32.hpp @@ -21,13 +21,13 @@ namespace libp2p::multi::detail { * @param bytes to be encoded * @return encoded string */ - std::string encodeBase32Upper(const Bytes &bytes); + std::string encodeBase32Upper(BytesIn bytes); /** * Encode bytes to base32 lowercase string * @param bytes to be encoded * @return encoded string */ - std::string encodeBase32Lower(const Bytes &bytes); + std::string encodeBase32Lower(BytesIn bytes); /** * Decode base32 uppercase to bytes diff --git a/include/libp2p/multi/multibase_codec/codecs/base58.hpp b/include/libp2p/multi/multibase_codec/codecs/base58.hpp index b5aabaf9a..a0c8eec70 100644 --- a/include/libp2p/multi/multibase_codec/codecs/base58.hpp +++ b/include/libp2p/multi/multibase_codec/codecs/base58.hpp @@ -6,8 +6,6 @@ #pragma once -#include - #include #include @@ -23,7 +21,7 @@ namespace libp2p::multi::detail { * @param bytes to be encoded * @return encoded string */ - std::string encodeBase58(const Bytes &bytes); + std::string encodeBase58(BytesIn bytes); /** * Decode base58 string to bytes diff --git a/include/libp2p/multi/multibase_codec/codecs/base64.hpp b/include/libp2p/multi/multibase_codec/codecs/base64.hpp index 8f4b41ae2..f95deffa6 100644 --- a/include/libp2p/multi/multibase_codec/codecs/base64.hpp +++ b/include/libp2p/multi/multibase_codec/codecs/base64.hpp @@ -6,8 +6,6 @@ #pragma once -#include - #include #include @@ -24,7 +22,7 @@ namespace libp2p::multi::detail { * @param bytes to be encoded * @return encoded string */ - std::string encodeBase64(const Bytes &bytes); + std::string encodeBase64(BytesIn bytes); /** * Decode base64 string to bytes diff --git a/include/libp2p/multi/multihash.hpp b/include/libp2p/multi/multihash.hpp index e6e5022a6..a2af554cd 100644 --- a/include/libp2p/multi/multihash.hpp +++ b/include/libp2p/multi/multihash.hpp @@ -6,14 +6,11 @@ #pragma once -#include -#include #include #include #include #include -#include namespace libp2p::multi { diff --git a/include/libp2p/multi/uvarint.hpp b/include/libp2p/multi/uvarint.hpp index c25ab84d8..883fe4e69 100644 --- a/include/libp2p/multi/uvarint.hpp +++ b/include/libp2p/multi/uvarint.hpp @@ -6,9 +6,7 @@ #pragma once -#include #include -#include #include diff --git a/include/libp2p/muxer/mplex/mplex_frame.hpp b/include/libp2p/muxer/mplex/mplex_frame.hpp index 1202e1e74..a20e68789 100644 --- a/include/libp2p/muxer/mplex/mplex_frame.hpp +++ b/include/libp2p/muxer/mplex/mplex_frame.hpp @@ -6,15 +6,7 @@ #pragma once -#include -#include -#include - -#include -#include -#include #include -#include namespace libp2p::connection { /** diff --git a/include/libp2p/muxer/yamux/yamux_frame.hpp b/include/libp2p/muxer/yamux/yamux_frame.hpp index caf1434bb..d77e71ec1 100644 --- a/include/libp2p/muxer/yamux/yamux_frame.hpp +++ b/include/libp2p/muxer/yamux/yamux_frame.hpp @@ -7,7 +7,6 @@ #pragma once #include -#include #include diff --git a/include/libp2p/muxer/yamux/yamux_stream.hpp b/include/libp2p/muxer/yamux/yamux_stream.hpp index 62dcac55e..1c42da36c 100644 --- a/include/libp2p/muxer/yamux/yamux_stream.hpp +++ b/include/libp2p/muxer/yamux/yamux_stream.hpp @@ -6,6 +6,8 @@ #pragma once +#include + #include #include #include @@ -152,7 +154,7 @@ namespace libp2p::connection { bool fin_sent_ = false; /// Non zero reason means that stream is closed and the reason of it - std::error_code close_reason_; + std::optional close_reason_; /// Max bytes allowed to send size_t window_size_; diff --git a/include/libp2p/network/cares/cares.hpp b/include/libp2p/network/cares/cares.hpp index 4a02689d8..8ba01a330 100644 --- a/include/libp2p/network/cares/cares.hpp +++ b/include/libp2p/network/cares/cares.hpp @@ -9,16 +9,12 @@ #include #include #include -#include #include #include #include #include -#include -#include #include -#include #include #include diff --git a/include/libp2p/network/dnsaddr_resolver.hpp b/include/libp2p/network/dnsaddr_resolver.hpp index 28b970ad6..86dc8f875 100644 --- a/include/libp2p/network/dnsaddr_resolver.hpp +++ b/include/libp2p/network/dnsaddr_resolver.hpp @@ -6,10 +6,6 @@ #pragma once -#include -#include - -#include #include #include diff --git a/include/libp2p/network/listener_manager.hpp b/include/libp2p/network/listener_manager.hpp index ddd300ee1..df40e5a0b 100644 --- a/include/libp2p/network/listener_manager.hpp +++ b/include/libp2p/network/listener_manager.hpp @@ -6,12 +6,9 @@ #pragma once -#include - #include #include #include -#include #include namespace libp2p::event::network { diff --git a/include/libp2p/network/router.hpp b/include/libp2p/network/router.hpp index caf78a7e6..b660b2926 100644 --- a/include/libp2p/network/router.hpp +++ b/include/libp2p/network/router.hpp @@ -6,13 +6,9 @@ #pragma once -#include -#include - #include #include #include -#include #include #include #include diff --git a/include/libp2p/outcome/outcome.hpp b/include/libp2p/outcome/outcome.hpp index b7e829b63..ba4dc8f81 100644 --- a/include/libp2p/outcome/outcome.hpp +++ b/include/libp2p/outcome/outcome.hpp @@ -34,7 +34,7 @@ #undef __cpp_sized_deallocation #endif -namespace libp2p::outcome { +namespace outcome { using namespace BOOST_OUTCOME_V2_NAMESPACE; // NOLINT template > // using result = basic_result; -} // namespace libp2p::outcome +} // namespace outcome // @see /docs/result.md @@ -95,78 +95,3 @@ struct fmt::formatter { return std::copy(std::begin(message), std::end(message), ctx.out()); } }; - -// Remove after it will be added to libp2p (will be happened compilation error) -template -struct fmt::formatter> { - // Parses format specifications. Must be empty - constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) { - // Parse the presentation format and store it in the formatter: - auto it = ctx.begin(), end = ctx.end(); - - // Check if reached the end of the range: - if (it != end && *it != '}') { - throw format_error("invalid format"); - } - - // Return an iterator past the end of the parsed range: - return it; - } - - // Formats the success - template - typename std::enable_if_t, OutputIt> format_impl( - OutputIt out, const libp2p::outcome::success_type &success) const { - return fmt::format_to(out, "{}", success.value()); - } - - // Formats the success - template - typename std::enable_if_t, OutputIt> format_impl( - OutputIt out, const libp2p::outcome::success_type &) const { - static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), out); - } - - // Formats the success - template - auto format(const libp2p::outcome::success_type &success, - FormatContext &ctx) const -> decltype(ctx.out()) { - return format_impl(ctx.out(), success); - } -}; - -template -struct fmt::formatter> { - // Parses format specifications. Must be empty - constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) { - // Parse the presentation format and store it in the formatter: - auto it = ctx.begin(), end = ctx.end(); - - // Check if reached the end of the range: - if (it != end && *it != '}') { - throw format_error("invalid format"); - } - - // Return an iterator past the end of the parsed range: - return it; - } - - // Formats the outcome result - template - auto format(const libp2p::outcome::result &res, - FormatContext &ctx) const -> decltype(ctx.out()) { - // ctx.out() is an output iterator to write to. - - if (res.has_value()) { - if constexpr (not std::is_void_v) { - return fmt::format_to(ctx.out(), "{}", res.value()); - } else { - static constexpr string_view message(""); - return std::copy(std::begin(message), std::end(message), ctx.out()); - } - } else { - return fmt::format_to(ctx.out(), "{}", res.error()); - } - } -}; diff --git a/include/libp2p/peer/key_repository.hpp b/include/libp2p/peer/key_repository.hpp index aafad509c..69d113855 100644 --- a/include/libp2p/peer/key_repository.hpp +++ b/include/libp2p/peer/key_repository.hpp @@ -7,7 +7,6 @@ #pragma once #include -#include #include #include diff --git a/include/libp2p/peer/peer_address.hpp b/include/libp2p/peer/peer_address.hpp index 15dc2fceb..30dddf74a 100644 --- a/include/libp2p/peer/peer_address.hpp +++ b/include/libp2p/peer/peer_address.hpp @@ -7,11 +7,9 @@ #pragma once #include -#include #include #include -#include #include namespace libp2p::peer { diff --git a/include/libp2p/peer/peer_id.hpp b/include/libp2p/peer/peer_id.hpp index b0d031c45..d5fb79b12 100644 --- a/include/libp2p/peer/peer_id.hpp +++ b/include/libp2p/peer/peer_id.hpp @@ -9,7 +9,6 @@ #include #include #include -#include namespace libp2p::peer { diff --git a/include/libp2p/peer/protocol_repository.hpp b/include/libp2p/peer/protocol_repository.hpp index ae49b9d24..fa87d12a2 100644 --- a/include/libp2p/peer/protocol_repository.hpp +++ b/include/libp2p/peer/protocol_repository.hpp @@ -8,13 +8,10 @@ #include #include -#include #include -#include #include #include -#include namespace libp2p::peer { diff --git a/include/libp2p/protocol/base_protocol.hpp b/include/libp2p/protocol/base_protocol.hpp index 8ab93213f..f65daa892 100644 --- a/include/libp2p/protocol/base_protocol.hpp +++ b/include/libp2p/protocol/base_protocol.hpp @@ -9,7 +9,6 @@ #include #include #include -#include namespace libp2p::protocol { diff --git a/include/libp2p/protocol/echo/client_echo_session.hpp b/include/libp2p/protocol/echo/client_echo_session.hpp index d93009f52..decee7ac1 100644 --- a/include/libp2p/protocol/echo/client_echo_session.hpp +++ b/include/libp2p/protocol/echo/client_echo_session.hpp @@ -6,6 +6,7 @@ #pragma once +#include #include #include @@ -36,7 +37,7 @@ namespace libp2p::protocol { std::shared_ptr stream_; std::vector buf_; std::vector recv_buf_; - std::error_code ec_; + std::optional ec_; size_t bytes_read_ = 0; Then then_; }; diff --git a/include/libp2p/protocol/identify/identify_msg_processor.hpp b/include/libp2p/protocol/identify/identify_msg_processor.hpp index 8fcdf8f0f..35e0a9f72 100644 --- a/include/libp2p/protocol/identify/identify_msg_processor.hpp +++ b/include/libp2p/protocol/identify/identify_msg_processor.hpp @@ -16,11 +16,9 @@ #include #include #include -#include #include #include #include -#include namespace identify::pb { class Identify; diff --git a/include/libp2p/protocol/kademlia/config.hpp b/include/libp2p/protocol/kademlia/config.hpp index ad5ba77a7..e66b6a123 100644 --- a/include/libp2p/protocol/kademlia/config.hpp +++ b/include/libp2p/protocol/kademlia/config.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include #include diff --git a/include/libp2p/protocol/kademlia/content_routing.hpp b/include/libp2p/protocol/kademlia/content_routing.hpp index fdb7347b8..ac84694d9 100644 --- a/include/libp2p/protocol/kademlia/content_routing.hpp +++ b/include/libp2p/protocol/kademlia/content_routing.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/kademlia/impl/kademlia_impl.hpp b/include/libp2p/protocol/kademlia/impl/kademlia_impl.hpp index 258235adb..1b4977b69 100644 --- a/include/libp2p/protocol/kademlia/impl/kademlia_impl.hpp +++ b/include/libp2p/protocol/kademlia/impl/kademlia_impl.hpp @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include diff --git a/include/libp2p/protocol/kademlia/impl/response_handler.hpp b/include/libp2p/protocol/kademlia/impl/response_handler.hpp index 4fe248cdb..089b7ac24 100644 --- a/include/libp2p/protocol/kademlia/impl/response_handler.hpp +++ b/include/libp2p/protocol/kademlia/impl/response_handler.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/kademlia/impl/storage.hpp b/include/libp2p/protocol/kademlia/impl/storage.hpp index 278df8565..1416ac400 100644 --- a/include/libp2p/protocol/kademlia/impl/storage.hpp +++ b/include/libp2p/protocol/kademlia/impl/storage.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/kademlia/peer_routing.hpp b/include/libp2p/protocol/kademlia/peer_routing.hpp index d24d85cd4..4e086b1a6 100644 --- a/include/libp2p/protocol/kademlia/peer_routing.hpp +++ b/include/libp2p/protocol/kademlia/peer_routing.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/kademlia/routing.hpp b/include/libp2p/protocol/kademlia/routing.hpp index 1f2ffc15d..11b14a5f6 100644 --- a/include/libp2p/protocol/kademlia/routing.hpp +++ b/include/libp2p/protocol/kademlia/routing.hpp @@ -10,8 +10,6 @@ #include #include -#include - namespace libp2p::protocol::kademlia { class Routing : public ValueStore, public ContentRouting, public PeerRouting { diff --git a/include/libp2p/protocol/kademlia/storage_backend.hpp b/include/libp2p/protocol/kademlia/storage_backend.hpp index 9024fd70e..b62ebff3c 100644 --- a/include/libp2p/protocol/kademlia/storage_backend.hpp +++ b/include/libp2p/protocol/kademlia/storage_backend.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/kademlia/validator.hpp b/include/libp2p/protocol/kademlia/validator.hpp index c332b54d8..99779a6ef 100644 --- a/include/libp2p/protocol/kademlia/validator.hpp +++ b/include/libp2p/protocol/kademlia/validator.hpp @@ -8,7 +8,6 @@ #include -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/kademlia/value_store.hpp b/include/libp2p/protocol/kademlia/value_store.hpp index 258b6b61a..01a97f380 100644 --- a/include/libp2p/protocol/kademlia/value_store.hpp +++ b/include/libp2p/protocol/kademlia/value_store.hpp @@ -6,7 +6,6 @@ #pragma once -#include #include namespace libp2p::protocol::kademlia { diff --git a/include/libp2p/protocol/ping/ping.hpp b/include/libp2p/protocol/ping/ping.hpp index 7f8ebd659..11a013353 100644 --- a/include/libp2p/protocol/ping/ping.hpp +++ b/include/libp2p/protocol/ping/ping.hpp @@ -8,11 +8,10 @@ #include -#include +#include #include #include #include -#include #include #include @@ -40,7 +39,7 @@ namespace libp2p::protocol { */ Ping(Host &host, event::Bus &bus, - boost::asio::io_context &io_context, + std::shared_ptr scheduler, std::shared_ptr rand_gen, PingConfig config = PingConfig{}); @@ -61,7 +60,7 @@ namespace libp2p::protocol { private: Host &host_; event::Bus &bus_; - boost::asio::io_context &io_context_; + std::shared_ptr scheduler_; std::shared_ptr rand_gen_; PingConfig config_; }; diff --git a/include/libp2p/protocol/ping/ping_client_session.hpp b/include/libp2p/protocol/ping/ping_client_session.hpp index 7c2f47b9a..00c9e5e46 100644 --- a/include/libp2p/protocol/ping/ping_client_session.hpp +++ b/include/libp2p/protocol/ping/ping_client_session.hpp @@ -9,7 +9,7 @@ #include #include -#include +#include #include #include #include @@ -33,7 +33,7 @@ namespace libp2p::protocol { class PingClientSession : public std::enable_shared_from_this { public: - PingClientSession(boost::asio::io_service &io_service, + PingClientSession(std::shared_ptr scheduler, libp2p::event::Bus &bus, std::shared_ptr stream, std::shared_ptr rand_gen, @@ -46,13 +46,15 @@ namespace libp2p::protocol { private: void write(); - void writeCompleted(const boost::system::error_code &ec); + void writeCompleted(outcome::result r); void read(); - void readCompleted(const boost::system::error_code &ec); + void readCompleted(outcome::result r); - boost::asio::io_service &io_service_; + void close(); + + std::shared_ptr scheduler_; libp2p::event::Bus &bus_; decltype(bus_.getChannel()) channel_; @@ -61,10 +63,8 @@ namespace libp2p::protocol { PingConfig config_; std::vector write_buffer_, read_buffer_; - boost::asio::deadline_timer timer_; - - bool last_op_completed_ = false; - std::error_code last_error_; + basic::Scheduler::Handle timer_; + bool closed_ = false; bool is_started_ = false; }; diff --git a/include/libp2p/protocol/ping/ping_config.hpp b/include/libp2p/protocol/ping/ping_config.hpp index 8ef87118d..279dcf71a 100644 --- a/include/libp2p/protocol/ping/ping_config.hpp +++ b/include/libp2p/protocol/ping/ping_config.hpp @@ -6,13 +6,16 @@ #pragma once +#include #include namespace libp2p::protocol { struct PingConfig { /// now much Ping is going to wait before declaring other node dead (in /// ms) - uint32_t timeout = 30000; + std::chrono::milliseconds timeout = std::chrono::seconds{30}; + + std::chrono::milliseconds interval = std::chrono::seconds{30}; /// size of the Ping message to be sent or received (in bytes) uint32_t message_size = 32; diff --git a/include/libp2p/protocol_muxer/protocol_muxer.hpp b/include/libp2p/protocol_muxer/protocol_muxer.hpp index d4eea7e5f..b1f9226f0 100644 --- a/include/libp2p/protocol_muxer/protocol_muxer.hpp +++ b/include/libp2p/protocol_muxer/protocol_muxer.hpp @@ -10,7 +10,6 @@ #include #include -#include namespace libp2p::protocol_muxer { /** diff --git a/include/libp2p/security/error.hpp b/include/libp2p/security/error.hpp index 34c8d6734..4ae88dbc0 100644 --- a/include/libp2p/security/error.hpp +++ b/include/libp2p/security/error.hpp @@ -14,4 +14,4 @@ namespace libp2p::security { } -OUTCOME_HPP_DECLARE_ERROR(libp2p::security::SecurityError); +OUTCOME_HPP_DECLARE_ERROR(libp2p::security, SecurityError); diff --git a/include/libp2p/security/noise/crypto/interfaces.hpp b/include/libp2p/security/noise/crypto/interfaces.hpp index b4e2d58a9..f5dbcf042 100644 --- a/include/libp2p/security/noise/crypto/interfaces.hpp +++ b/include/libp2p/security/noise/crypto/interfaces.hpp @@ -13,7 +13,6 @@ #include #include #include -#include namespace libp2p::security::noise { @@ -22,7 +21,6 @@ namespace libp2p::security::noise { using libp2p::crypto::asVector; using crypto::common::HashType; - using libp2p::Bytes; struct HKDFResult { Bytes one; Bytes two; diff --git a/include/libp2p/security/noise/handshake.hpp b/include/libp2p/security/noise/handshake.hpp index c2ab8c389..849b2b5f1 100644 --- a/include/libp2p/security/noise/handshake.hpp +++ b/include/libp2p/security/noise/handshake.hpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include diff --git a/include/libp2p/security/noise/handshake_message_marshaller.hpp b/include/libp2p/security/noise/handshake_message_marshaller.hpp index 2b85afbf1..bd7b8a2e0 100644 --- a/include/libp2p/security/noise/handshake_message_marshaller.hpp +++ b/include/libp2p/security/noise/handshake_message_marshaller.hpp @@ -9,9 +9,7 @@ #include #include -#include #include -#include namespace libp2p::security::noise { diff --git a/include/libp2p/security/plaintext/exchange_message_marshaller.hpp b/include/libp2p/security/plaintext/exchange_message_marshaller.hpp index ee26701cf..2f63e3ab5 100644 --- a/include/libp2p/security/plaintext/exchange_message_marshaller.hpp +++ b/include/libp2p/security/plaintext/exchange_message_marshaller.hpp @@ -7,12 +7,10 @@ #pragma once #include -#include #include #include #include -#include namespace libp2p::security::plaintext { diff --git a/include/libp2p/security/secio/exchange_message_marshaller.hpp b/include/libp2p/security/secio/exchange_message_marshaller.hpp index 22760c281..516da83d1 100644 --- a/include/libp2p/security/secio/exchange_message_marshaller.hpp +++ b/include/libp2p/security/secio/exchange_message_marshaller.hpp @@ -6,11 +6,8 @@ #pragma once -#include - #include #include -#include namespace libp2p::security::secio { diff --git a/include/libp2p/security/secio/propose_message.hpp b/include/libp2p/security/secio/propose_message.hpp index 12b7a8cc2..e31ca69e1 100644 --- a/include/libp2p/security/secio/propose_message.hpp +++ b/include/libp2p/security/secio/propose_message.hpp @@ -7,6 +7,7 @@ #pragma once #include +#include namespace libp2p::security::secio { diff --git a/include/libp2p/security/secio/propose_message_marshaller.hpp b/include/libp2p/security/secio/propose_message_marshaller.hpp index 3e9ada375..4e1241afb 100644 --- a/include/libp2p/security/secio/propose_message_marshaller.hpp +++ b/include/libp2p/security/secio/propose_message_marshaller.hpp @@ -6,11 +6,8 @@ #pragma once -#include - #include #include -#include namespace libp2p::security::secio { diff --git a/include/libp2p/security/secio/secio_dialer.hpp b/include/libp2p/security/secio/secio_dialer.hpp index ee756e091..f17cbae5e 100644 --- a/include/libp2p/security/secio/secio_dialer.hpp +++ b/include/libp2p/security/secio/secio_dialer.hpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include diff --git a/include/libp2p/security/security_adaptor.hpp b/include/libp2p/security/security_adaptor.hpp index 78b65e010..ca0b94640 100644 --- a/include/libp2p/security/security_adaptor.hpp +++ b/include/libp2p/security/security_adaptor.hpp @@ -11,7 +11,6 @@ #include #include #include -#include #include namespace libp2p::security { diff --git a/include/libp2p/security/tls/tls_errors.hpp b/include/libp2p/security/tls/tls_errors.hpp index 5fe111245..351f3eea7 100644 --- a/include/libp2p/security/tls/tls_errors.hpp +++ b/include/libp2p/security/tls/tls_errors.hpp @@ -6,8 +6,6 @@ #pragma once -#include - namespace libp2p::security { enum class TlsError : int { diff --git a/include/libp2p/transport/impl/upgrader_impl.hpp b/include/libp2p/transport/impl/upgrader_impl.hpp index 54f4d51da..a2803f25c 100644 --- a/include/libp2p/transport/impl/upgrader_impl.hpp +++ b/include/libp2p/transport/impl/upgrader_impl.hpp @@ -15,7 +15,6 @@ #include #include #include -#include namespace libp2p::transport { class UpgraderImpl : public Upgrader, diff --git a/include/libp2p/transport/tcp/tcp_connection.hpp b/include/libp2p/transport/tcp/tcp_connection.hpp index b0dc9d80a..762ab8920 100644 --- a/include/libp2p/transport/tcp/tcp_connection.hpp +++ b/include/libp2p/transport/tcp/tcp_connection.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -135,7 +136,7 @@ namespace libp2p::transport { bool closed_by_host_ = false; /// Close reason, is set on close to respond to further calls - std::error_code close_reason_; + std::optional close_reason_; boost::optional remote_multiaddress_; boost::optional local_multiaddress_; diff --git a/include/libp2p/transport/tcp/tcp_util.hpp b/include/libp2p/transport/tcp/tcp_util.hpp index dd2e39ad0..f108edf20 100644 --- a/include/libp2p/transport/tcp/tcp_util.hpp +++ b/include/libp2p/transport/tcp/tcp_util.hpp @@ -12,8 +12,6 @@ #include #include #include -#include -#include namespace libp2p::transport::detail { template diff --git a/include/libp2p/transport/transport_adaptor.hpp b/include/libp2p/transport/transport_adaptor.hpp index bb732ccef..f2321f0aa 100644 --- a/include/libp2p/transport/transport_adaptor.hpp +++ b/include/libp2p/transport/transport_adaptor.hpp @@ -9,13 +9,11 @@ #include #include #include -#include #include #include #include #include -#include // for outcome::result #include #include diff --git a/include/libp2p/transport/upgrader.hpp b/include/libp2p/transport/upgrader.hpp index 49270a4c9..14d409957 100644 --- a/include/libp2p/transport/upgrader.hpp +++ b/include/libp2p/transport/upgrader.hpp @@ -12,7 +12,6 @@ #include #include #include -#include namespace libp2p::transport { diff --git a/src/basic/scheduler/asio_scheduler_backend.cpp b/src/basic/scheduler/asio_scheduler_backend.cpp index 5fd7c4ce6..0c7ee89f9 100644 --- a/src/basic/scheduler/asio_scheduler_backend.cpp +++ b/src/basic/scheduler/asio_scheduler_backend.cpp @@ -38,7 +38,7 @@ namespace libp2p::basic { if (ec) { // this should never happen auto log = log::createLogger("Scheduler", "scheduler"); - log->critical("cannot set timer: {}", ec.message()); + log->critical("cannot set timer: {}", ec); boost::asio::detail::throw_error(ec, "setTimer"); } diff --git a/src/common/hexutil.cpp b/src/common/hexutil.cpp index 326a2291d..0a645a173 100644 --- a/src/common/hexutil.cpp +++ b/src/common/hexutil.cpp @@ -6,10 +6,6 @@ #include -#include - -#include - OUTCOME_CPP_DEFINE_CATEGORY(libp2p::common, UnhexError, e) { using libp2p::common::UnhexError; switch (e) { @@ -23,23 +19,6 @@ OUTCOME_CPP_DEFINE_CATEGORY(libp2p::common, UnhexError, e) { } namespace libp2p::common { - - std::string int_to_hex(uint64_t n, size_t fixed_width) noexcept { - std::stringstream result; - result.width(static_cast(fixed_width)); - result.fill('0'); - result << std::hex << std::uppercase << n; - auto str = result.str(); - if (str.length() % 2 != 0) { - str.push_back('\0'); - for (int64_t i = static_cast(str.length()) - 2; i >= 0; --i) { - str[i + 1] = str[i]; - } - str[0] = '0'; - } - return str; - } - outcome::result> unhex(std::string_view hex) { std::vector blob; blob.reserve((hex.size() + 1) / 2); diff --git a/src/connection/loopback_stream.cpp b/src/connection/loopback_stream.cpp index 3e765b4f4..8cc92ff1e 100644 --- a/src/connection/loopback_stream.cpp +++ b/src/connection/loopback_stream.cpp @@ -12,11 +12,11 @@ namespace libp2p::connection { namespace { - template + template void deferCallback(boost::asio::io_context &ctx, std::weak_ptr wptr, Callback cb, - Arg arg) { + outcome::result arg) { // defers callback to the next event loop cycle, // cb will be called iff Loopbackstream is still exists boost::asio::post( @@ -106,7 +106,7 @@ namespace libp2p::connection { buffer_.commit(bytes); // intentionally used deferReadCallback, since it acquires bytes written - deferReadCallback(outcome::success(bytes), std::move(cb)); + deferReadCallback(bytes, std::move(cb)); /* The whole approach with such methods (deferReadCallback and * deferWriteCallback) is going to be avoided in the near future, thus we do * not remove from the source code the counting of bytes written */ @@ -174,7 +174,8 @@ namespace libp2p::connection { void LoopbackStream::deferReadCallback(outcome::result res, basic::Reader::ReadCallbackFunc cb) { - deferCallback(*io_context_, weak_from_this(), std::move(cb), res); + deferCallback( + *io_context_, weak_from_this(), std::move(cb), std::move(res)); } void LoopbackStream::deferWriteCallback(std::error_code ec, diff --git a/src/crypto/aes_provider/aes_ctr_impl.cpp b/src/crypto/aes_provider/aes_ctr_impl.cpp index 4ed1554de..0af5b40e1 100644 --- a/src/crypto/aes_provider/aes_ctr_impl.cpp +++ b/src/crypto/aes_provider/aes_ctr_impl.cpp @@ -13,7 +13,6 @@ namespace libp2p::crypto::aes { - using libp2p::Bytes; using libp2p::crypto::common::Aes128Secret; using libp2p::crypto::common::Aes256Secret; diff --git a/src/crypto/key_validator/key_validator_impl.cpp b/src/crypto/key_validator/key_validator_impl.cpp index 4963ff96d..429057f6c 100644 --- a/src/crypto/key_validator/key_validator_impl.cpp +++ b/src/crypto/key_validator/key_validator_impl.cpp @@ -8,7 +8,6 @@ #include #include -#include #include using libp2p::common::FinalAction; diff --git a/src/crypto/rsa_provider/rsa_provider_impl.cpp b/src/crypto/rsa_provider/rsa_provider_impl.cpp index ee81691b5..ce92af9f9 100644 --- a/src/crypto/rsa_provider/rsa_provider_impl.cpp +++ b/src/crypto/rsa_provider/rsa_provider_impl.cpp @@ -20,8 +20,8 @@ using libp2p::common::FinalAction; namespace { /// encode cryptographic key in `ASN.1 DER` format template - libp2p::outcome::result> encodeKeyDer( - KeyStructure *ks, Function *function) { + outcome::result> encodeKeyDer(KeyStructure *ks, + Function *function) { unsigned char *buffer = nullptr; FinalAction cleanup([pptr = &buffer] { if (*pptr != nullptr) { diff --git a/src/host/basic_host/basic_host.cpp b/src/host/basic_host/basic_host.cpp index ff1bae31a..d52140f2d 100644 --- a/src/host/basic_host/basic_host.cpp +++ b/src/host/basic_host/basic_host.cpp @@ -7,7 +7,6 @@ #include #include -#include #include namespace libp2p::host { diff --git a/src/multi/content_identifier.cpp b/src/multi/content_identifier.cpp index cd12bc9f3..df9663301 100644 --- a/src/multi/content_identifier.cpp +++ b/src/multi/content_identifier.cpp @@ -6,9 +6,6 @@ #include -#include -#include - namespace libp2p::multi { ContentIdentifier::ContentIdentifier(Version version, @@ -18,21 +15,6 @@ namespace libp2p::multi { content_type{content_type}, content_address{std::move(content_address)} {} - std::string ContentIdentifier::toPrettyString(const std::string &base) const { - /// TODO(Harrm) FIL-14: hash type is a subset of multicodec type, better - /// move them to one place - std::string hash_type = MulticodecType::getName( - static_cast(content_address.getType())); - std::string hash_hex = common::hex_lower(content_address.getHash()); - std::string hash_length = - std::to_string(content_address.getHash().size() * 8); - std::string v = "cidv" + std::to_string(static_cast(version)); - return (boost::format("%1% - %2% - %3% - %4%-%5%-%6%") % base % v - % MulticodecType::getName(content_type) % hash_type % hash_length - % hash_hex) - .str(); - } - bool ContentIdentifier::operator==(const ContentIdentifier &c) const { return version == c.version and content_type == c.content_type and content_address == c.content_address; diff --git a/src/multi/content_identifier_codec.cpp b/src/multi/content_identifier_codec.cpp index 5c185a71b..d26d7806e 100644 --- a/src/multi/content_identifier_codec.cpp +++ b/src/multi/content_identifier_codec.cpp @@ -56,13 +56,14 @@ namespace libp2p::multi { const ContentIdentifier &cid) { std::vector bytes; if (cid.version == ContentIdentifier::Version::V1) { + auto append = [&](BytesIn x) { + bytes.insert(bytes.end(), x.begin(), x.end()); + }; UVarint version(static_cast(cid.version)); - common::append(bytes, version.toBytes()); + append(version.toBytes()); UVarint type(static_cast(cid.content_type)); - common::append(bytes, type.toBytes()); - const auto &hash = cid.content_address.toBuffer(); - common::append(bytes, hash); - + append(type.toBytes()); + append(cid.content_address.toBuffer()); } else if (cid.version == ContentIdentifier::Version::V0) { if (cid.content_type != MulticodecType::Code::DAG_PB) { return EncodeError::INVALID_CONTENT_TYPE; @@ -73,8 +74,7 @@ namespace libp2p::multi { if (cid.content_address.getHash().size() != 32) { return EncodeError::INVALID_HASH_LENGTH; } - const auto &hash = cid.content_address.toBuffer(); - common::append(bytes, hash); + bytes = cid.content_address.toBuffer(); } return bytes; } diff --git a/src/multi/converters/CMakeLists.txt b/src/multi/converters/CMakeLists.txt index 44b5da854..9e63eb8d6 100644 --- a/src/multi/converters/CMakeLists.txt +++ b/src/multi/converters/CMakeLists.txt @@ -16,7 +16,6 @@ libp2p_add_library(p2p_converters ) target_link_libraries(p2p_converters Boost::boost - p2p_hexutil p2p_byteutil p2p_uvarint p2p_multibase_codec diff --git a/src/multi/converters/converter_utils.cpp b/src/multi/converters/converter_utils.cpp index 911cdeb5c..8df994241 100644 --- a/src/multi/converters/converter_utils.cpp +++ b/src/multi/converters/converter_utils.cpp @@ -6,11 +6,12 @@ #include -#include +#include + #include #include #include -#include +#include #include #include #include @@ -20,12 +21,65 @@ #include #include #include -#include +#include #include -#include -using libp2p::common::hex_upper; -using libp2p::common::unhex; +// TODO(turuslan): qtils, https://github.com/qdrvm/kagome/issues/1813 +namespace qtils { + inline std::string_view byte2str(const libp2p::BytesIn &s) { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) + return {reinterpret_cast(s.data()), s.size()}; + } +} // namespace qtils + +// https://github.com/multiformats/rust-multiaddr/blob/3c7e813c3b1fdd4187a9ca9ff67e10af0e79231d/src/protocol.rs#L613-L622 +inline void percentEncode(std::string &out, std::string_view str) { + constexpr std::array mask{ + 0xffffffff, + 0xd000802d, + 0x00000000, + 0xa8000001, + }; + for (const auto &c : str) { + if (static_cast(c) > 0x7f + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) + or (mask[c / 32] & (1 << (c % 32))) != 0) { + fmt::format_to(std::back_inserter(out), "%{:02X}", c); + } else { + out += c; + } + } +} + +// https://github.com/multiformats/rust-multiaddr/blob/3c7e813c3b1fdd4187a9ca9ff67e10af0e79231d/src/protocol.rs#L203-L212 +inline std::string percentDecode(std::string_view str) { + auto f = [&](char c) -> std::optional { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + return std::nullopt; + }; + std::string out; + while (not str.empty()) { + if (str[0] == '%' and str.size() >= 3) { + auto x1 = f(str[1]), x2 = f(str[2]); + if (x1 and x2) { + out.push_back((*x1 << 4) | *x2); + str.remove_prefix(3); + continue; + } + } + out.push_back(str[0]); + str.remove_prefix(1); + } + return out; +} namespace libp2p::multi::converters { @@ -112,9 +166,10 @@ namespace libp2p::multi::converters { case Protocol::Code::DNS6: case Protocol::Code::DNS_ADDR: case Protocol::Code::UNIX: + return DnsConverter::addressToBytes(addr); case Protocol::Code::X_PARITY_WS: case Protocol::Code::X_PARITY_WSS: - return DnsConverter::addressToBytes(addr); + return DnsConverter::addressToBytes(percentDecode(addr)); case Protocol::Code::IP6_ZONE: case Protocol::Code::ONION3: @@ -132,164 +187,105 @@ namespace libp2p::multi::converters { } } - outcome::result addressToHex(const Protocol &protocol, - std::string_view addr) { - OUTCOME_TRY(bytes, addressToBytes(protocol, addr)); - std::string hex; - hex.reserve(bytes.size() * 2); - boost::algorithm::hex_lower( - bytes.begin(), bytes.end(), std::back_inserter(hex)); - return std::move(hex); - } - outcome::result bytesToMultiaddrString(BytesIn bytes) { + auto read = [&](size_t n) -> outcome::result { + if (n > bytes.size()) { + return ConversionError::INVALID_ADDRESS; + } + auto r = bytes.first(n); + bytes = bytes.subspan(n); + return r; + }; + auto uvar = [&]() -> outcome::result { + auto var = UVarint::create(bytes); + if (not var) { + return ConversionError::INVALID_ADDRESS; + } + bytes = bytes.subspan(var->size()); + return var->toUInt64(); + }; + auto read_uvar = [&]() -> outcome::result { + OUTCOME_TRY(n, uvar()); + return read(n); + }; std::string results; - - size_t lastpos = 0; - - // set up variables - const std::string hex = hex_upper(bytes); - - // Process Hex String - while (lastpos < bytes.size() * 2) { - BytesIn pid_bytes{bytes}; - auto protocol_int = UVarint(pid_bytes.subspan(lastpos / 2)).toUInt64(); + while (not bytes.empty()) { + OUTCOME_TRY(protocol_num, uvar()); const Protocol *protocol = - ProtocolList::get(static_cast(protocol_int)); + ProtocolList::get(static_cast(protocol_num)); if (protocol == nullptr) { return ConversionError::NO_SUCH_PROTOCOL; } - - if (protocol->code != Protocol::Code::P2P) { - lastpos += (UVarint::calculateSize(pid_bytes.subspan(lastpos / 2)) * 2); - std::string address; - address = hex.substr(lastpos, protocol->size / 4); - - lastpos = lastpos + (protocol->size / 4); - - results += "/"; - results += protocol->name; - - if (protocol->size == 0) { - continue; + results += "/"; + results += protocol->name; + if (protocol->size == 0) { + continue; + } + switch (protocol->code) { + case Protocol::Code::P2P: { + OUTCOME_TRY(data, read_uvar()); + results += "/"; + results += detail::encodeBase58(data); + break; } - try { - switch (protocol->code) { - case Protocol::Code::DNS: - case Protocol::Code::DNS4: - case Protocol::Code::DNS6: - case Protocol::Code::DNS_ADDR: { - // fetch the size of the address based on the varint prefix - auto prefixedvarint = hex.substr(lastpos, 2); - OUTCOME_TRY(prefixBytes, unhex(prefixedvarint)); - - auto addrsize = UVarint(prefixBytes).toUInt64(); - - // get the ipfs address as hex values - auto hex_domain_name = hex.substr(lastpos + 2, addrsize * 2); - OUTCOME_TRY(domain_name, unhex(hex_domain_name)); - - lastpos += addrsize * 2 + 2; - - // Add domain name - results += "/"; - results += std::string(domain_name.begin(), domain_name.end()); - - auto i = std::find_if_not( - domain_name.begin(), domain_name.end(), [](auto c) { - return std::isalnum(c) || c == '-' || c == '.'; - }); - if (i != domain_name.end()) { - return ConversionError::INVALID_ADDRESS; - } - break; - } - - case Protocol::Code::X_PARITY_WS: - case Protocol::Code::X_PARITY_WSS: { - // fetch the size of the address based on the varint prefix - auto prefixedvarint = hex.substr(lastpos, 2); - OUTCOME_TRY(prefixBytes, unhex(prefixedvarint)); - - auto addrsize = UVarint(prefixBytes).toUInt64(); - - // get the ipfs address as hex values - auto hex_domain_name = hex.substr(lastpos + 2, addrsize * 2); - OUTCOME_TRY(domain_name, unhex(hex_domain_name)); - - lastpos += addrsize * 2 + 2; - - results += "/"; - results += std::string(domain_name.begin(), domain_name.end()); - break; - } - - case Protocol::Code::IP4: { - // Add IP - results += "/"; - results += boost::asio::ip::make_address_v4( - std::stoul(address, nullptr, 16)) - .to_string(); - break; - } - - case Protocol::Code::IP6: { - // Add IP - OUTCOME_TRY(addr_bytes, unhex(address)); - std::array arr{}; - std::copy_n(addr_bytes.begin(), 16, arr.begin()); - results += "/"; - results += boost::asio::ip::make_address_v6(arr).to_string(); - break; - } - - case Protocol::Code::TCP: - case Protocol::Code::UDP: { - // Add port - results += "/"; - results += std::to_string(std::stoul(address, nullptr, 16)); - break; - } + case Protocol::Code::DNS: + case Protocol::Code::DNS4: + case Protocol::Code::DNS6: + case Protocol::Code::DNS_ADDR: { + OUTCOME_TRY(data, read_uvar()); + auto name = qtils::byte2str(data); + const auto *i = + std::find_if_not(name.begin(), name.end(), [](auto c) { + return std::isalnum(c) || c == '-' || c == '.'; + }); + if (i != name.end()) { + return ConversionError::INVALID_ADDRESS; + } + results += "/"; + results += name; + break; + } - case Protocol::Code::QUIC: - case Protocol::Code::WS: - case Protocol::Code::WSS: - // No details - break; + case Protocol::Code::X_PARITY_WS: + case Protocol::Code::X_PARITY_WSS: { + OUTCOME_TRY(data, read_uvar()); + results += "/"; + percentEncode(results, qtils::byte2str(data)); + break; + } - default: - return ConversionError::NOT_IMPLEMENTED; - } - } catch (const std::exception &e) { - return ConversionError::INVALID_ADDRESS; + case Protocol::Code::IP4: { + std::array arr{}; + OUTCOME_TRY(data, read(arr.size())); + std::copy(data.begin(), data.end(), arr.begin()); + results += "/"; + results += boost::asio::ip::make_address_v4(arr).to_string(); + break; } - } else { - lastpos = lastpos + 4; - // fetch the size of the address based on the varint prefix - auto prefixedvarint = hex.substr(lastpos, 2); - OUTCOME_TRY(prefixBytes, unhex(prefixedvarint)); + case Protocol::Code::IP6: { + std::array arr{}; + OUTCOME_TRY(data, read(arr.size())); + std::copy(data.begin(), data.end(), arr.begin()); + results += "/"; + results += boost::asio::ip::make_address_v6(arr).to_string(); + break; + } - auto addrsize = UVarint(prefixBytes).toUInt64(); - // get the ipfs address as hex values - auto ipfsAddr = hex.substr(lastpos + 2, addrsize * 2); + case Protocol::Code::TCP: + case Protocol::Code::UDP: { + OUTCOME_TRY(data, read(sizeof(uint16_t))); + results += "/"; + results += std::to_string(boost::endian::load_big_u16(data.data())); + break; + } - // convert the address from hex values to a binary array - OUTCOME_TRY(addrbuf, unhex(ipfsAddr)); - auto encode_res = MultibaseCodecImpl{}.encode( - addrbuf, MultibaseCodecImpl::Encoding::BASE58); - encode_res.erase(0, 1); // because multibase contains a char that - // denotes which base is used - results += "/p2p/" + encode_res; - lastpos += addrsize * 2 + 2; + default: + return ConversionError::NOT_IMPLEMENTED; } } return results; } - - outcome::result bytesToMultiaddrString(const Bytes &bytes) { - return bytesToMultiaddrString(BytesIn(bytes)); - } } // namespace libp2p::multi::converters diff --git a/src/multi/converters/dns_converter.cpp b/src/multi/converters/dns_converter.cpp index 9a6424d08..2fa4397ee 100644 --- a/src/multi/converters/dns_converter.cpp +++ b/src/multi/converters/dns_converter.cpp @@ -6,23 +6,9 @@ #include -#include - #include namespace libp2p::multi::converters { - - outcome::result DnsConverter::addressToHex( - std::string_view addr) { - outcome::result res = outcome::success(); // NRVO - auto &hex = res.value(); - hex = UVarint(addr.size()).toHex(); - hex.reserve(hex.size() + addr.size() * 2); - boost::algorithm::hex_lower( - addr.begin(), addr.end(), std::back_inserter(hex)); - return res; - } - outcome::result DnsConverter::addressToBytes(std::string_view addr) { outcome::result res = outcome::success(); // NRVO auto &bytes = res.value(); diff --git a/src/multi/converters/ip_v4_converter.cpp b/src/multi/converters/ip_v4_converter.cpp index 0151883ad..1256d3db9 100644 --- a/src/multi/converters/ip_v4_converter.cpp +++ b/src/multi/converters/ip_v4_converter.cpp @@ -7,24 +7,9 @@ #include #include -#include #include namespace libp2p::multi::converters { - - outcome::result IPv4Converter::addressToHex( - std::string_view addr) { - boost::system::error_code ec; - auto address = boost::asio::ip::make_address_v4(addr, ec); - if (ec) { - return ConversionError::INVALID_ADDRESS; - } - uint32_t iip = address.to_uint(); - auto hex = common::int_to_hex(iip); - hex = std::string(8 - hex.length(), '0') + hex; - return hex; - } - outcome::result IPv4Converter::addressToBytes(std::string_view addr) { boost::system::error_code ec; auto address = boost::asio::ip::make_address_v4(addr, ec); diff --git a/src/multi/converters/ip_v6_converter.cpp b/src/multi/converters/ip_v6_converter.cpp index e13088a7c..1c9103f36 100644 --- a/src/multi/converters/ip_v6_converter.cpp +++ b/src/multi/converters/ip_v6_converter.cpp @@ -7,7 +7,6 @@ #include #include -#include #include namespace libp2p::multi::converters { diff --git a/src/multi/converters/ipfs_converter.cpp b/src/multi/converters/ipfs_converter.cpp index 324d5184a..a481da70b 100644 --- a/src/multi/converters/ipfs_converter.cpp +++ b/src/multi/converters/ipfs_converter.cpp @@ -8,39 +8,14 @@ #include -#include -#include #include #include #include #include -#include using std::string_literals::operator""s; namespace libp2p::multi::converters { - - outcome::result IpfsConverter::addressToHex( - std::string_view addr) { - std::string encoded = - static_cast(MultibaseCodecImpl::Encoding::BASE58) - + std::string(addr); - - MultibaseCodecImpl codec; - auto decoded_res = codec.decode(encoded); - if (decoded_res.has_error()) { - return ConversionError::INVALID_ADDRESS; - } - auto &decoded = decoded_res.value(); - - // throw everything in a hex string so we can debug the results - std::string hex = UVarint(decoded.size()).toHex(); - hex.reserve(hex.size() + addr.size() * 2); - boost::algorithm::hex_lower( - decoded.begin(), decoded.end(), std::back_inserter(hex)); - return std::move(hex); - } - outcome::result IpfsConverter::addressToBytes(std::string_view addr) { std::string encoded = static_cast(MultibaseCodecImpl::Encoding::BASE58) diff --git a/src/multi/converters/tcp_converter.cpp b/src/multi/converters/tcp_converter.cpp index 9fb764661..8fb14ec3e 100644 --- a/src/multi/converters/tcp_converter.cpp +++ b/src/multi/converters/tcp_converter.cpp @@ -7,30 +7,9 @@ #include #include -#include #include namespace libp2p::multi::converters { - - outcome::result TcpConverter::addressToHex( - std::string_view addr) { - for (auto c : addr) { - if (std::isdigit(c) == 0) { - return ConversionError::INVALID_ADDRESS; - } - } - int64_t port_int = 0; - try { - port_int = std::stoi(std::string(addr)); - } catch (std::exception &e) { - return ConversionError::INVALID_ADDRESS; - } - if (port_int >= 0 and port_int <= 65535) { - return common::int_to_hex(port_int, 4); - } - return ConversionError::INVALID_ADDRESS; - } - outcome::result TcpConverter::addressToBytes(std::string_view addr) { for (auto c : addr) { if (std::isdigit(c) == 0) { diff --git a/src/multi/converters/udp_converter.cpp b/src/multi/converters/udp_converter.cpp index 371bf9b58..1764fc251 100644 --- a/src/multi/converters/udp_converter.cpp +++ b/src/multi/converters/udp_converter.cpp @@ -7,30 +7,9 @@ #include #include -#include #include namespace libp2p::multi::converters { - - outcome::result UdpConverter::addressToHex( - std::string_view addr) { - for (auto c : addr) { - if (std::isdigit(c) == 0) { - return ConversionError::INVALID_ADDRESS; - } - } - int64_t port_int = 0; - try { - port_int = std::stoi(std::string(addr)); - } catch (std::exception &e) { - return ConversionError::INVALID_ADDRESS; - } - if (port_int >= 0 and port_int <= 65535) { - return common::int_to_hex(port_int, 4); - } - return ConversionError::INVALID_ADDRESS; - } - outcome::result UdpConverter::addressToBytes(std::string_view addr) { for (auto c : addr) { if (std::isdigit(c) == 0) { diff --git a/src/multi/multibase_codec/codecs/base16.cpp b/src/multi/multibase_codec/codecs/base16.cpp index e3b401fce..06fce528f 100644 --- a/src/multi/multibase_codec/codecs/base16.cpp +++ b/src/multi/multibase_codec/codecs/base16.cpp @@ -32,11 +32,11 @@ namespace libp2p::multi::detail { using common::hex_upper; using common::unhex; - std::string encodeBase16Upper(const Bytes &bytes) { + std::string encodeBase16Upper(BytesIn bytes) { return hex_upper(bytes); } - std::string encodeBase16Lower(const Bytes &bytes) { + std::string encodeBase16Lower(BytesIn bytes) { return hex_lower(bytes); } diff --git a/src/multi/multibase_codec/codecs/base32.cpp b/src/multi/multibase_codec/codecs/base32.cpp index 4e3055d94..5a0feb5aa 100644 --- a/src/multi/multibase_codec/codecs/base32.cpp +++ b/src/multi/multibase_codec/codecs/base32.cpp @@ -88,7 +88,7 @@ namespace libp2p::multi::detail { return 8; } - std::string encodeBase32(const Bytes &bytes, Base32Mode mode) { + std::string encodeBase32(BytesIn bytes, Base32Mode mode) { std::string result; if (bytes.size() % 5 == 0) { result = std::string(bytes.size() / 5 * 8, ' '); @@ -109,11 +109,11 @@ namespace libp2p::multi::detail { return result; } - std::string encodeBase32Upper(const Bytes &bytes) { + std::string encodeBase32Upper(BytesIn bytes) { return encodeBase32(bytes, Base32Mode::UPPER); } - std::string encodeBase32Lower(const Bytes &bytes) { + std::string encodeBase32Lower(BytesIn bytes) { return encodeBase32(bytes, Base32Mode::LOWER); } diff --git a/src/multi/multibase_codec/codecs/base58.cpp b/src/multi/multibase_codec/codecs/base58.cpp index 550d18e25..924ecadf7 100644 --- a/src/multi/multibase_codec/codecs/base58.cpp +++ b/src/multi/multibase_codec/codecs/base58.cpp @@ -169,7 +169,7 @@ namespace libp2p::multi::detail { return vch; } - std::string encodeBase58(const Bytes &bytes) { + std::string encodeBase58(BytesIn bytes) { return encodeImpl(bytes.begin().base(), bytes.end().base()); } diff --git a/src/multi/multibase_codec/codecs/base64.cpp b/src/multi/multibase_codec/codecs/base64.cpp index 83209ae61..1a3541845 100644 --- a/src/multi/multibase_codec/codecs/base64.cpp +++ b/src/multi/multibase_codec/codecs/base64.cpp @@ -91,7 +91,7 @@ namespace libp2p::multi::detail { * @param bytes to be encoded * @return how much chars are in the resulting string */ - size_t encodeImpl(std::string &out, const Bytes &bytes) { + size_t encodeImpl(std::string &out, BytesIn bytes) { auto len = bytes.size(); const auto tab = alphabet; size_t bytes_pos = 0u; @@ -183,7 +183,7 @@ namespace libp2p::multi::detail { return out; } - std::string encodeBase64(const Bytes &bytes) { + std::string encodeBase64(BytesIn bytes) { std::string dest; dest.resize(encodeImpl(dest, bytes)); return dest; diff --git a/src/multi/multihash.cpp b/src/multi/multihash.cpp index e52f9cc0a..977732a47 100644 --- a/src/multi/multihash.cpp +++ b/src/multi/multihash.cpp @@ -12,7 +12,6 @@ #include #include -using libp2p::Bytes; using libp2p::common::hex_upper; using libp2p::common::unhex; diff --git a/src/multi/uvarint.cpp b/src/multi/uvarint.cpp index 71751ac68..d43306f14 100644 --- a/src/multi/uvarint.cpp +++ b/src/multi/uvarint.cpp @@ -51,9 +51,7 @@ namespace libp2p::multi { } BytesIn UVarint::toBytes() const & { - return std::span(bytes_.data(), - // NOLINTNEXTLINE(cppcoreguidelines-narrowing-conversions) - bytes_.size()); + return bytes_; } const std::vector &UVarint::toVector() const { diff --git a/src/muxer/mplex/mplex_stream.cpp b/src/muxer/mplex/mplex_stream.cpp index 2c3b17d27..9a82c78dc 100644 --- a/src/muxer/mplex/mplex_stream.cpp +++ b/src/muxer/mplex/mplex_stream.cpp @@ -14,11 +14,11 @@ #include #include -#define TRY_GET_CONNECTION(conn_var_name) \ - if (connection_.expired()) { \ - return Error::STREAM_RESET_BY_HOST; \ - } \ - auto(conn_var_name) = connection_.lock(); +#define TRY_GET_CONNECTION(tmp) \ + auto tmp = connection_.lock(); \ + if (tmp == nullptr) { \ + return Error::STREAM_RESET_BY_HOST; \ + } namespace libp2p::connection { std::string MplexStream::StreamId::toString() const { @@ -121,7 +121,7 @@ namespace libp2p::connection { if (!write_res) { self->log_->error("write for stream {} failed: {}", self->stream_id_.toString(), - write_res.error().message()); + write_res.error()); } cb(std::forward(write_res)); @@ -168,7 +168,7 @@ namespace libp2p::connection { if (!close_res) { self->log_->error("cannot close stream {} for writes: {}", self->stream_id_.toString(), - close_res.error().message()); + close_res.error()); return cb(close_res.error()); } diff --git a/src/muxer/mplex/mplexed_connection.cpp b/src/muxer/mplex/mplexed_connection.cpp index 784f5e462..b7b519040 100644 --- a/src/muxer/mplex/mplexed_connection.cpp +++ b/src/muxer/mplex/mplexed_connection.cpp @@ -73,7 +73,7 @@ namespace libp2p::connection { auto &&create_res) { if (!create_res) { self->log_->error("stream creation failed: {}", - create_res.error().message()); + create_res.error()); return cb(create_res.error()); } @@ -180,7 +180,7 @@ namespace libp2p::connection { void MplexedConnection::onWriteCompleted(outcome::result write_res) { if (!write_res) { - log_->error("data write failed: {}", write_res.error().message()); + log_->error("data write failed: {}", write_res.error()); } write_queue_.front().cb(std::forward(write_res)); @@ -197,7 +197,7 @@ namespace libp2p::connection { [self{shared_from_this()}](auto &&frame_res) mutable { if (!frame_res) { self->log_->error("cannot read frame from the connection: {}", - frame_res.error().message()); + frame_res.error()); return self->closeSession(); } @@ -273,7 +273,7 @@ namespace libp2p::connection { if (!commit_res) { return log_->error("failed to commit data for stream {}: {}", stream_id.toString(), - commit_res.error().message()); + commit_res.error()); } } @@ -322,7 +322,7 @@ namespace libp2p::connection { if (!reset_res) { self->log_->error("cannot reset stream {}: {}", stream_id.toString(), - reset_res.error().message()); + reset_res.error()); } }}); } @@ -341,8 +341,7 @@ namespace libp2p::connection { auto close_res = close(); if (!close_res) { - log_->error("cannot close the connection: {}", - close_res.error().message()); + log_->error("cannot close the connection: {}", close_res.error()); } } diff --git a/src/muxer/yamux/yamux.cpp b/src/muxer/yamux/yamux.cpp index 2984c7143..723f50847 100644 --- a/src/muxer/yamux/yamux.cpp +++ b/src/muxer/yamux/yamux.cpp @@ -40,7 +40,7 @@ namespace libp2p::muxer { } if (auto res = conn->remotePeer(); res.has_error()) { log::createLogger("Yamux")->error( - "inactive connection passed to muxer: {}", res.error().message()); + "inactive connection passed to muxer: {}", res.error()); return cb(res.error()); } cb(std::make_shared( diff --git a/src/muxer/yamux/yamux_stream.cpp b/src/muxer/yamux/yamux_stream.cpp index ce951d4f3..95b26043f 100644 --- a/src/muxer/yamux/yamux_stream.cpp +++ b/src/muxer/yamux/yamux_stream.cpp @@ -86,7 +86,7 @@ namespace libp2p::connection { } bool YamuxStream::isClosed() const noexcept { - return close_reason_.value() != 0; + return close_reason_.has_value(); } void YamuxStream::close(VoidResultHandlerFunc cb) { @@ -95,7 +95,7 @@ namespace libp2p::connection { feedback_.deferCall([wptr{weak_from_this()}, cb{std::move(cb)}] { auto self = wptr.lock(); if (self) { - cb(self->close_reason_); + cb(*self->close_reason_); } }); } @@ -120,7 +120,7 @@ namespace libp2p::connection { if (!close_reason_) { close_reason_ = Error::STREAM_CLOSED_BY_HOST; } else if (close_reason_ != Error::STREAM_CLOSED_BY_HOST) { - p.second = close_reason_; + p.second = *close_reason_; } if (close_cb_) { p.first.swap(close_cb_); @@ -144,7 +144,7 @@ namespace libp2p::connection { void YamuxStream::adjustWindowSize(uint32_t new_size, VoidResultHandlerFunc cb) { - std::error_code ec = close_reason_; + auto ec = close_reason_; if (!ec) { if (!is_readable_) { ec = Error::STREAM_NOT_READABLE; @@ -174,7 +174,7 @@ namespace libp2p::connection { if (!ec) { cb(outcome::success()); } else { - cb(ec); + cb(*ec); } }); } @@ -217,9 +217,6 @@ namespace libp2p::connection { } TRACE("stream {} read {} bytes", stream_id_, sz); - if (sz < 80) { - TRACE("{}", common::dumpBin(bytes)); - } bool overflow = false; bool read_completed = false; @@ -345,12 +342,10 @@ namespace libp2p::connection { } void YamuxStream::closedByConnection(std::error_code ec) { - doClose(ec, true); + doClose(std::move(ec), true); } void YamuxStream::doClose(std::error_code ec, bool notify_read_side) { - assert(ec); - if (close_reason_) { // already closed return; @@ -437,7 +432,7 @@ namespace libp2p::connection { } if (close_reason_) { - return deferReadCallback(close_reason_, std::move(cb)); + return deferReadCallback(*close_reason_, std::move(cb)); } if (is_reading_) { @@ -474,7 +469,7 @@ namespace libp2p::connection { r.first.swap(read_cb_); if (!is_readable_) { if (close_reason_) { - r.second = close_reason_; + r.second = *close_reason_; } else { // FIN received, but not yet closed r.second = Error::STREAM_CLOSED_BY_PEER; @@ -534,7 +529,10 @@ namespace libp2p::connection { } if (close_reason_) { - return deferWriteCallback(close_reason_, std::move(cb)); + return deferWriteCallback( + std::error_code{}, + [cb{std::move(cb)}, res{*close_reason_}]( + outcome::result) mutable { cb(std::move(res)); }); } if (!write_queue_.canEnqueue(bytes)) { diff --git a/src/muxer/yamux/yamuxed_connection.cpp b/src/muxer/yamux/yamuxed_connection.cpp index f76cbd90b..6e7e60697 100644 --- a/src/muxer/yamux/yamuxed_connection.cpp +++ b/src/muxer/yamux/yamuxed_connection.cpp @@ -140,13 +140,13 @@ namespace libp2p::connection { void YamuxedConnection::newStream(StreamHandlerFunc cb) { if (!started_) { return connection_->deferWriteCallback( - Error::CONNECTION_NOT_ACTIVE, + std::error_code{}, [cb = std::move(cb)](auto) { cb(Error::CONNECTION_NOT_ACTIVE); }); } if (streams_.size() >= config_.maximum_streams) { return connection_->deferWriteCallback( - Error::CONNECTION_TOO_MANY_STREAMS, [cb = std::move(cb)](auto) { + std::error_code{}, [cb = std::move(cb)](auto) { cb(Error::CONNECTION_TOO_MANY_STREAMS); }); } @@ -246,11 +246,10 @@ namespace libp2p::connection { } if (!res) { - std::error_code ec = res.error(); - if (ec.value() == boost::asio::error::eof) { - ec = Error::CONNECTION_CLOSED_BY_PEER; + if (res.error() == make_error_code(boost::asio::error::eof)) { + res.error() = Error::CONNECTION_CLOSED_BY_PEER; } - close(ec, boost::none); + close(std::move(res.error()), boost::none); return; } @@ -567,8 +566,7 @@ namespace libp2p::connection { started_ = false; - SL_DEBUG( - log(), "closing connection, reason: {}", notify_streams_code.message()); + SL_DEBUG(log(), "closing connection, reason: {}", notify_streams_code); write_queue_.clear(); diff --git a/src/network/cares/cares.cpp b/src/network/cares/cares.cpp index 1556ca5ca..0ded56eb0 100644 --- a/src/network/cares/cares.cpp +++ b/src/network/cares/cares.cpp @@ -6,6 +6,7 @@ #include +#include #include #include #include diff --git a/src/network/impl/listener_manager_impl.cpp b/src/network/impl/listener_manager_impl.cpp index 13489ef03..b22178265 100644 --- a/src/network/impl/listener_manager_impl.cpp +++ b/src/network/impl/listener_manager_impl.cpp @@ -181,15 +181,14 @@ namespace libp2p::network { void ListenerManagerImpl::onConnection( outcome::result> rconn) { if (!rconn) { - log()->warn("can not accept valid connection, {}", - rconn.error().message()); + log()->warn("can not accept valid connection, {}", rconn.error()); return; // ignore } auto &&conn = rconn.value(); auto rid = conn->remotePeer(); if (!rid) { - log()->warn("can not get remote peer id, {}", rid.error().message()); + log()->warn("can not get remote peer id, {}", rid.error()); return; // ignore } auto &&id = rid.value(); @@ -198,7 +197,7 @@ namespace libp2p::network { conn->onStream( [this](outcome::result> rstream) { if (!rstream) { - log()->warn("can not accept stream, {}", rstream.error().message()); + log()->warn("can not accept stream, {}", rstream.error()); return; // ignore } auto &&stream = rstream.value(); @@ -221,7 +220,7 @@ namespace libp2p::network { if (!rproto) { log()->warn("can not negotiate protocols, {}", - rproto.error().message()); + rproto.error()); success = false; } else { auto &&proto = rproto.value(); @@ -229,7 +228,7 @@ namespace libp2p::network { auto rhandle = this->router_->handle(proto, stream); if (!rhandle) { log()->warn("no protocol handler found, {}", - rhandle.error().message()); + rhandle.error()); success = false; } } diff --git a/src/protocol/echo/client_echo_session.cpp b/src/protocol/echo/client_echo_session.cpp index 146ddbd24..2457267dd 100644 --- a/src/protocol/echo/client_echo_session.cpp +++ b/src/protocol/echo/client_echo_session.cpp @@ -27,7 +27,7 @@ namespace libp2p::protocol { buf_ = std::vector(send.begin(), send.end()); recv_buf_.resize(buf_.size()); - ec_.clear(); + ec_.reset(); bytes_read_ = 0; then_ = std::move(then); @@ -73,7 +73,7 @@ namespace libp2p::protocol { auto then = decltype(then_){}; then_.swap(then); if (ec_) { - then(ec_); + then(*ec_); } else { if (not std::equal( recv_buf_.begin(), recv_buf_.end(), buf_.begin(), buf_.end())) { diff --git a/src/protocol/echo/server_echo_session.cpp b/src/protocol/echo/server_echo_session.cpp index 085499de1..494d4a437 100644 --- a/src/protocol/echo/server_echo_session.cpp +++ b/src/protocol/echo/server_echo_session.cpp @@ -34,7 +34,7 @@ namespace libp2p::protocol { void ServerEchoSession::stop() { stream_->close([self{shared_from_this()}](auto &&res) { if (!res) { - self->log_->error("cannot close the stream: {}", res.error().message()); + self->log_->error("cannot close the stream: {}", res.error()); } }); } @@ -55,7 +55,7 @@ namespace libp2p::protocol { void ServerEchoSession::onRead(outcome::result rread) { if (!rread) { - log_->error("error happened during read: {}", rread.error().message()); + log_->error("error happened during read: {}", rread.error()); return stop(); } @@ -92,7 +92,7 @@ namespace libp2p::protocol { void ServerEchoSession::onWrite(outcome::result rwrite) { if (!rwrite) { - log_->error("error happened during write: {}", rwrite.error().message()); + log_->error("error happened during write: {}", rwrite.error()); return stop(); } diff --git a/src/protocol/gossip/impl/connectivity.cpp b/src/protocol/gossip/impl/connectivity.cpp index ce5c22555..65447f4c2 100644 --- a/src/protocol/gossip/impl/connectivity.cpp +++ b/src/protocol/gossip/impl/connectivity.cpp @@ -149,7 +149,7 @@ namespace libp2p::protocol::gossip { // no remote peer id means dead stream auto peer_res = stream->remotePeerId(); if (!peer_res) { - log_.info("ignoring dead stream: {}", peer_res.error().message()); + log_.info("ignoring dead stream: {}", peer_res.error()); return; } @@ -272,8 +272,7 @@ namespace libp2p::protocol::gossip { assert(!ctx->outbound_stream); if (!rstream) { - log_.info("outbound connection failed, error={}", - rstream.error().message()); + log_.info("outbound connection failed, error={}", rstream.error()); if (started_) { banOrForget(ctx); } @@ -290,7 +289,7 @@ namespace libp2p::protocol::gossip { // no remote peer id means dead stream auto peer_res = stream->remotePeerId(); if (!peer_res) { - log_.info("ignoring dead stream: {}", peer_res.error().message()); + log_.info("ignoring dead stream: {}", peer_res.error()); banOrForget(ctx); return; } @@ -390,7 +389,7 @@ namespace libp2p::protocol::gossip { // do nothing at the moment, keep it connected return; } - log_.info("stream error='{}', peer={}", event.error().message(), from->str); + log_.info("stream error='{}', peer={}", event.error(), from->str); // TODO(artem): ban incoming peers for protocol violations etc. - v.1.1 diff --git a/src/protocol/gossip/impl/gossip_core.cpp b/src/protocol/gossip/impl/gossip_core.cpp index c158eea66..811a392ef 100644 --- a/src/protocol/gossip/impl/gossip_core.cpp +++ b/src/protocol/gossip/impl/gossip_core.cpp @@ -172,7 +172,7 @@ namespace libp2p::protocol::gossip { if (config_.sign_messages) { auto res = signMessage(*msg); if (!res) { - log_.warn("signMessage error: {}", res.error().message()); + log_.warn("signMessage error: {}", res.error()); } } @@ -338,7 +338,7 @@ namespace libp2p::protocol::gossip { auto res = heartbeat_timer_.reschedule(config_.heartbeat_interval_msec); if (!res) { - log_.error("Heartbeat reschedule error: {}", res.error().message()); + log_.error("Heartbeat reschedule error: {}", res.error()); } } diff --git a/src/protocol/gossip/impl/message_builder.cpp b/src/protocol/gossip/impl/message_builder.cpp index cc3c6c6a3..fdce915b1 100644 --- a/src/protocol/gossip/impl/message_builder.cpp +++ b/src/protocol/gossip/impl/message_builder.cpp @@ -105,7 +105,7 @@ namespace libp2p::protocol::gossip { if (success) { return buffer; } - return outcome::failure(Error::MESSAGE_SERIALIZE_ERROR); + return Error::MESSAGE_SERIALIZE_ERROR; } void MessageBuilder::addSubscription(bool subscribe, const TopicId &topic) { @@ -184,7 +184,7 @@ namespace libp2p::protocol::gossip { std::copy(kPrefix.begin(), kPrefix.end(), signable.begin()); if (!pb_msg.SerializeToArray(&signable[kPrefix.size()], static_cast(size))) { - return outcome::failure(Error::MESSAGE_SERIALIZE_ERROR); + return Error::MESSAGE_SERIALIZE_ERROR; } return signable; } diff --git a/src/protocol/identify/identify_delta.cpp b/src/protocol/identify/identify_delta.cpp index c6f634b68..6ac17f108 100644 --- a/src/protocol/identify/identify_delta.cpp +++ b/src/protocol/identify/identify_delta.cpp @@ -66,7 +66,7 @@ namespace libp2p::protocol { log_->error("cannot read identify-delta message from peer {}, {}: {}", peer_id_str, peer_addr_str, - msg_res.error().message()); + msg_res.error()); return stream->reset(); } @@ -88,10 +88,8 @@ namespace libp2p::protocol { p = std::move(peer_id_str), a = std::move(peer_addr_str)](auto &&res) { if (!res) { - self->log_->error("cannot close stream to peer {}, {}: {}", - p, - a, - res.error().message()); + self->log_->error( + "cannot close stream to peer {}, {}: {}", p, a, res.error()); } }); @@ -117,7 +115,7 @@ namespace libp2p::protocol { log_->error("cannot add new protocols of peer {}, {}: {}", peer_id_str, peer_addr_str, - add_res.error().message()); + add_res.error()); } std::vector rm_protocols; @@ -130,7 +128,7 @@ namespace libp2p::protocol { log_->error("cannot remove protocols of peer {}, {}: {}", peer_id_str, peer_addr_str, - rm_res.error().message()); + rm_res.error()); } } @@ -166,7 +164,7 @@ namespace libp2p::protocol { self->log_->error("cannot write Identify-Delta to peer {}, {}: {}", s->remotePeerId().value().toBase58(), s->remoteMultiaddr().value().getStringAddress(), - res.error().message()); + res.error()); } }); } diff --git a/src/protocol/identify/identify_msg_processor.cpp b/src/protocol/identify/identify_msg_processor.cpp index 2bc8869a6..47c618774 100644 --- a/src/protocol/identify/identify_msg_processor.cpp +++ b/src/protocol/identify/identify_msg_processor.cpp @@ -27,8 +27,8 @@ namespace { return {addr.begin(), addr.end()}; } - inline libp2p::outcome::result - fromStringToMultiaddr(const std::string &addr) { + inline outcome::result fromStringToMultiaddr( + const std::string &addr) { return libp2p::multi::Multiaddress::create(BytesIn( // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) reinterpret_cast(addr.data()), @@ -80,7 +80,7 @@ namespace libp2p::protocol { log_->critical( "cannot marshal public key, which was provided to us by the identity " "manager: {}", - marshalled_pubkey_res.error().message()); + marshalled_pubkey_res.error()); } else { auto &&marshalled_pubkey = marshalled_pubkey_res.value(); msg.set_publickey(marshalled_pubkey.key.data(), @@ -108,7 +108,7 @@ namespace libp2p::protocol { log_->error("cannot write identify message to stream to peer {}, {}: {}", peer_id, peer_addr, - written_bytes.error().message()); + written_bytes.error()); return stream->reset(); } @@ -120,10 +120,8 @@ namespace libp2p::protocol { p = std::move(peer_id), a = std::move(peer_addr)](auto &&res) { if (!res) { - self->log_->error("cannot close the stream to peer {}, {}: {}", - p, - a, - res.error().message()); + self->log_->error( + "cannot close the stream to peer {}, {}: {}", p, a, res.error()); } }); } @@ -169,10 +167,8 @@ namespace libp2p::protocol { p = std::move(peer_id_str), a = std::move(peer_addr_str)](auto &&res) { if (!res) { - self->log_->error("cannot close the stream to peer {}, {}: {}", - p, - a, - res.error().message()); + self->log_->error( + "cannot close the stream to peer {}, {}: {}", p, a, res.error()); } }); @@ -198,7 +194,7 @@ namespace libp2p::protocol { if (!add_res) { log_->error("cannot add protocols to peer {}: {}", peer_id.toBase58(), - add_res.error().message()); + add_res.error()); } if (msg.has_observedaddr()) { @@ -245,7 +241,7 @@ namespace libp2p::protocol { if (!pubkey_res) { log_->info("cannot unmarshal public key for peer {}: {}", stream_peer_id ? stream_peer_id->toBase58() : "", - pubkey_res.error().message()); + pubkey_res.error()); return stream_peer_id; } pubkey = std::move(pubkey_res.value()); @@ -256,7 +252,7 @@ namespace libp2p::protocol { peer::PeerId::fromPublicKey(crypto::ProtobufKey{pubkey_buf}); if (!msg_peer_id_res) { log_->info("cannot derive PeerId from the received key: {}", - msg_peer_id_res.error().message()); + msg_peer_id_res.error()); return stream_peer_id; } auto msg_peer_id = std::move(msg_peer_id_res.value()); @@ -269,7 +265,7 @@ namespace libp2p::protocol { if (!add_res) { log_->error("cannot add key to the repo of peer {}: {}", msg_peer_id.toBase58(), - add_res.error().message()); + add_res.error()); } return msg_peer_id; } @@ -288,7 +284,7 @@ namespace libp2p::protocol { if (!add_res) { log_->error("cannot add key to the repo of peer {}: {}", stream_peer_id->toBase58(), - add_res.error().message()); + add_res.error()); } return stream_peer_id; } @@ -377,7 +373,7 @@ namespace libp2p::protocol { SL_DEBUG(log_, "cannot update listen addresses of the peer {}: {}", peer_id.toBase58(), - update_res.error().message()); + update_res.error()); } // memorize the addresses @@ -398,7 +394,7 @@ namespace libp2p::protocol { if (!upsert_res) { log_->error("cannot add addresses to peer {}: {}", peer_id.toBase58(), - upsert_res.error().message()); + upsert_res.error()); } } } // namespace libp2p::protocol diff --git a/src/protocol/kademlia/impl/add_provider_executor.cpp b/src/protocol/kademlia/impl/add_provider_executor.cpp index 0128d4a5e..125a63098 100644 --- a/src/protocol/kademlia/impl/add_provider_executor.cpp +++ b/src/protocol/kademlia/impl/add_provider_executor.cpp @@ -165,7 +165,7 @@ namespace libp2p::protocol::kademlia { --requests_in_progress_; log_.debug("cannot connect to peer: {}; done {}, active {}, in queue {}", - stream_res.error().message(), + stream_res.error(), requests_succeed_, requests_in_progress_, queue_.size()); diff --git a/src/protocol/kademlia/impl/find_peer_executor.cpp b/src/protocol/kademlia/impl/find_peer_executor.cpp index 509ec6681..ab855d2a4 100644 --- a/src/protocol/kademlia/impl/find_peer_executor.cpp +++ b/src/protocol/kademlia/impl/find_peer_executor.cpp @@ -100,7 +100,7 @@ namespace libp2p::protocol::kademlia { if (result.has_value()) { log_.debug("done: peer is found"); } else { - log_.debug("done: {}", result.error().message()); + log_.debug("done: {}", result.error()); } handler_(result); } @@ -179,7 +179,7 @@ namespace libp2p::protocol::kademlia { --requests_in_progress_; log_.debug("cannot connect to peer: {}; active {}, in queue {}", - stream_res.error().message(), + stream_res.error(), requests_in_progress_, queue_.size()); @@ -237,7 +237,7 @@ namespace libp2p::protocol::kademlia { if (not msg_res) { log_.warn("Result from {} is failed: {}; active {}, in queue {}", session->stream()->remotePeerId().value().toBase58(), - msg_res.error().message(), + msg_res.error(), requests_in_progress_, queue_.size()); return; diff --git a/src/protocol/kademlia/impl/find_providers_executor.cpp b/src/protocol/kademlia/impl/find_providers_executor.cpp index 846dbef73..cb30812e9 100644 --- a/src/protocol/kademlia/impl/find_providers_executor.cpp +++ b/src/protocol/kademlia/impl/find_providers_executor.cpp @@ -190,7 +190,7 @@ namespace libp2p::protocol::kademlia { --requests_in_progress_; log_.debug("cannot connect to peer: {}; active {}, in queue {}", - stream_res.error().message(), + stream_res.error(), requests_in_progress_, queue_.size()); @@ -249,7 +249,7 @@ namespace libp2p::protocol::kademlia { if (not msg_res) { log_.warn("Result from {} is failed: {}; active {}, in queue {}", session->stream()->remotePeerId().value().toBase58(), - msg_res.error().message(), + msg_res.error(), requests_in_progress_, queue_.size()); return; diff --git a/src/protocol/kademlia/impl/get_value_executor.cpp b/src/protocol/kademlia/impl/get_value_executor.cpp index a137099c0..030787542 100644 --- a/src/protocol/kademlia/impl/get_value_executor.cpp +++ b/src/protocol/kademlia/impl/get_value_executor.cpp @@ -182,7 +182,7 @@ namespace libp2p::protocol::kademlia { --requests_in_progress_; log_.debug("cannot connect to peer: {}; active {}, in queue {}", - stream_res.error().message(), + stream_res.error(), requests_in_progress_, queue_.size()); @@ -242,7 +242,7 @@ namespace libp2p::protocol::kademlia { if (not msg_res) { log_.warn("Result from {} failed: {}; active {}, in queue {}", session->stream()->remotePeerId().value().toBase58(), - msg_res.error().message(), + msg_res.error(), requests_in_progress_, queue_.size()); return; diff --git a/src/protocol/kademlia/impl/kademlia_impl.cpp b/src/protocol/kademlia/impl/kademlia_impl.cpp index 328ad36f5..ea8d0beb2 100644 --- a/src/protocol/kademlia/impl/kademlia_impl.cpp +++ b/src/protocol/kademlia/impl/kademlia_impl.cpp @@ -228,7 +228,7 @@ namespace libp2p::protocol::kademlia { if (not upsert_res) { log_.debug("{} was skipped at addind to peer routing table: {}", peer_info.id.toBase58(), - upsert_res.error().message()); + upsert_res.error()); return; } @@ -237,7 +237,7 @@ namespace libp2p::protocol::kademlia { if (not update_res) { log_.debug("{} was not added to peer routing table: {}", peer_info.id.toBase58(), - update_res.error().message()); + update_res.error()); return; } if (update_res.value()) { @@ -312,14 +312,13 @@ namespace libp2p::protocol::kademlia { auto validation_res = validator_->validate(key, value); if (not validation_res) { - log_.warn("incoming PutValue failed: {}", - validation_res.error().message()); + log_.warn("incoming PutValue failed: {}", validation_res.error()); return; } auto res = putValue(key, value); if (!res) { - log_.warn("incoming PutValue failed: {}", res.error().message()); + log_.warn("incoming PutValue failed: {}", res.error()); return; } diff --git a/src/protocol/kademlia/impl/put_value_executor.cpp b/src/protocol/kademlia/impl/put_value_executor.cpp index 7f8952409..4b3a3279e 100644 --- a/src/protocol/kademlia/impl/put_value_executor.cpp +++ b/src/protocol/kademlia/impl/put_value_executor.cpp @@ -118,7 +118,7 @@ namespace libp2p::protocol::kademlia { --requests_in_progress_; log_.debug("cannot connect to peer: {}; active {}, in queue {}", - stream_res.error().message(), + stream_res.error(), requests_in_progress_, addressees_.size() - addressees_idx_); @@ -175,7 +175,7 @@ namespace libp2p::protocol::kademlia { requests_succeed_, requests_in_progress_, addressees_.size() - addressees_idx_, - msg_res.error().message()); + msg_res.error()); } else { ++requests_succeed_; log_.debug("write to {} successfuly; done {}, active {}, in queue {}", diff --git a/src/protocol/kademlia/message.cpp b/src/protocol/kademlia/message.cpp index 524aa748a..4134fbc95 100644 --- a/src/protocol/kademlia/message.cpp +++ b/src/protocol/kademlia/message.cpp @@ -124,12 +124,13 @@ namespace libp2p::protocol::kademlia { } auto closer_res = assign_peers(closer_peers, pb_msg.closerpeers()); if (not closer_res) { - error_message_ = "Bad closer peers: " + closer_res.error().message(); + error_message_ = fmt::format("Bad closer peers: {}", closer_res.error()); return false; } auto provider_res = assign_peers(provider_peers, pb_msg.providerpeers()); if (not provider_res) { - error_message_ = "Bad provider peers: " + provider_res.error().message(); + error_message_ = + fmt::format("Bad provider peers: {}", provider_res.error()); return false; } return true; diff --git a/src/protocol/ping/CMakeLists.txt b/src/protocol/ping/CMakeLists.txt index 3c19c9506..bd8bf43be 100644 --- a/src/protocol/ping/CMakeLists.txt +++ b/src/protocol/ping/CMakeLists.txt @@ -11,4 +11,5 @@ libp2p_add_library(p2p_ping ) target_link_libraries(p2p_ping Boost::boost + p2p_basic_scheduler ) diff --git a/src/protocol/ping/ping.cpp b/src/protocol/ping/ping.cpp index bc9b85a30..b008d7302 100644 --- a/src/protocol/ping/ping.cpp +++ b/src/protocol/ping/ping.cpp @@ -13,12 +13,12 @@ namespace libp2p::protocol { Ping::Ping(Host &host, libp2p::event::Bus &bus, - boost::asio::io_context &io_context, + std::shared_ptr scheduler, std::shared_ptr rand_gen, PingConfig config) : host_{host}, bus_{bus}, - io_context_{io_context}, + scheduler_{scheduler}, rand_gen_{std::move(rand_gen)}, config_{config} {} @@ -49,7 +49,7 @@ namespace libp2p::protocol { return cb(stream_res.error()); } auto session = std::make_shared( - self->io_context_, + self->scheduler_, self->bus_, std::move(stream_res.value().stream), self->rand_gen_, diff --git a/src/protocol/ping/ping_client_session.cpp b/src/protocol/ping/ping_client_session.cpp index 543244979..8e46db2cf 100644 --- a/src/protocol/ping/ping_client_session.cpp +++ b/src/protocol/ping/ping_client_session.cpp @@ -6,27 +6,25 @@ #include -#include #include #include #include namespace libp2p::protocol { PingClientSession::PingClientSession( - boost::asio::io_service &io_service, + std::shared_ptr scheduler, libp2p::event::Bus &bus, std::shared_ptr stream, std::shared_ptr rand_gen, PingConfig config) - : io_service_{io_service}, + : scheduler_{scheduler}, bus_{bus}, channel_{bus_.getChannel()}, stream_{std::move(stream)}, rand_gen_{std::move(rand_gen)}, config_{config}, write_buffer_(config_.message_size, 0), - read_buffer_(config_.message_size, 0), - timer_{io_service_, boost::posix_time::milliseconds(config_.timeout)} { + read_buffer_(config_.message_size, 0) { BOOST_ASSERT(stream_); BOOST_ASSERT(rand_gen_); } @@ -43,67 +41,81 @@ namespace libp2p::protocol { } void PingClientSession::write() { - if (!is_started_ || stream_->isClosedForWrite()) { + if (not is_started_ or closed_ or stream_->isClosedForWrite()) { return; } - write_buffer_ = rand_gen_->randomBytes(config_.message_size); - writeReturnSize( - stream_, write_buffer_, [self{shared_from_this()}](auto &&write_res) { - if (!write_res) { - self->last_error_ = write_res.error(); + timer_ = scheduler_->scheduleWithHandle( + [weak{weak_from_this()}] { + if (auto self = weak.lock()) { + self->writeCompleted(std::errc::timed_out); } - self->last_op_completed_ = true; - }); + }, + config_.timeout); - timer_.async_wait([self{shared_from_this()}](auto &&ec) { - self->writeCompleted(std::forward(ec)); - }); + write_buffer_ = rand_gen_->randomBytes(config_.message_size); + writeReturnSize(stream_, + write_buffer_, + [self{shared_from_this()}](outcome::result r) { + self->writeCompleted(r); + }); } - void PingClientSession::writeCompleted(const boost::system::error_code &ec) { - if (ec || !last_op_completed_ || last_error_) { + void PingClientSession::writeCompleted(outcome::result r) { + timer_.cancel(); + if (r.has_error()) { // timeout passed or error happened; in any case, we cannot ping it // anymore - if (auto peer_id_res = stream_->remotePeerId()) { - channel_.publish(peer_id_res.value()); - } - return; + return close(); } - last_op_completed_ = false; read(); } void PingClientSession::read() { - if (!is_started_ || stream_->isClosedForRead()) { + if (not is_started_ or closed_ or stream_->isClosedForRead()) { return; } + timer_ = scheduler_->scheduleWithHandle( + [weak{weak_from_this()}] { + if (auto self = weak.lock()) { + self->readCompleted(std::errc::timed_out); + } + }, + config_.timeout); + stream_->read(read_buffer_, config_.message_size, - [self{shared_from_this()}](auto &&read_res) { - if (!read_res) { - self->last_error_ = read_res.error(); - } - self->last_op_completed_ = true; + [self{shared_from_this()}](outcome::result r) { + self->readCompleted(r); }); - - timer_.async_wait([self{shared_from_this()}](auto &&ec) { - self->readCompleted(std::forward(ec)); - }); } - void PingClientSession::readCompleted(const boost::system::error_code &ec) { - if (ec || !last_op_completed_ || last_error_ - || write_buffer_ != read_buffer_) { + void PingClientSession::readCompleted(outcome::result r) { + timer_.cancel(); + if (r.has_error() || write_buffer_ != read_buffer_) { // again, in case of any error we cannot continue to ping the peer and // thus declare it dead - if (auto peer_id_res = stream_->remotePeerId()) { - channel_.publish(peer_id_res.value()); - } + return close(); + } + + timer_ = scheduler_->scheduleWithHandle( + [weak{weak_from_this()}] { + if (auto self = weak.lock()) { + self->write(); + } + }, + config_.interval); + } + + void PingClientSession::close() { + if (closed_) { return; } - last_op_completed_ = false; - write(); + closed_ = true; + if (auto peer_id_res = stream_->remotePeerId()) { + channel_.publish(peer_id_res.value()); + } + stream_->reset(); } } // namespace libp2p::protocol diff --git a/src/protocol_muxer/CMakeLists.txt b/src/protocol_muxer/CMakeLists.txt index 81f48fd81..421e84558 100644 --- a/src/protocol_muxer/CMakeLists.txt +++ b/src/protocol_muxer/CMakeLists.txt @@ -15,8 +15,4 @@ target_link_libraries(p2p_multiselect p2p_read_buffer p2p_varint_prefix_reader p2p_logger - p2p_hexutil ) - - -#add_library(p2p_protocol_muxer_error) diff --git a/src/protocol_muxer/multiselect/multiselect_instance.cpp b/src/protocol_muxer/multiselect/multiselect_instance.cpp index 601c159e2..316b8e538 100644 --- a/src/protocol_muxer/multiselect/multiselect_instance.cpp +++ b/src/protocol_muxer/multiselect/multiselect_instance.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -110,12 +109,13 @@ namespace libp2p::protocol_muxer::multiselect { void MultiselectInstance::send(outcome::result msg) { if (!msg) { return connection_->deferWriteCallback( - msg.error(), + std::error_code{}, [wptr = weak_from_this(), - round = current_round_](outcome::result res) { + res = std::move(msg.error()), + round = current_round_](outcome::result) mutable { auto self = wptr.lock(); if (self && self->current_round_ == round) { - self->onDataWritten(res); + self->onDataWritten(std::move(res)); } }); } @@ -130,8 +130,6 @@ namespace libp2p::protocol_muxer::multiselect { auto span = BytesIn(*packet); - SL_TRACE(log(), "sending {}", common::dumpBin(span)); - writeReturnSize(connection_, span, [wptr = weak_from_this(), @@ -222,8 +220,6 @@ namespace libp2p::protocol_muxer::multiselect { BytesIn span(*read_buffer_); span = span.first(static_cast(bytes_read)); - SL_TRACE(log(), "received {}", common::dumpBin(span)); - boost::optional> got_result; auto state = parser_.consume(span); @@ -263,15 +259,9 @@ namespace libp2p::protocol_muxer::multiselect { result = handleNA(); break; case Message::kWrongProtocolVersion: { - SL_DEBUG(log(), - "Received unsupported protocol version: {}", - common::dumpBin(msg.content)); result = ProtocolMuxer::Error::PROTOCOL_VIOLATION; } break; default: { - SL_DEBUG(log(), - "Received invalid message: {}", - common::dumpBin(msg.content)); result = ProtocolMuxer::Error::PROTOCOL_VIOLATION; } break; } @@ -296,10 +286,6 @@ namespace libp2p::protocol_muxer::multiselect { return MaybeResult(std::string(protocol)); } } - - SL_DEBUG(log(), - "Unexpected message received by client: {}", - common::dumpBin(protocol)); return MaybeResult(ProtocolMuxer::Error::PROTOCOL_VIOLATION); } diff --git a/src/protocol_muxer/multiselect/simple_stream_negotiate.cpp b/src/protocol_muxer/multiselect/simple_stream_negotiate.cpp index 496d8648f..849f9f59d 100644 --- a/src/protocol_muxer/multiselect/simple_stream_negotiate.cpp +++ b/src/protocol_muxer/multiselect/simple_stream_negotiate.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include #include @@ -15,11 +14,6 @@ namespace libp2p::protocol_muxer::multiselect { namespace { - const log::Logger &log() { - static log::Logger logger = log::createLogger("Multiselect(simple)"); - return logger; - } - using StreamPtr = std::shared_ptr; using Callback = std::function)>; @@ -52,9 +46,6 @@ namespace libp2p::protocol_muxer::multiselect { if (!res) { return failed(stream, cb, res.error()); } - - SL_TRACE(log(), "received {}", common::dumpBin(BytesIn(buffers.read))); - completed(std::move(stream), cb, buffers); } @@ -78,8 +69,6 @@ namespace libp2p::protocol_muxer::multiselect { assert(total_sz > kMaxVarintSize); - SL_TRACE(log(), "read {}", common::dumpBin(BytesOut(buffers->read))); - size_t remaining_bytes = total_sz - kMaxVarintSize; BytesOut span(buffers->read); @@ -128,7 +117,9 @@ namespace libp2p::protocol_muxer::multiselect { auto res = detail::createMessage(a, false); if (!res) { return stream->deferWriteCallback( - res.error(), [cb = std::move(cb)](auto res) { cb(res.error()); }); + std::error_code{}, + [cb{std::move(cb)}, res{std::move(res.error())}]( + outcome::result) mutable { cb(std::move(res)); }); } auto buffers = std::make_shared(); @@ -139,8 +130,6 @@ namespace libp2p::protocol_muxer::multiselect { BytesIn span(buffers->written); - SL_TRACE(log(), "sending {}", common::dumpBin(span)); - writeReturnSize( stream, span, diff --git a/src/security/error.cpp b/src/security/error.cpp index 3d1dcc982..1d50b45fd 100644 --- a/src/security/error.cpp +++ b/src/security/error.cpp @@ -6,7 +6,7 @@ #include -OUTCOME_CPP_DEFINE_CATEGORY(libp2p::security::SecurityError, e) { +OUTCOME_CPP_DEFINE_CATEGORY(libp2p::security, SecurityError, e) { using E = libp2p::security::SecurityError; switch (e) { case E::AUTHENTICATION_ERROR: diff --git a/src/security/noise/CMakeLists.txt b/src/security/noise/CMakeLists.txt index c6a1db818..cbf9a6e22 100644 --- a/src/security/noise/CMakeLists.txt +++ b/src/security/noise/CMakeLists.txt @@ -24,7 +24,6 @@ target_link_libraries(p2p_noise p2p_x25519_provider p2p_hmac_provider p2p_chachapoly_provider - p2p_hexutil ) libp2p_add_library(p2p_noise_handshake_message_marshaller diff --git a/src/security/noise/handshake.cpp b/src/security/noise/handshake.cpp index 3df27e136..b7f7a90b8 100644 --- a/src/security/noise/handshake.cpp +++ b/src/security/noise/handshake.cpp @@ -265,7 +265,7 @@ namespace libp2p::security::noise { void Handshake::hscb(outcome::result secured) { if (secured.has_error()) { - log_->error("handshake failed, {}", secured.error().message()); + log_->error("handshake failed, {}", secured.error()); return connection_cb_(secured.error()); } if (not secured.value()) { diff --git a/src/security/plaintext/plaintext.cpp b/src/security/plaintext/plaintext.cpp index d44600afc..76d4bd732 100644 --- a/src/security/plaintext/plaintext.cpp +++ b/src/security/plaintext/plaintext.cpp @@ -160,7 +160,7 @@ namespace libp2p::security { auto derived_pid_res = peer::PeerId::fromPublicKey(in_exchange_msg.second); if (!derived_pid_res) { log_->error("cannot create a PeerId from the received public key: {}", - derived_pid_res.error().message()); + derived_pid_res.error()); return cb(derived_pid_res.error()); } auto derived_pid = std::move(derived_pid_res.value()); @@ -195,10 +195,10 @@ namespace libp2p::security { const std::shared_ptr &conn, const std::error_code &err) const { log_->error("error happened while establishing a Plaintext session: {}", - err.message()); + err); if (auto close_res = conn->close(); !close_res) { log_->error("connection close attempt ended with error: {}", - close_res.error().message()); + close_res.error()); } } diff --git a/src/security/secio/secio.cpp b/src/security/secio/secio.cpp index 0d830cb97..4b83d9106 100644 --- a/src/security/secio/secio.cpp +++ b/src/security/secio/secio.cpp @@ -284,10 +284,10 @@ namespace libp2p::security { void Secio::closeConnection( const std::shared_ptr &conn, const std::error_code &err) const { - log_->error("error happened, closing connection: {}", err.message()); + log_->error("error happened, closing connection: {}", err); if (auto close_res = conn->close(); !close_res) { log_->error("connection close attempt ended with error: {}", - close_res.error().message()); + close_res.error()); } } diff --git a/src/security/secio/secio_connection.cpp b/src/security/secio/secio_connection.cpp index e41147e7f..73c044f18 100644 --- a/src/security/secio/secio_connection.cpp +++ b/src/security/secio/secio_connection.cpp @@ -16,7 +16,6 @@ #include #include #include -#include OUTCOME_CPP_DEFINE_CATEGORY(libp2p::connection, SecioConnection::Error, e) { using E = libp2p::connection::SecioConnection::Error; @@ -63,8 +62,8 @@ OUTCOME_CPP_DEFINE_CATEGORY(libp2p::connection, SecioConnection::Error, e) { namespace { template - libp2p::outcome::result initAesSecret( - const libp2p::Bytes &key, const libp2p::Bytes &iv) { + outcome::result initAesSecret(const libp2p::Bytes &key, + const libp2p::Bytes &iv) { AesSecretType secret{}; if (key.size() != secret.key.size()) { return libp2p::crypto::OpenSslError::WRONG_KEY_SIZE; @@ -247,7 +246,7 @@ namespace libp2p::connection { kLenMarkerSize, [self{shared_from_this()}, buffer = read_buffer_, cb{std::move(cb)}]( outcome::result read_bytes_res) mutable { - IO_OUTCOME_TRY(len_marker_size, read_bytes_res, cb) + IO_OUTCOME_TRY(len_marker_size, read_bytes_res, cb); if (len_marker_size != kLenMarkerSize) { self->log_->error( "Cannot read frame header. Read {} bytes when {} expected", @@ -271,7 +270,7 @@ namespace libp2p::connection { frame_len, [self, buffer, frame_len, cb{cb}]( outcome::result read_bytes) mutable { - IO_OUTCOME_TRY(read_frame_bytes, read_bytes, cb) + IO_OUTCOME_TRY(read_frame_bytes, read_bytes, cb); if (frame_len != read_frame_bytes) { self->log_->error( "Unable to read expected amount of bytes. Read {} when " @@ -283,11 +282,11 @@ namespace libp2p::connection { } SL_TRACE( self->log_, "Received frame with len {}", read_frame_bytes); - IO_OUTCOME_TRY(mac_size, self->macSize(), cb) + IO_OUTCOME_TRY(mac_size, self->macSize(), cb); const auto data_size{frame_len - mac_size}; auto data_span{std::span(buffer->data(), data_size)}; auto mac_span{std::span(*buffer).subspan(data_size, mac_size)}; - IO_OUTCOME_TRY(remote_mac, self->macRemote(data_span), cb) + IO_OUTCOME_TRY(remote_mac, self->macRemote(data_span), cb); if (BytesIn(remote_mac) != BytesIn(mac_span)) { self->log_->error( "Signature does not validate for the received frame"); diff --git a/src/security/tls/tls_adaptor.cpp b/src/security/tls/tls_adaptor.cpp index 69912ff38..8fa23a798 100644 --- a/src/security/tls/tls_adaptor.cpp +++ b/src/security/tls/tls_adaptor.cpp @@ -96,7 +96,7 @@ namespace libp2p::security { SL_DEBUG(log(), "securing inbound connection"); } - std::error_code ec; + std::optional ec; if (!ssl_context_) { auto res = setupContext(); if (!res) { @@ -121,7 +121,7 @@ namespace libp2p::security { } if (ec) { - io_context_->post([cb, ec] { cb(ec); }); // NOLINT + io_context_->post([cb, ec] { cb(*ec); }); } } diff --git a/src/security/tls/tls_connection.cpp b/src/security/tls/tls_connection.cpp index 4c20e15e6..b8f14bdac 100644 --- a/src/security/tls/tls_connection.cpp +++ b/src/security/tls/tls_connection.cpp @@ -59,7 +59,10 @@ namespace libp2p::connection { const boost::system::error_code &error, const HandshakeCallback &cb, const crypto::marshaller::KeyMarshaller &key_marshaller) { - std::error_code ec = error; + std::optional ec; + if (error) { + ec = error; + } while (!ec) { X509 *cert = SSL_get_peer_certificate(socket_.native_handle()); if (cert == nullptr) { @@ -96,12 +99,11 @@ namespace libp2p::connection { assert(ec); - log()->info("handshake error: {}", ec.message()); + log()->info("handshake error: {}", *ec); if (auto close_res = close(); !close_res) { - log()->info("cannot close raw connection: {}", - close_res.error().message()); + log()->info("cannot close raw connection: {}", close_res.error()); } - return cb(ec); + return cb(*ec); } outcome::result TlsConnection::localPeer() const { @@ -139,9 +141,9 @@ namespace libp2p::connection { return [cb{std::move(cb)}, conn{conn.shared_from_this()}](auto &&ec, auto &&result) { if (ec) { - SL_DEBUG(log(), "connection async op error {}", ec.message()); + SL_DEBUG(log(), "connection async op error {}", ec); std::ignore = conn->close(); - return cb(std::forward(ec)); + return cb(ec); } cb(std::forward(result)); }; diff --git a/src/security/tls/tls_details.cpp b/src/security/tls/tls_details.cpp index 83d28b578..e79decd12 100644 --- a/src/security/tls/tls_details.cpp +++ b/src/security/tls/tls_details.cpp @@ -391,7 +391,7 @@ namespace libp2p::security::tls_details { if (!verify_res) { log()->info("peer {} verification failed, {}", peer_id.toBase58(), - verify_res.error().message()); + verify_res.error()); return TlsError::TLS_PEER_VERIFY_FAILED; } diff --git a/src/transport/tcp/tcp_connection.cpp b/src/transport/tcp/tcp_connection.cpp index 4e16aabc8..ef4948e2b 100644 --- a/src/transport/tcp/tcp_connection.cpp +++ b/src/transport/tcp/tcp_connection.cpp @@ -20,14 +20,6 @@ namespace libp2p::transport { static auto logger = log::createLogger("TcpConnection"); return *logger; } - - inline std::error_code convert(boost::system::errc::errc_t ec) { - return {static_cast(ec), std::system_category()}; - } - - inline std::error_code convert(std::error_code ec) { - return ec; - } } // namespace TcpConnection::TcpConnection(boost::asio::io_context &ctx, @@ -51,17 +43,14 @@ namespace libp2p::transport { outcome::result TcpConnection::close() { closed_by_host_ = true; - close(convert(boost::system::errc::connection_aborted)); + close(make_error_code(boost::system::errc::connection_aborted)); return outcome::success(); } void TcpConnection::close(std::error_code reason) { - assert(reason); - if (!close_reason_) { close_reason_ = reason; - log().debug( - "{} closing with reason: {}", debug_str_, close_reason_.message()); + log().debug("{} closing with reason: {}", debug_str_, *close_reason_); } if (socket_.is_open()) { boost::system::error_code ec; @@ -102,12 +91,12 @@ namespace libp2p::transport { auto closeOnError(TcpConnection &conn, Callback cb) { return [cb{std::move(cb)}, wptr{conn.weak_from_this()}](auto ec, auto result) { - if (!wptr.expired()) { + if (auto self = wptr.lock()) { if (ec) { - wptr.lock()->close(convert(ec)); - return cb(std::forward(ec)); + self->close(ec); + return cb(ec); } - TRACE("{} {}", wptr.lock()->str(), result); + TRACE("{} {}", self->str(), result); cb(result); } else { log().debug("connection wptr expired"); @@ -308,10 +297,10 @@ namespace libp2p::transport { } } } else { - return convert(boost::system::errc::not_connected); + return make_error_code(boost::system::errc::not_connected); } if (ec) { - return convert(ec); + return ec; } #ifndef NDEBUG debug_str_ = fmt::format("{} {} {}", diff --git a/src/transport/tcp/tcp_listener.cpp b/src/transport/tcp/tcp_listener.cpp index 978d61162..824f54072 100644 --- a/src/transport/tcp/tcp_listener.cpp +++ b/src/transport/tcp/tcp_listener.cpp @@ -48,9 +48,8 @@ namespace libp2p::transport { return outcome::success(); } catch (const boost::system::system_error &e) { log::createLogger("Listener") - ->error("Cannot listen to {}: {}", - address.getStringAddress(), - e.code().message()); + ->error( + "Cannot listen to {}: {}", address.getStringAddress(), e.code()); return e.code(); } } @@ -76,7 +75,7 @@ namespace libp2p::transport { boost::system::error_code ec; acceptor_.close(ec); if (ec) { - return outcome::failure(ec); + return ec; } return outcome::success(); } diff --git a/test/acceptance/p2p/host/peer/test_peer.cpp b/test/acceptance/p2p/host/peer/test_peer.cpp index 63ef1da5c..d09aad538 100644 --- a/test/acceptance/p2p/host/peer/test_peer.cpp +++ b/test/acceptance/p2p/host/peer/test_peer.cpp @@ -51,10 +51,8 @@ Peer::Peer(Peer::Duration timeout, bool secure) std::make_shared(context_), basic::Scheduler::Config{})}, secure_{secure} { - EXPECT_OUTCOME_TRUE_MSG( - keys, - crypto_provider_->generateKeys(crypto::Key::Type::Ed25519), - "failed to generate keys"); + EXPECT_OUTCOME_TRUE( + keys, crypto_provider_->generateKeys(crypto::Key::Type::Ed25519)); host_ = makeHost(keys); auto handler = [this](StreamAndProtocol stream) { echo_->handle(stream); }; @@ -64,7 +62,7 @@ Peer::Peer(Peer::Duration timeout, bool secure) void Peer::startServer(const multi::Multiaddress &address, std::shared_ptr> promise) { context_->post([this, address, p = std::move(promise)] { - EXPECT_OUTCOME_TRUE_MSG_1(host_->listen(address), "failed to start server"); + EXPECT_OUTCOME_TRUE_1(host_->listen(address)); host_->start(); p->set_value(host_->getPeerInfo()); }); @@ -88,8 +86,7 @@ void Peer::startClient(const peer::PeerInfo &pinfo, counter = std::move(counter)](StreamAndProtocolOrError rstream) mutable { // get stream - EXPECT_OUTCOME_TRUE_MSG( - stream, rstream, "failed to connect to server: " + server_id); + EXPECT_OUTCOME_TRUE(stream, rstream); // make client session auto client = std::make_shared( stream.stream, ping_times); @@ -102,10 +99,7 @@ void Peer::startClient(const peer::PeerInfo &pinfo, // count message exchange counter->tick(); // ensure message returned - EXPECT_OUTCOME_TRUE_MSG( - vec, - res, - "failed to receive response from server: " + server_id); + EXPECT_OUTCOME_TRUE(vec, res); // ensure message is correct ASSERT_EQ(vec.size(), client->bufferSize()); // NOLINT }); diff --git a/test/acceptance/p2p/muxer.cpp b/test/acceptance/p2p/muxer.cpp index ebbcff7ec..6de212405 100644 --- a/test/acceptance/p2p/muxer.cpp +++ b/test/acceptance/p2p/muxer.cpp @@ -133,7 +133,7 @@ struct Server : public std::enable_shared_from_this { || rread.error() == Stream::Error::STREAM_RESET_BY_HOST) { return; } - this->println("readSome error: ", rread.error().message()); + this->println(fmt::format("readSome error: {}", rread.error())); } EXPECT_OUTCOME_TRUE(read, rread) diff --git a/test/deps/outcome_test.cpp b/test/deps/outcome_test.cpp index 8d4a16a8d..4a08ad2f5 100644 --- a/test/deps/outcome_test.cpp +++ b/test/deps/outcome_test.cpp @@ -10,8 +10,6 @@ using std::string_literals::operator""s; -using namespace libp2p; - #define ILLEGAL_CHAR_MSG "illegal char"s #define DIV_0_MSG "division by 0"s diff --git a/test/libp2p/basic/message_read_writer_test.cpp b/test/libp2p/basic/message_read_writer_test.cpp index db77b1b50..c511bbbde 100644 --- a/test/libp2p/basic/message_read_writer_test.cpp +++ b/test/libp2p/basic/message_read_writer_test.cpp @@ -16,7 +16,6 @@ using namespace basic; using namespace connection; using namespace multi; -using libp2p::Bytes; using testing::_; using testing::Return; diff --git a/test/libp2p/basic/scheduler_test.cpp b/test/libp2p/basic/scheduler_test.cpp index 1e324e99e..bd8fd667b 100644 --- a/test/libp2p/basic/scheduler_test.cpp +++ b/test/libp2p/basic/scheduler_test.cpp @@ -72,8 +72,7 @@ TEST(Scheduler, BasicThings) { log().debug( "timed w/handle called first time (98), rescheduling +70"); first_time = false; - EXPECT_OUTCOME_SUCCESS(_, - h3.reschedule(std::chrono::milliseconds(70))); + EXPECT_OUTCOME_TRUE_1(h3.reschedule(std::chrono::milliseconds(70))); } else { log().debug("timed w/handle called second time, rescheduled"); } @@ -85,7 +84,7 @@ TEST(Scheduler, BasicThings) { if (first_time) { log().debug("deferred w/handle called first time, rescheduling +120"); first_time = false; - EXPECT_OUTCOME_SUCCESS(_, h4.reschedule(std::chrono::milliseconds(120))); + EXPECT_OUTCOME_TRUE_1(h4.reschedule(std::chrono::milliseconds(120))); } else { log().debug("deferred->timed w/handle called second time, rescheduled"); } @@ -131,8 +130,7 @@ TEST(Scheduler, ManualScheduler) { log().debug( "timed w/handle called first time (98), rescheduling +70"); first_time = false; - EXPECT_OUTCOME_SUCCESS(_, - h3.reschedule(std::chrono::milliseconds(70))); + EXPECT_OUTCOME_TRUE_1(h3.reschedule(std::chrono::milliseconds(70))); } else { log().debug("timed w/handle called second time, rescheduled"); } @@ -144,7 +142,7 @@ TEST(Scheduler, ManualScheduler) { if (first_time) { log().debug("deferred w/handle called first time, rescheduling +120"); first_time = false; - EXPECT_OUTCOME_SUCCESS(_, h4.reschedule(std::chrono::milliseconds(120))); + EXPECT_OUTCOME_TRUE_1(h4.reschedule(std::chrono::milliseconds(120))); } else { log().debug("deferred->timed w/handle called second time, rescheduled"); } diff --git a/test/libp2p/connection/security_conn/plaintext_connection_test.cpp b/test/libp2p/connection/security_conn/plaintext_connection_test.cpp index 34bada743..b62e85791 100644 --- a/test/libp2p/connection/security_conn/plaintext_connection_test.cpp +++ b/test/libp2p/connection/security_conn/plaintext_connection_test.cpp @@ -124,7 +124,7 @@ TEST_F(PlaintextConnectionTest, Read) { EXPECT_CALL(*connection_, read(_, _, _)).WillOnce(AsioSuccess(size)); auto buf = std::make_shared>(size, 0); secure_connection_->read(*buf, size, [size, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), size); }); } @@ -141,7 +141,7 @@ TEST_F(PlaintextConnectionTest, ReadSome) { .WillOnce(AsioSuccess(smaller /* less than 100 */)); auto buf = std::make_shared>(size, 0); secure_connection_->readSome(*buf, smaller, [smaller, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), smaller); }); } @@ -156,7 +156,7 @@ TEST_F(PlaintextConnectionTest, Write) { EXPECT_CALL(*connection_, writeSome(_, _, _)).WillOnce(AsioSuccess(size)); auto buf = std::make_shared>(size, 0); libp2p::writeReturnSize(secure_connection_, *buf, [size, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), size); }); } @@ -173,7 +173,7 @@ TEST_F(PlaintextConnectionTest, WriteSome) { .WillOnce(AsioSuccess(smaller /* less than 100 */)); auto buf = std::make_shared>(size, 0); secure_connection_->writeSome(*buf, smaller, [smaller, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), smaller); }); } diff --git a/test/libp2p/crypto/key_generator_test.cpp b/test/libp2p/crypto/key_generator_test.cpp index d7d84f44d..e4677f797 100644 --- a/test/libp2p/crypto/key_generator_test.cpp +++ b/test/libp2p/crypto/key_generator_test.cpp @@ -77,7 +77,7 @@ class KeyGeneratorTest : public KeyGenTest, */ TEST_P(KeyGeneratorTest, GenerateKeyPairSuccess) { auto key_type = GetParam(); - EXPECT_OUTCOME_TRUE_2(val, crypto_provider_->generateKeys(key_type)) + EXPECT_OUTCOME_TRUE(val, crypto_provider_->generateKeys(key_type)) ASSERT_EQ(val.privateKey.type, key_type); ASSERT_EQ(val.publicKey.type, key_type); } @@ -89,8 +89,8 @@ TEST_P(KeyGeneratorTest, GenerateKeyPairSuccess) { */ TEST_P(KeyGeneratorTest, TwoKeysAreDifferent) { auto key_type = GetParam(); - EXPECT_OUTCOME_TRUE_2(val1, crypto_provider_->generateKeys(key_type)); - EXPECT_OUTCOME_TRUE_2(val2, crypto_provider_->generateKeys(key_type)); + EXPECT_OUTCOME_TRUE(val1, crypto_provider_->generateKeys(key_type)); + EXPECT_OUTCOME_TRUE(val2, crypto_provider_->generateKeys(key_type)); ASSERT_NE(val1.privateKey.data, val2.privateKey.data); ASSERT_NE(val1.publicKey.data, val2.privateKey.data); } @@ -105,9 +105,9 @@ TEST_P(KeyGeneratorTest, TwoKeysAreDifferent) { TEST_P(KeyGeneratorTest, DerivePublicKeySuccess) { auto key_type = GetParam(); - EXPECT_OUTCOME_TRUE_2(keys, crypto_provider_->generateKeys(key_type)); - EXPECT_OUTCOME_TRUE_2(derived, - crypto_provider_->derivePublicKey(keys.privateKey)); + EXPECT_OUTCOME_TRUE(keys, crypto_provider_->generateKeys(key_type)); + EXPECT_OUTCOME_TRUE(derived, + crypto_provider_->derivePublicKey(keys.privateKey)); ASSERT_EQ(derived.type, key_type); ASSERT_EQ(keys.publicKey.data, derived.data); } @@ -140,7 +140,7 @@ INSTANTIATE_TEST_SUITE_P( TEST_P(KeyLengthTest, KeyLengthCorrect) { auto [key_type, private_key_length, public_key_length] = GetParam(); - EXPECT_OUTCOME_TRUE_2(val, crypto_provider_->generateKeys(key_type)) + EXPECT_OUTCOME_TRUE(val, crypto_provider_->generateKeys(key_type)) ASSERT_EQ(val.privateKey.data.size(), private_key_length); } diff --git a/test/libp2p/crypto/keys_test.cpp b/test/libp2p/crypto/keys_test.cpp index 3f2ea798e..536e75125 100644 --- a/test/libp2p/crypto/keys_test.cpp +++ b/test/libp2p/crypto/keys_test.cpp @@ -5,7 +5,6 @@ */ #include -#include #include "libp2p/crypto/common.hpp" #include "libp2p/crypto/key.hpp" diff --git a/test/libp2p/crypto/marshaller_test.cpp b/test/libp2p/crypto/marshaller_test.cpp index 4e579a8c6..b2f3f2ac1 100644 --- a/test/libp2p/crypto/marshaller_test.cpp +++ b/test/libp2p/crypto/marshaller_test.cpp @@ -43,7 +43,7 @@ class Pubkey : public testing::TestWithParam> { public: void SetUp() override { ON_CALL(*validator_, validate(::testing::An())) - .WillByDefault(Return(libp2p::outcome::success())); + .WillByDefault(Return(outcome::success())); } std::shared_ptr validator_ = std::make_shared(); @@ -54,7 +54,7 @@ class Privkey : public testing::TestWithParam> { public: void SetUp() override { ON_CALL(*validator_, validate(::testing::An())) - .WillByDefault(Return(libp2p::outcome::success())); + .WillByDefault(Return(outcome::success())); } std::shared_ptr validator_ = diff --git a/test/libp2p/multi/cid_test.cpp b/test/libp2p/multi/cid_test.cpp index 65fc7f00a..025fb697d 100644 --- a/test/libp2p/multi/cid_test.cpp +++ b/test/libp2p/multi/cid_test.cpp @@ -6,7 +6,6 @@ #include -#include #include #include #include @@ -31,21 +30,6 @@ const Multihash ZERO_MULTIHASH = const Multihash EXAMPLE_MULTIHASH = "12206e6ff7950a36187a801613426e858dce686cd7d7e3c0fc42ee0330072d245c95"_multihash; -TEST(CidTest, PrettyString) { - ContentIdentifier c1(ContentIdentifier::Version::V1, - MulticodecType::Code::IDENTITY, - ZERO_MULTIHASH); - ASSERT_EQ(c1.toPrettyString("base58"), - "base58 - cidv1 - identity - sha2-256-256-" - + libp2p::common::hex_lower(ZERO_MULTIHASH.getHash())); - ContentIdentifier c2(ContentIdentifier::Version::V0, - MulticodecType::Code::DAG_PB, - EXAMPLE_MULTIHASH); - ASSERT_EQ(c2.toPrettyString("base64"), - "base64 - cidv0 - dag-pb - sha2-256-256-" - + libp2p::common::hex_lower(EXAMPLE_MULTIHASH.getHash())); -} - /** * @given CID with sample multihash and it's string representation from * reference implementation tests @@ -127,10 +111,9 @@ TEST(CidTest, MultibaseStringOfBaseCIDV0InvalidBase) { ContentIdentifier cid(ContentIdentifier::Version::V0, MulticodecType::Code::DAG_PB, reference_multihash); - EXPECT_OUTCOME_FALSE(error, - ContentIdentifierCodec::toStringOfBase( - cid, MultibaseCodec::Encoding::BASE32_LOWER)) - ASSERT_EQ(error, ContentIdentifierCodec::EncodeError::INVALID_BASE_ENCODING); + EXPECT_EC(ContentIdentifierCodec::toStringOfBase( + cid, MultibaseCodec::Encoding::BASE32_LOWER), + ContentIdentifierCodec::EncodeError::INVALID_BASE_ENCODING); } /** @@ -180,8 +163,8 @@ TEST(CidTest, MultibaseFromStringSuccessCIDV0) { TEST(CidTest, MultibaseFromStringShortCid) { const std::string short_string = "*"; - EXPECT_OUTCOME_FALSE(error, ContentIdentifierCodec::fromString(short_string)) - ASSERT_EQ(error, ContentIdentifierCodec::DecodeError::CID_TOO_SHORT); + EXPECT_EC(ContentIdentifierCodec::fromString(short_string), + ContentIdentifierCodec::DecodeError::CID_TOO_SHORT); } /** @@ -248,11 +231,6 @@ TEST(CidTest, CompareDifferentHashes) { ASSERT_FALSE(c2 < c2); } -class CidEncodeTest - : public testing::TestWithParam< - std::pair>>> {}; - TEST(CidTest, Create) { ContentIdentifier c(ContentIdentifier::Version::V0, MulticodecType::Code::IDENTITY, @@ -260,26 +238,23 @@ TEST(CidTest, Create) { ASSERT_EQ(c.content_address, EXAMPLE_MULTIHASH); } -TEST_P(CidEncodeTest, Encode) { - auto [cid, expectation] = GetParam(); - auto bytes = ContentIdentifierCodec::encode(cid); - if (expectation) { - auto bytes_value = bytes.value(); - auto expectation_value = expectation.value(); - ASSERT_TRUE(std::equal(bytes_value.begin(), - bytes_value.end(), - expectation_value.begin(), - expectation_value.end())) - << libp2p::common::hex_lower(bytes_value); - } else { - ASSERT_EQ(bytes.error(), expectation.error()) << bytes.error().message(); - } +TEST(CidEncodeTest, Encode) { + EXPECT_EC(ContentIdentifierCodec::encode( + ContentIdentifier(ContentIdentifier::Version::V0, + MulticodecType::Code::SHA1, + ZERO_MULTIHASH)), + ContentIdentifierCodec::EncodeError::INVALID_CONTENT_TYPE); + + EXPECT_EQ(ContentIdentifierCodec::encode( + ContentIdentifier(ContentIdentifier::Version::V0, + MulticodecType::Code::DAG_PB, + ZERO_MULTIHASH)) + .value(), + ZERO_MULTIHASH.toBuffer()); } -class CidDecodeTest - : public testing::TestWithParam< - std::pair, - libp2p::outcome::result>> { +class CidDecodeTest : public testing::TestWithParam< + std::pair, ContentIdentifier>> { public: void SetUp() { base_codec = std::make_shared(); @@ -291,11 +266,7 @@ class CidDecodeTest TEST_P(CidDecodeTest, Decode) { auto [cid_bytes, expectation] = GetParam(); auto cid = ContentIdentifierCodec::decode(cid_bytes); - if (expectation) { - ASSERT_EQ(cid.value(), expectation.value()); - } else { - ASSERT_EQ(cid.error(), expectation.error()) << cid.error().message(); - } + ASSERT_EQ(cid.value(), expectation); } class CidEncodeDecodeTest : public testing::TestWithParam {}; @@ -307,23 +278,7 @@ TEST_P(CidEncodeDecodeTest, DecodedMatchesOriginal) { ASSERT_EQ(cid, dec_cid); } -const std::vector< - std::pair>>> - encodeSuite{{ContentIdentifier(ContentIdentifier::Version::V0, - MulticodecType::Code::SHA1, - ZERO_MULTIHASH), - ContentIdentifierCodec::EncodeError::INVALID_CONTENT_TYPE}, - {ContentIdentifier(ContentIdentifier::Version::V0, - MulticodecType::Code::DAG_PB, - ZERO_MULTIHASH), - ZERO_MULTIHASH.toBuffer()}}; - -INSTANTIATE_TEST_SUITE_P(EncodeTests, - CidEncodeTest, - testing::ValuesIn(encodeSuite)); - -const std::vector< - std::pair, libp2p::outcome::result>> +const std::vector, ContentIdentifier>> decodeSuite{{EXAMPLE_MULTIHASH.toBuffer(), ContentIdentifier(ContentIdentifier::Version::V0, MulticodecType::Code::DAG_PB, diff --git a/test/libp2p/multi/utils/CMakeLists.txt b/test/libp2p/multi/utils/CMakeLists.txt index 9446f57d9..0a5e81ca0 100644 --- a/test/libp2p/multi/utils/CMakeLists.txt +++ b/test/libp2p/multi/utils/CMakeLists.txt @@ -10,7 +10,7 @@ addtest(uvarint_test target_link_libraries(uvarint_test p2p_uvarint - p2p_hexutil + p2p_literals ) addtest(protocol_list_test diff --git a/test/libp2p/multi/utils/address_converter_test.cpp b/test/libp2p/multi/utils/address_converter_test.cpp index 513a8af58..7761c2623 100644 --- a/test/libp2p/multi/utils/address_converter_test.cpp +++ b/test/libp2p/multi/utils/address_converter_test.cpp @@ -18,24 +18,24 @@ using libp2p::multi::ProtocolList; using libp2p::multi::converters::addressToBytes; using libp2p::multi::converters::ConversionError; -#define EXAMINE_STR_TO_BYTES(str_addr, hex_bytes, should_be_success) \ - do { \ - if (should_be_success) { \ - ASSERT_OUTCOME_SUCCESS(actual, addressToBytes(protocol, str_addr)); \ - ASSERT_OUTCOME_SUCCESS(expected, unhex(hex_bytes)); \ - ASSERT_EQ(actual, expected); \ - } else { \ - ASSERT_OUTCOME_ERROR(addressToBytes(protocol, str_addr), \ - ConversionError::INVALID_ADDRESS); \ - } \ +#define EXAMINE_STR_TO_BYTES(str_addr, hex_bytes, should_be_success) \ + do { \ + if (should_be_success) { \ + EXPECT_OUTCOME_TRUE(actual, addressToBytes(protocol, str_addr)); \ + EXPECT_OUTCOME_TRUE(expected, unhex(hex_bytes)); \ + ASSERT_EQ(actual, expected); \ + } else { \ + EXPECT_EC(addressToBytes(protocol, str_addr), \ + ConversionError::INVALID_ADDRESS); \ + } \ } while (false) -#define EXAMINE_BYTES_TO_STR(str_addr, hex_bytes) \ - do { \ - auto &expected = str_addr; \ - ASSERT_OUTCOME_SUCCESS(bytes, unhex(hex_bytes)); \ - ASSERT_OUTCOME_SUCCESS(actual, bytesToMultiaddrString(bytes)); \ - ASSERT_EQ(actual, expected); \ +#define EXAMINE_BYTES_TO_STR(str_addr, hex_bytes) \ + do { \ + auto &expected = str_addr; \ + EXPECT_OUTCOME_TRUE(bytes, unhex(hex_bytes)); \ + EXPECT_OUTCOME_TRUE(actual, bytesToMultiaddrString(bytes)); \ + ASSERT_EQ(actual, expected); \ } while (false) /** diff --git a/test/libp2p/multi/utils/string_from_to_bytes_test.cpp b/test/libp2p/multi/utils/string_from_to_bytes_test.cpp index 99e530b6f..1a5413e2e 100644 --- a/test/libp2p/multi/utils/string_from_to_bytes_test.cpp +++ b/test/libp2p/multi/utils/string_from_to_bytes_test.cpp @@ -18,19 +18,19 @@ using libp2p::multi::converters::bytesToMultiaddrString; using libp2p::multi::converters::ConversionError; using libp2p::multi::converters::multiaddrToBytes; -#define EXAMINE_STR_TO_BYTES(str_addr, hex_bytes) \ - do { \ - ASSERT_OUTCOME_SUCCESS(actual, multiaddrToBytes(str_addr)); \ - ASSERT_OUTCOME_SUCCESS(expected, unhex(hex_bytes)); \ - ASSERT_EQ(actual, expected); \ +#define EXAMINE_STR_TO_BYTES(str_addr, hex_bytes) \ + do { \ + EXPECT_OUTCOME_TRUE(actual, multiaddrToBytes(str_addr)); \ + EXPECT_OUTCOME_TRUE(expected, unhex(hex_bytes)); \ + ASSERT_EQ(actual, expected); \ } while (false) -#define EXAMINE_BYTES_TO_STR(str_addr, hex_bytes) \ - do { \ - auto &expected = str_addr; \ - ASSERT_OUTCOME_SUCCESS(bytes, unhex(hex_bytes)); \ - ASSERT_OUTCOME_SUCCESS(actual, bytesToMultiaddrString(bytes)); \ - ASSERT_EQ(actual, expected); \ +#define EXAMINE_BYTES_TO_STR(str_addr, hex_bytes) \ + do { \ + auto &expected = str_addr; \ + EXPECT_OUTCOME_TRUE(bytes, unhex(hex_bytes)); \ + EXPECT_OUTCOME_TRUE(actual, bytesToMultiaddrString(bytes)); \ + ASSERT_EQ(actual, expected); \ } while (false) /** @@ -125,21 +125,17 @@ TEST(AddressConverter, BytesToString) { } TEST(AddressConverter, InvalidAddresses) { - ASSERT_OUTCOME_ERROR(multiaddrToBytes("ip4/127.0.0.1"), - ConversionError::ADDRESS_DOES_NOT_BEGIN_WITH_SLASH); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/"), ConversionError::EMPTY_PROTOCOL); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/ip4/8.8.8.8//"), - ConversionError::EMPTY_PROTOCOL); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/fake"), - ConversionError::NO_SUCH_PROTOCOL); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/80/tcp"), - ConversionError::NO_SUCH_PROTOCOL); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/ip4/127.0.0.1/tcp"), - ConversionError::EMPTY_ADDRESS); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/ip4/254.255.256.257/"), - ConversionError::INVALID_ADDRESS); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/tcp/77777"), - ConversionError::INVALID_ADDRESS); - ASSERT_OUTCOME_ERROR(multiaddrToBytes("/tcp/udp"), - ConversionError::INVALID_ADDRESS); + EXPECT_EC(multiaddrToBytes("ip4/127.0.0.1"), + ConversionError::ADDRESS_DOES_NOT_BEGIN_WITH_SLASH); + EXPECT_EC(multiaddrToBytes("/"), ConversionError::EMPTY_PROTOCOL); + EXPECT_EC(multiaddrToBytes("/ip4/8.8.8.8//"), + ConversionError::EMPTY_PROTOCOL); + EXPECT_EC(multiaddrToBytes("/fake"), ConversionError::NO_SUCH_PROTOCOL); + EXPECT_EC(multiaddrToBytes("/80/tcp"), ConversionError::NO_SUCH_PROTOCOL); + EXPECT_EC(multiaddrToBytes("/ip4/127.0.0.1/tcp"), + ConversionError::EMPTY_ADDRESS); + EXPECT_EC(multiaddrToBytes("/ip4/254.255.256.257/"), + ConversionError::INVALID_ADDRESS); + EXPECT_EC(multiaddrToBytes("/tcp/77777"), ConversionError::INVALID_ADDRESS); + EXPECT_EC(multiaddrToBytes("/tcp/udp"), ConversionError::INVALID_ADDRESS); } diff --git a/test/libp2p/multi/utils/uvarint_test.cpp b/test/libp2p/multi/utils/uvarint_test.cpp index b6c58ec9b..768aff2ca 100644 --- a/test/libp2p/multi/utils/uvarint_test.cpp +++ b/test/libp2p/multi/utils/uvarint_test.cpp @@ -7,12 +7,10 @@ #include "libp2p/multi/uvarint.hpp" #include -#include +#include -#include - -using libp2p::common::hex_upper; using libp2p::multi::UVarint; +using libp2p::common::operator""_unhex; /** * @given an unsigned integer @@ -37,17 +35,17 @@ TEST(UVarint, CreateFromInt) { */ TEST(UVarint, CorrectEncoding) { UVarint var(1); - ASSERT_EQ(hex_upper(var.toBytes()), "01"); + ASSERT_EQ(var.toVector(), "01"_unhex); var = 127; - ASSERT_EQ(hex_upper(var.toBytes()), "7F"); + ASSERT_EQ(var.toVector(), "7F"_unhex); var = 128; - ASSERT_EQ(hex_upper(var.toBytes()), "8001"); + ASSERT_EQ(var.toVector(), "8001"_unhex); var = 255; - ASSERT_EQ(hex_upper(var.toBytes()), "FF01"); + ASSERT_EQ(var.toVector(), "FF01"_unhex); var = 300; - ASSERT_EQ(hex_upper(var.toBytes()), "AC02"); + ASSERT_EQ(var.toVector(), "AC02"_unhex); var = 16384; - ASSERT_EQ(hex_upper(var.toBytes()), "808001"); + ASSERT_EQ(var.toVector(), "808001"_unhex); } /** diff --git a/test/libp2p/muxer/muxers_and_streams_test.cpp b/test/libp2p/muxer/muxers_and_streams_test.cpp index 03be32dc5..021833bfc 100644 --- a/test/libp2p/muxer/muxers_and_streams_test.cpp +++ b/test/libp2p/muxer/muxers_and_streams_test.cpp @@ -158,7 +158,7 @@ namespace libp2p::regression { TRACE("({}): Cannot listen to multiaddress {}, {}", stats_.node_id, listen_to.getStringAddress(), - listen_res.error().message()); + listen_res.error()); stats_.put(Stats::FATAL_ERROR); return behavior_(*this); } @@ -262,9 +262,7 @@ namespace libp2p::regression { void onConnected(StreamAndProtocolOrError rstream) { if (!rstream) { - TRACE("({}): connect error: {}", - stats_.node_id, - rstream.error().message()); + TRACE("({}): connect error: {}", stats_.node_id, rstream.error()); stats_.put(Stats::CONNECT_FAILURE); } else { TRACE("({}): connected", stats_.node_id); diff --git a/test/libp2p/network/dialer_test.cpp b/test/libp2p/network/dialer_test.cpp index 65406b2d6..9b8bd3e8e 100644 --- a/test/libp2p/network/dialer_test.cpp +++ b/test/libp2p/network/dialer_test.cpp @@ -101,7 +101,7 @@ TEST_F(DialerTest, DialAllTheAddresses) { *transport, dial(pinfo_two_addrs.id, ma1, _, std::chrono::milliseconds::zero())) .WillOnce( - Arg2CallbackWithArg(outcome::failure(std::errc::connection_refused))); + Arg2CallbackWithArg(make_error_code(std::errc::connection_refused))); // transport->dial returns valid connection for the second address EXPECT_CALL( @@ -172,8 +172,7 @@ TEST_F(DialerTest, DialNoAddresses) { peer::PeerInfo pinfo = {pid, {}}; bool executed = false; dialer->dial(pinfo, [&](auto &&rconn) { - EXPECT_OUTCOME_FALSE(e, rconn); - EXPECT_EQ(e.value(), (int)std::errc::destination_address_required); + EXPECT_EC(rconn, std::errc::destination_address_required); executed = true; }); @@ -200,8 +199,7 @@ TEST_F(DialerTest, DialNoTransports) { bool executed = false; dialer->dial(pinfo, [&](auto &&rconn) { - EXPECT_OUTCOME_FALSE(e, rconn); - EXPECT_EQ(e.value(), (int)std::errc::address_family_not_supported); + EXPECT_EC(rconn, std::errc::address_family_not_supported); executed = true; }); @@ -254,13 +252,11 @@ TEST_F(DialerTest, NewStreamFailed) { // report random error. // we simulate a case when "newStream" gets error - outcome::result> r = std::errc::io_error; - EXPECT_CALL(*connection, newStream()).WillOnce(Return(r)); + EXPECT_CALL(*connection, newStream()).WillOnce(Return(std::errc::io_error)); bool executed = false; dialer->newStream(pinfo, protocols, [&](auto &&rstream) { - EXPECT_OUTCOME_FALSE(e, rstream); - EXPECT_EQ(e.value(), (int)std::errc::io_error); + EXPECT_EC(rstream, std::errc::io_error); executed = true; }); @@ -284,7 +280,7 @@ TEST_F(DialerTest, NewStreamNegotiationFailed) { // newStream returns valid stream EXPECT_CALL(*connection, newStream()).WillOnce(Return(stream)); - auto r = std::make_error_code(std::errc::io_error); + auto r = std::errc::io_error; auto if_protocols = [&](std::span actual) { auto expected = std::span(protocols); @@ -293,12 +289,11 @@ TEST_F(DialerTest, NewStreamNegotiationFailed) { }; EXPECT_CALL(*proto_muxer, selectOneOf(Truly(if_protocols), _, _, _, _)) - .WillOnce(InvokeArgument<4>(r)); + .WillOnce(InvokeArgument<4>(make_error_code(r))); bool executed = false; dialer->newStream(pinfo, protocols, [&](auto &&rstream) { - EXPECT_OUTCOME_FALSE(e, rstream); - EXPECT_EQ(e, r); + EXPECT_EC(rstream, r); executed = true; }); diff --git a/test/libp2p/peer/CMakeLists.txt b/test/libp2p/peer/CMakeLists.txt index 82e4d0fae..60ff2e3f4 100644 --- a/test/libp2p/peer/CMakeLists.txt +++ b/test/libp2p/peer/CMakeLists.txt @@ -20,6 +20,7 @@ addtest(peer_address_test ) target_link_libraries(peer_address_test p2p_peer_address + p2p_literals ) add_subdirectory(address_repository) diff --git a/test/libp2p/peer/address_repository/inmem_address_repository_test.cpp b/test/libp2p/peer/address_repository/inmem_address_repository_test.cpp index 2d0e6664c..cee49c805 100644 --- a/test/libp2p/peer/address_repository/inmem_address_repository_test.cpp +++ b/test/libp2p/peer/address_repository/inmem_address_repository_test.cpp @@ -69,8 +69,8 @@ TEST_F(InmemAddressRepository_Test, GarbageCollection) { // @when no collectGarbage is called { - EXPECT_OUTCOME_TRUE_2(v1, db->getAddresses(p1)); - EXPECT_OUTCOME_TRUE_2(v2, db->getAddresses(p2)); + EXPECT_OUTCOME_TRUE(v1, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v2, db->getAddresses(p2)); // @then initial state is initial EXPECT_EQ(v1.size(), 4); @@ -81,8 +81,8 @@ TEST_F(InmemAddressRepository_Test, GarbageCollection) { collectGarbage(); { - EXPECT_OUTCOME_TRUE_2(v1, db->getAddresses(p1)); - EXPECT_OUTCOME_TRUE_2(v2, db->getAddresses(p2)); + EXPECT_OUTCOME_TRUE(v1, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v2, db->getAddresses(p2)); // @then no addresses are evicted EXPECT_EQ(v1.size(), 4); @@ -96,14 +96,13 @@ TEST_F(InmemAddressRepository_Test, GarbageCollection) { { // @then p1 has evicted 2 addresses - EXPECT_OUTCOME_TRUE_2(v1, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v1, db->getAddresses(p1)); EXPECT_EQ(v1.size(), 2); // @and p2 has been evicted completely auto v2 = db->getAddresses(p2); - EXPECT_FALSE(v2); // peers without addresses are removed... so we can't find this peer - EXPECT_EQ(v2.error().value(), (int)PeerError::NOT_FOUND); + EXPECT_EC(v2, PeerError::NOT_FOUND); } // @when clear p1 addresses @@ -113,13 +112,12 @@ TEST_F(InmemAddressRepository_Test, GarbageCollection) { // @then p1 is not evicted, but all its addresses are // since we intentionally cleared addresses of this peer, we do not evict // this peer from the list of known peers up to the next garbage collection - EXPECT_OUTCOME_TRUE_2(v1, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v1, db->getAddresses(p1)); EXPECT_EQ(v1.size(), 0); // @and p2 is still evicted auto v2 = db->getAddresses(p2); - EXPECT_FALSE(v2); - EXPECT_EQ(v2.error().value(), (int)PeerError::NOT_FOUND); + EXPECT_EC(v2, PeerError::NOT_FOUND); } // @when third collect garbage is called @@ -130,8 +128,7 @@ TEST_F(InmemAddressRepository_Test, GarbageCollection) { // last garbage collection removed all peers that do not have addresses for (const auto &it : {p1, p2}) { auto v = db->getAddresses(it); - EXPECT_FALSE(v); - EXPECT_EQ(v.error().value(), (int)PeerError::NOT_FOUND); + EXPECT_EC(v, PeerError::NOT_FOUND); } } } @@ -148,7 +145,7 @@ TEST_F(InmemAddressRepository_Test, UpdateAddress) { db->upsertAddresses(p1, std::vector{ma1}, 1000ms)); { - EXPECT_OUTCOME_TRUE_2(v, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v, db->getAddresses(p1)); EXPECT_EQ(v.size(), 1); } @@ -156,7 +153,7 @@ TEST_F(InmemAddressRepository_Test, UpdateAddress) { collectGarbage(); // ma1 is updated - EXPECT_OUTCOME_TRUE_2(v, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v, db->getAddresses(p1)); EXPECT_EQ(v.size(), 1); } @@ -172,7 +169,7 @@ TEST_F(InmemAddressRepository_Test, InsertAddress) { db->upsertAddresses(p1, std::vector{ma2}, 1000ms)); { - EXPECT_OUTCOME_TRUE_2(v, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v, db->getAddresses(p1)); EXPECT_EQ(v.size(), 2); } @@ -180,7 +177,7 @@ TEST_F(InmemAddressRepository_Test, InsertAddress) { collectGarbage(); // ma1 is evicted, ma2 is not - EXPECT_OUTCOME_TRUE_2(v, db->getAddresses(p1)); + EXPECT_OUTCOME_TRUE(v, db->getAddresses(p1)); EXPECT_EQ(v.size(), 1); EXPECT_EQ(v.front(), ma2); } diff --git a/test/libp2p/peer/key_book/inmem_key_repository_test.cpp b/test/libp2p/peer/key_book/inmem_key_repository_test.cpp index be3fac169..6ab7c5db9 100644 --- a/test/libp2p/peer/key_book/inmem_key_repository_test.cpp +++ b/test/libp2p/peer/key_book/inmem_key_repository_test.cpp @@ -20,15 +20,7 @@ using namespace libp2p::crypto; struct InmemKeyRepositoryTest : ::testing::Test { static PeerId createPeerId(HashType type, Buffer b) { auto hash = Multihash::create(type, std::move(b)); - if (!hash) { - throw std::invalid_argument(hash.error().message()); - } - auto r1 = PeerId::fromHash(hash.value()); - if (!r1) { - throw std::invalid_argument(r1.error().message()); - } - return r1.value(); } diff --git a/test/libp2p/peer/peer_address_test.cpp b/test/libp2p/peer/peer_address_test.cpp index 97f37d7b7..71f255537 100644 --- a/test/libp2p/peer/peer_address_test.cpp +++ b/test/libp2p/peer/peer_address_test.cpp @@ -7,7 +7,7 @@ #include #include -#include +#include #include #include #include @@ -18,6 +18,7 @@ using namespace libp2p::common; using namespace libp2p::multi; using namespace libp2p::peer; using namespace libp2p::common; +using libp2p::common::operator""_unhex; class PeerAddressTest : public ::testing::Test { public: @@ -25,8 +26,7 @@ class PeerAddressTest : public ::testing::Test { std::make_shared(); Bytes hash = - unhex("af85e416fa66390b3c834cb6b7aeafb8b4b484e7245fd9a9d81e7f3f5f95714f") - .value(); + "af85e416fa66390b3c834cb6b7aeafb8b4b484e7245fd9a9d81e7f3f5f95714f"_unhex; const Multihash kDefaultMultihash = Multihash::create(HashType::sha256, hash).value(); @@ -49,7 +49,7 @@ class PeerAddressTest : public ::testing::Test { * @then creation is successful */ TEST_F(PeerAddressTest, FromStringSuccess) { - ASSERT_OUTCOME_SUCCESS(address, PeerAddress::create(kAddressString)) + EXPECT_OUTCOME_TRUE(address, PeerAddress::create(kAddressString)) EXPECT_EQ(address.toString(), kAddressString); EXPECT_EQ(address.getId(), kDefaultPeerId); EXPECT_EQ(address.getAddress(), kDefaultAddress); diff --git a/test/libp2p/peer/protocol_repository/inmem_protocol_repository_test.cpp b/test/libp2p/peer/protocol_repository/inmem_protocol_repository_test.cpp index 1d66fed21..54305ae13 100644 --- a/test/libp2p/peer/protocol_repository/inmem_protocol_repository_test.cpp +++ b/test/libp2p/peer/protocol_repository/inmem_protocol_repository_test.cpp @@ -49,12 +49,11 @@ struct InmemProtocolRepository_Test : public ::testing::Test { TEST_F(InmemProtocolRepository_Test, Add) { EXPECT_OUTCOME_TRUE_1(db->addProtocols(p1, vec(s1, s2))); { - EXPECT_OUTCOME_TRUE_2(v, db->getProtocols(p1)); + EXPECT_OUTCOME_TRUE(v, db->getProtocols(p1)); EXPECT_EQ(v.size(), 2); auto r = db->getProtocols(p2); - EXPECT_FALSE(r); - EXPECT_EQ(r.error().value(), (int)PeerError::NOT_FOUND); + EXPECT_EC(r, PeerError::NOT_FOUND); } } @@ -71,12 +70,11 @@ TEST_F(InmemProtocolRepository_Test, CollectGarbage) { db->collectGarbage(); { - EXPECT_OUTCOME_TRUE_2(v, db->getProtocols(p1)); + EXPECT_OUTCOME_TRUE(v, db->getProtocols(p1)); EXPECT_EQ(v.size(), 2); auto r = db->getProtocols(p2); - EXPECT_FALSE(r); - EXPECT_EQ(r.error().value(), (int)PeerError::NOT_FOUND); + EXPECT_EC(r, PeerError::NOT_FOUND); } // clear p1. now p1 has 0 protocols @@ -88,8 +86,7 @@ TEST_F(InmemProtocolRepository_Test, CollectGarbage) { { for (const auto &it : {p1, p2}) { auto r = db->getProtocols(it); - EXPECT_FALSE(r); - EXPECT_EQ(r.error().value(), (int)PeerError::NOT_FOUND); + EXPECT_EC(r, PeerError::NOT_FOUND); } } } @@ -104,26 +101,26 @@ TEST_F(InmemProtocolRepository_Test, Supports) { // one of { - EXPECT_OUTCOME_TRUE_2(v, db->supportsProtocols(p1, set(s1))); + EXPECT_OUTCOME_TRUE(v, db->supportsProtocols(p1, set(s1))); EXPECT_EQ(v, vec(s1)); } // forward order { - EXPECT_OUTCOME_TRUE_2(v, db->supportsProtocols(p1, set(s1, s2))); + EXPECT_OUTCOME_TRUE(v, db->supportsProtocols(p1, set(s1, s2))); EXPECT_EQ(v, vec(s1, s2)); } // reverse order { - EXPECT_OUTCOME_TRUE_2(v, db->supportsProtocols(p1, set(s2, s1))); + EXPECT_OUTCOME_TRUE(v, db->supportsProtocols(p1, set(s2, s1))); EXPECT_EQ(v, vec(s1, s2)); } // non existing { EXPECT_OUTCOME_TRUE_1(db->removeProtocols(p1, vec(s1))); - EXPECT_OUTCOME_TRUE_2(v, db->supportsProtocols(p1, set(s1, s2))); + EXPECT_OUTCOME_TRUE(v, db->supportsProtocols(p1, set(s1, s2))); EXPECT_EQ(v, vec(s2)); } } @@ -136,7 +133,7 @@ TEST_F(InmemProtocolRepository_Test, Supports) { TEST_F(InmemProtocolRepository_Test, Remove) { EXPECT_OUTCOME_TRUE_1(db->addProtocols(p1, vec(s1, s2))); EXPECT_OUTCOME_TRUE_1(db->removeProtocols(p1, vec(s1))); - EXPECT_OUTCOME_TRUE_2(v, db->getProtocols(p1)); + EXPECT_OUTCOME_TRUE(v, db->getProtocols(p1)); EXPECT_EQ(v, vec(s2)); } @@ -148,7 +145,7 @@ TEST_F(InmemProtocolRepository_Test, Remove) { TEST_F(InmemProtocolRepository_Test, RemoveNonExisting) { EXPECT_OUTCOME_TRUE_1(db->addProtocols(p1, vec(s2))); EXPECT_OUTCOME_TRUE_1(db->removeProtocols(p1, vec(s1))); - EXPECT_OUTCOME_TRUE_2(v, db->getProtocols(p1)); + EXPECT_OUTCOME_TRUE(v, db->getProtocols(p1)); EXPECT_EQ(v.size(), 1); } diff --git a/test/libp2p/protocol/identify_test.cpp b/test/libp2p/protocol/identify_test.cpp index 81446d5be..3c6c0018e 100644 --- a/test/libp2p/protocol/identify_test.cpp +++ b/test/libp2p/protocol/identify_test.cpp @@ -6,8 +6,6 @@ #include -#include - #include #include #include diff --git a/test/libp2p/protocol/kademlia/CMakeLists.txt b/test/libp2p/protocol/kademlia/CMakeLists.txt index 4936022ad..8de0d1ef9 100644 --- a/test/libp2p/protocol/kademlia/CMakeLists.txt +++ b/test/libp2p/protocol/kademlia/CMakeLists.txt @@ -4,10 +4,10 @@ # SPDX-License-Identifier: Apache-2.0 # -addtest(node_id +addtest(node_id_test node_id_test.cpp ) -target_link_libraries(node_id +target_link_libraries(node_id_test p2p_sha p2p_testutil_peer p2p_literals diff --git a/test/libp2p/protocol/kademlia/peer_routing_table_test.cpp b/test/libp2p/protocol/kademlia/peer_routing_table_test.cpp index fd29b4363..4187f6a3e 100644 --- a/test/libp2p/protocol/kademlia/peer_routing_table_test.cpp +++ b/test/libp2p/protocol/kademlia/peer_routing_table_test.cpp @@ -92,7 +92,7 @@ TEST_F(PeerRoutingTableTest, FindMultiple) { std::generate_n(std::back_inserter(peers), 18, testutil::randomPeerId); for (const auto &peer : peers) { - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peer, false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peer, false)); } auto found = table_->getNearestPeers(NodeId(peers[2]), 15); @@ -134,31 +134,31 @@ TEST_F(PeerRoutingTableTest, RecyclingTest) { } } - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[0], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[0], false)); ASSERT_TRUE(hasPeer(peerset, peers[0])) << "should have this peer"; - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[1], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[1], false)); ASSERT_FALSE(hasPeer(peerset, peers[0])) << "should have recycled peer"; ASSERT_TRUE(hasPeer(peerset, peers[1])) << "should have this peer"; - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[2], true)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[2], true)); ASSERT_FALSE(hasPeer(peerset, peers[0])) << "should have recycled peer"; ASSERT_FALSE(hasPeer(peerset, peers[1])) << "should have recycled peer"; ASSERT_TRUE(hasPeer(peerset, peers[2])) << "should have this peer"; // if bucket is full of permanent peers addition of peers into same bucket // should fail - ASSERT_OUTCOME_ERROR(table_->update(peers[0], false), - PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); - ASSERT_OUTCOME_ERROR(table_->update(peers[1], true), - PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); + EXPECT_EC(table_->update(peers[0], false), + PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); + EXPECT_EC(table_->update(peers[1], true), + PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); // re-adding an existent peer should return false regardless of is permanent auto updateVal = table_->update(peers[2], true); - ASSERT_OUTCOME_SUCCESS_TRY(updateVal); + EXPECT_OUTCOME_TRUE_1(updateVal); ASSERT_FALSE(updateVal.value()); updateVal = table_->update(peers[2], false); - ASSERT_OUTCOME_SUCCESS_TRY(updateVal); + EXPECT_OUTCOME_TRUE_1(updateVal); ASSERT_FALSE(updateVal.value()); } @@ -191,18 +191,18 @@ TEST_F(PeerRoutingTableTest, PreferLongLivedPeers) { } } // recycle FIFO; known peers but not connected dont get boost - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[0], false)); - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[1], false)); - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[0], false)); - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[2], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[0], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[1], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[0], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[2], false)); ASSERT_FALSE(hasPeer(peerset, peers[0])); ASSERT_TRUE(hasPeer(peerset, peers[1])); ASSERT_TRUE(hasPeer(peerset, peers[2])); // if connected; peer gets a boost - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[1], false, true)); - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[0], false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[1], false, true)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[0], false)); ASSERT_TRUE(hasPeer(peerset, peers[0])); ASSERT_TRUE(hasPeer(peerset, peers[1])); @@ -228,12 +228,11 @@ TEST_F(PeerRoutingTableTest, EldestRecycledIfNotPermanent) { for (size_t i = 0; i < peers.size(); i++) { if (i < config_->maxBucketSize) { // peers added till bucket filled are accepted - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[i], true)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[i], true)); } else { // Remained are rejected - ASSERT_OUTCOME_ERROR( - table_->update(peers[i], true), - PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); + EXPECT_EC(table_->update(peers[i], true), + PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); } } } @@ -257,12 +256,11 @@ TEST_F(PeerRoutingTableTest, EldestPrefferedIfPermanent) { for (size_t i = 0; i < peers.size(); i++) { if (i < config_->maxBucketSize) { // peers added till bucket filled are accepted - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peers[i], true)); + EXPECT_OUTCOME_TRUE_1(table_->update(peers[i], true)); } else { // Remained are rejected - ASSERT_OUTCOME_ERROR( - table_->update(peers[i], true), - PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); + EXPECT_EC(table_->update(peers[i], true), + PeerRoutingTableImpl::Error::PEER_REJECTED_NO_CAPACITY); } } } @@ -309,7 +307,7 @@ TEST_F(PeerRoutingTableTest, Find) { std::generate_n(std::back_inserter(peers), nPeers, testutil::randomPeerId); for (const auto &peer : peers) { - ASSERT_OUTCOME_SUCCESS_TRY(table_->update(peer, false)); + EXPECT_OUTCOME_TRUE_1(table_->update(peer, false)); } ASSERT_EQ(table_->size(), nPeers); diff --git a/test/libp2p/protocol/ping_test.cpp b/test/libp2p/protocol/ping_test.cpp index 4980b9236..81e1acefb 100644 --- a/test/libp2p/protocol/ping_test.cpp +++ b/test/libp2p/protocol/ping_test.cpp @@ -17,12 +17,15 @@ #include #include +#include "mock/libp2p/basic/scheduler_mock.hpp" #include "mock/libp2p/connection/capable_connection_mock.hpp" #include "mock/libp2p/connection/stream_mock.hpp" #include "mock/libp2p/crypto/random_generator_mock.hpp" #include "mock/libp2p/host/host_mock.hpp" #include "mock/libp2p/peer/peer_repository_mock.hpp" +using libp2p::basic::Scheduler; +using libp2p::basic::SchedulerMock; using namespace libp2p; using namespace common; using namespace protocol; @@ -39,19 +42,38 @@ using testing::Truly; using std::chrono_literals::operator""ms; +constexpr auto kTimeout = 100ms; +constexpr auto kInterval = 1ms; + class PingTest : public testing::Test { public: static constexpr uint32_t kPingMsgSize = 32; - boost::asio::io_context io_context_; + void setTimer(bool timeout) { + EXPECT_CALL(*scheduler_, scheduleImplMockCall(_, kInterval, true)) + .WillRepeatedly([](auto cb, auto, auto) { + cb(); + return Scheduler::Handle{}; + }); + EXPECT_CALL(*scheduler_, scheduleImplMockCall(_, kTimeout, true)) + .WillRepeatedly([timeout](auto cb, auto, auto) { + if (timeout) { + cb(); + } + return Scheduler::Handle{}; + }); + } + + std::shared_ptr scheduler_ = std::make_shared(); libp2p::event::Bus bus_; HostMock host_; std::shared_ptr rand_gen_ = std::make_shared(); - std::shared_ptr ping_ = std::make_shared( - host_, bus_, io_context_, rand_gen_, PingConfig{1, kPingMsgSize}); + PingConfig config_{kTimeout, kInterval, kPingMsgSize}; + std::shared_ptr ping_ = + std::make_shared(host_, bus_, scheduler_, rand_gen_, config_); std::shared_ptr conn_ = std::make_shared(); @@ -79,7 +101,7 @@ TEST_F(PingTest, PingServer) { EXPECT_CALL(*stream_, read(_, kPingMsgSize, _)) .WillOnce(ReadPut(buffer_)) .WillOnce( // no second read - InvokeArgument<2>(outcome::failure(boost::system::error_code{}))); + InvokeArgument<2>(std::error_code{})); auto if_eq_buf = [&](BytesIn actual) { auto expected = BytesIn(buffer_); @@ -103,6 +125,8 @@ TEST_F(PingTest, PingServer) { * @then a Ping message is sent over that stream @and we expect to get it back */ TEST_F(PingTest, PingClient) { + setTimer(false); + EXPECT_CALL(*conn_, remotePeer()).WillOnce(Return(peer_id_)); EXPECT_CALL(host_, getPeerRepository()).WillOnce(ReturnRef(peer_repo_)); EXPECT_CALL(peer_repo_, getPeerInfo(peer_id_)).WillOnce(Return(peer_info_)); @@ -120,8 +144,8 @@ TEST_F(PingTest, PingClient) { EXPECT_CALL(*stream_, writeSome(Truly(if_eq_buf), kPingMsgSize, _)) .WillOnce(InvokeArgument<2>(buffer_.size())) .WillOnce( // no second write - InvokeArgument<2>(outcome::failure(boost::system::error_code{ - boost::asio::error::invalid_argument}))); + InvokeArgument<2>( + make_error_code(boost::asio::error::invalid_argument))); EXPECT_CALL(*stream_, read(_, kPingMsgSize, _)).WillOnce(ReadPut(buffer_)); EXPECT_CALL(*stream_, isClosedForWrite()) @@ -130,11 +154,10 @@ TEST_F(PingTest, PingClient) { EXPECT_CALL(*stream_, isClosedForRead()).WillOnce(Return(false)); EXPECT_CALL(*stream_, remotePeerId()).WillOnce(Return(peer_id_)); + EXPECT_CALL(*stream_, reset()); ping_->startPinging(conn_, [](auto &&session_res) { ASSERT_TRUE(session_res); }); - - io_context_.run_for(100ms); } /** @@ -144,6 +167,8 @@ TEST_F(PingTest, PingClient) { * @then PingIsDead event is emitted over the bus */ TEST_F(PingTest, PingClientTimeoutExpired) { + setTimer(true); + EXPECT_CALL(*conn_, remotePeer()).WillOnce(Return(peer_id_)); EXPECT_CALL(host_, getPeerRepository()).WillOnce(ReturnRef(peer_repo_)); EXPECT_CALL(peer_repo_, getPeerInfo(peer_id_)).WillOnce(Return(peer_info_)); @@ -161,6 +186,7 @@ TEST_F(PingTest, PingClientTimeoutExpired) { EXPECT_CALL(*stream_, isClosedForWrite()).WillOnce(Return(false)); EXPECT_CALL(*stream_, remotePeerId()).WillOnce(Return(peer_id_)); + EXPECT_CALL(*stream_, reset()); boost::optional dead_peer_id; auto h = bus_.getChannel().subscribe( @@ -169,8 +195,6 @@ TEST_F(PingTest, PingClientTimeoutExpired) { ping_->startPinging(conn_, [](auto &&session_res) { ASSERT_TRUE(session_res); }); - io_context_.run_for(100ms); - ASSERT_TRUE(dead_peer_id); ASSERT_EQ(*dead_peer_id, peer_id_); } diff --git a/test/libp2p/security/plaintext_adaptor_test.cpp b/test/libp2p/security/plaintext_adaptor_test.cpp index 13a6c7a59..671f92da9 100644 --- a/test/libp2p/security/plaintext_adaptor_test.cpp +++ b/test/libp2p/security/plaintext_adaptor_test.cpp @@ -7,7 +7,6 @@ #include "libp2p/security/plaintext/plaintext.hpp" #include -#include #include #include #include diff --git a/test/libp2p/transport/multiaddress_parser_test.cpp b/test/libp2p/transport/multiaddress_parser_test.cpp index 2edcf60cf..43bd48da3 100644 --- a/test/libp2p/transport/multiaddress_parser_test.cpp +++ b/test/libp2p/transport/multiaddress_parser_test.cpp @@ -8,7 +8,6 @@ #include #include -#include #include "testutil/outcome.hpp" using libp2p::multi::Multiaddress; diff --git a/test/libp2p/transport/tcp/tcp_integration_test.cpp b/test/libp2p/transport/tcp/tcp_integration_test.cpp index a7d40bd7d..62c5de6bb 100644 --- a/test/libp2p/transport/tcp/tcp_integration_test.cpp +++ b/test/libp2p/transport/tcp/tcp_integration_test.cpp @@ -38,8 +38,8 @@ using ::testing::Return; namespace { std::shared_ptr expectConnectionValid( - libp2p::outcome::result> rconn) { - EXPECT_TRUE(rconn) << rconn.error(); + outcome::result> rconn) { + EXPECT_OUTCOME_TRUE_1(rconn); auto conn = rconn.value(); EXPECT_OUTCOME_TRUE(mar, conn->remoteMultiaddr()) @@ -113,7 +113,7 @@ TEST(TCP, TwoListenersCantBindOnSamePort) { std::cout << "listener 2 starting...\n"; auto r = listener2->listen(ma); - ASSERT_EQ(r.error().value(), (int)std::errc::address_in_use); + EXPECT_EC(r, boost::asio::error::address_in_use); using std::chrono_literals::operator""ms; context->run_for(50ms); @@ -141,11 +141,11 @@ TEST(TCP, SingleListenerCanAcceptManyClients) { auto buf = std::make_shared>(kSize, 0); conn->readSome( *buf, buf->size(), [&counter, conn, buf, context](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); libp2p::writeReturnSize( conn, *buf, [&counter, conn, buf, context](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); EXPECT_EQ(res.value(), buf->size()); counter++; if (counter >= kClients) { @@ -178,13 +178,13 @@ TEST(TCP, SingleListenerCanAcceptManyClients) { libp2p::writeReturnSize( conn, *buf, [conn, readback, buf, context](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), buf->size()); conn->read(*readback, readback->size(), [conn, readback, buf, context](auto &&res) { context->stop(); - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), readback->size()); ASSERT_EQ(*buf, *readback); }); @@ -214,8 +214,7 @@ TEST(TCP, DialToNoServer) { auto ma = "/ip4/127.0.0.1/tcp/40003"_multiaddr; transport->dial(testutil::randomPeerId(), ma, [](auto &&rc) { - ASSERT_FALSE(rc); - ASSERT_EQ(rc.error().value(), (int)std::errc::connection_refused); + EXPECT_EC(rc, boost::asio::error::connection_refused); }); using std::chrono_literals::operator""ms; @@ -237,9 +236,7 @@ TEST(TCP, ClientClosesConnection) { auto buf = std::make_shared>(100, 0); conn->readSome(*buf, buf->size(), [conn, buf](auto &&res) { - ASSERT_FALSE(res); - ASSERT_EQ(res.error().value(), (int)boost::asio::error::eof) - << res.error().message(); + EXPECT_EC(res, boost::asio::error::eof); }); }); @@ -280,9 +277,7 @@ TEST(TCP, ServerClosesConnection) { EXPECT_TRUE(conn->isInitiator()); auto buf = std::make_shared>(100, 0); conn->readSome(*buf, buf->size(), [conn, buf](auto &&res) { - ASSERT_FALSE(res); - ASSERT_EQ(res.error().value(), (int)boost::asio::error::eof) - << res.error().message(); + EXPECT_EC(res, boost::asio::error::eof); }); }); @@ -307,10 +302,10 @@ TEST(TCP, OneTransportServerHandlesManyClients) { auto buf = std::make_shared>(kSize, 0); conn->readSome(*buf, kSize, [&counter, conn, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); libp2p::writeReturnSize(conn, *buf, [&counter, buf, conn](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); EXPECT_EQ(res.value(), buf->size()); counter++; }); @@ -337,10 +332,10 @@ TEST(TCP, OneTransportServerHandlesManyClients) { libp2p::writeReturnSize( conn, *buf, [conn, kSize, readback, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), buf->size()); conn->read(*readback, kSize, [conn, readback, buf](auto &&res) { - ASSERT_TRUE(res) << res.error().message(); + EXPECT_OUTCOME_TRUE_1(res); ASSERT_EQ(res.value(), readback->size()); ASSERT_EQ(*buf, *readback); }); diff --git a/test/libp2p/transport/tcp/tcp_listener_test.cpp b/test/libp2p/transport/tcp/tcp_listener_test.cpp index ac7d3d21a..6fbb04886 100644 --- a/test/libp2p/transport/tcp/tcp_listener_test.cpp +++ b/test/libp2p/transport/tcp/tcp_listener_test.cpp @@ -55,11 +55,7 @@ struct TcpListenerTest : public ::testing::Test { */ TEST_F(TcpListenerTest, ListenCloseListen) { EXPECT_CALL(cb, Call(_)).WillRepeatedly(Invoke([](CapConnResult c) { - if (!c) { - ASSERT_EQ(c.error().value(), (int)std::errc::operation_canceled); - } else { - ADD_FAILURE(); - } + EXPECT_EC(c, boost::asio::error::operation_aborted); })); EXPECT_OUTCOME_TRUE_1(listener->listen(ma)); @@ -83,7 +79,7 @@ TEST_F(TcpListenerTest, ListenCloseListen) { TEST_F(TcpListenerTest, DoubleClose) { EXPECT_CALL(cb, Call(_)).WillOnce(Invoke([](CapConnResult c) { if (!c) { - ASSERT_EQ(c.error().value(), (int)std::errc::operation_canceled); + EXPECT_EC(c, boost::asio::error::operation_aborted); } })); diff --git a/test/libp2p/transport/upgrader_test.cpp b/test/libp2p/transport/upgrader_test.cpp index 0449268ad..9c804a31f 100644 --- a/test/libp2p/transport/upgrader_test.cpp +++ b/test/libp2p/transport/upgrader_test.cpp @@ -40,8 +40,7 @@ using testing::NiceMock; using testing::Return; using testing::Truly; -using libp2p::outcome::failure; -using libp2p::outcome::success; +using outcome::success; class UpgraderTest : public testing::Test { protected: @@ -126,7 +125,7 @@ class UpgraderTest : public testing::Test { TEST_F(UpgraderTest, UpgradeLayersInitiator) { setAllOutbound(); - ASSERT_OUTCOME_SUCCESS( + EXPECT_OUTCOME_TRUE( address, libp2p::multi::Multiaddress::create( "/ip4/127.0.0.1/tcp/1234/_dummy_proto_1/_dummy_proto_2" @@ -146,7 +145,7 @@ TEST_F(UpgraderTest, UpgradeLayersInitiator) { upgrader_->upgradeLayersOutbound( address, raw_conn_, layers, [this](auto &&upgraded_conn_res) { - ASSERT_OUTCOME_SUCCESS(upgraded_conn, upgraded_conn_res); + EXPECT_OUTCOME_TRUE(upgraded_conn, upgraded_conn_res); ASSERT_EQ(upgraded_conn, layer2_conn_); }); } @@ -154,7 +153,7 @@ TEST_F(UpgraderTest, UpgradeLayersInitiator) { TEST_F(UpgraderTest, UpgradeLayersNotInitiator) { setAllInbound(); - ASSERT_OUTCOME_SUCCESS( + EXPECT_OUTCOME_TRUE( address, libp2p::multi::Multiaddress::create( "/ip4/127.0.0.1/tcp/1234/_dummy_proto_1/_dummy_proto_2" @@ -250,7 +249,7 @@ TEST_F(UpgraderTest, UpgradeSecureFail) { false, true, _)) - .WillOnce(Arg4CallbackWithArg(failure(std::error_code()))); + .WillOnce(Arg4CallbackWithArg(std::error_code{})); upgrader_->upgradeToSecureInbound(layer2_conn_, [](auto &&upgraded_conn_res) { ASSERT_FALSE(upgraded_conn_res); @@ -299,7 +298,7 @@ TEST_F(UpgraderTest, UpgradeMuxFail) { true, true, _)) - .WillOnce(Arg4CallbackWithArg(failure(std::error_code()))); + .WillOnce(Arg4CallbackWithArg(std::error_code{})); upgrader_->upgradeToMuxed(sec_conn_, [](auto &&upgraded_conn_res) { ASSERT_FALSE(upgraded_conn_res); diff --git a/test/mock/libp2p/basic/reader_mock.hpp b/test/mock/libp2p/basic/reader_mock.hpp index 61c827e98..9ccd84c4d 100644 --- a/test/mock/libp2p/basic/reader_mock.hpp +++ b/test/mock/libp2p/basic/reader_mock.hpp @@ -10,8 +10,6 @@ #include -#include - namespace libp2p::basic { class ReaderMock : public Reader { public: @@ -21,9 +19,3 @@ namespace libp2p::basic { MOCK_METHOD2(readSome, void(BytesOut, Reader::ReadCallbackFunc)); }; } // namespace libp2p::basic - -inline std::ostream &operator<<(std::ostream &s, - const std::vector &v) { - s << common::hex_upper(v) << "\n"; - return s; -} diff --git a/test/mock/libp2p/basic/readwritecloser_mock.hpp b/test/mock/libp2p/basic/readwritecloser_mock.hpp index 6248e6f76..be108e9a7 100644 --- a/test/mock/libp2p/basic/readwritecloser_mock.hpp +++ b/test/mock/libp2p/basic/readwritecloser_mock.hpp @@ -10,8 +10,6 @@ #include -#include - namespace libp2p::basic { class ReadWriteCloserMock : public ReadWriteCloser { public: @@ -26,9 +24,3 @@ namespace libp2p::basic { MOCK_METHOD2(writeSome, void(BytesIn, Writer::WriteCallbackFunc)); }; } // namespace libp2p::basic - -inline std::ostream &operator<<(std::ostream &s, - const std::vector &v) { - s << kagome::common::hex_upper(v) << "\n"; - return s; -} diff --git a/test/testutil/outcome.hpp b/test/testutil/outcome.hpp index e2a9747b8..25e27d8ab 100644 --- a/test/testutil/outcome.hpp +++ b/test/testutil/outcome.hpp @@ -7,53 +7,29 @@ #pragma once #include -#include #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic ignored "-Wparentheses" #endif -#define PP_CAT(a, b) PP_CAT_I(a, b) -#define PP_CAT_I(a, b) PP_CAT_II(~, a##b) -#define PP_CAT_II(p, res) res +#define EXPECT_OUTCOME_TRUE_VOID(var, expr) \ + auto && (var) = expr; \ + EXPECT_TRUE(var) << "Line " << __LINE__ << ": " \ + << fmt::to_string(var.error()); -#define UNIQUE_NAME(base) PP_CAT(base, __LINE__) - -#define EXPECT_OUTCOME_TRUE_VOID(var, expr) \ - auto && (var) = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << (var).error().message(); - -#define EXPECT_OUTCOME_TRUE_NAME(var, val, expr) \ - auto && (var) = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << (var).error().message(); \ +#define EXPECT_OUTCOME_TRUE_NAME(var, val, expr) \ + EXPECT_OUTCOME_TRUE_VOID(var, expr) \ auto && (val) = (var).value(); #define EXPECT_OUTCOME_FALSE_VOID(var, expr) \ auto && (var) = expr; \ - EXPECT_FALSE(var) << "Line " << __LINE__ << ": " << (var).error().message(); - -#define EXPECT_OUTCOME_FALSE_NAME(var, val, expr) \ - auto && (var) = expr; \ - EXPECT_FALSE(var) << "Line " << __LINE__ << ": " << (var).error().message(); \ - auto && (val) = (var).error(); - -#define EXPECT_OUTCOME_TRUE_3(var, val, expr) \ - EXPECT_OUTCOME_TRUE_NAME(var, val, expr) - -#define EXPECT_OUTCOME_TRUE_2(val, expr) \ - EXPECT_OUTCOME_TRUE_3(UNIQUE_NAME(_r), val, expr) + EXPECT_FALSE(var) << "Line " << __LINE__; #define EXPECT_OUTCOME_TRUE_1(expr) \ - EXPECT_OUTCOME_TRUE_VOID(UNIQUE_NAME(_v), expr) - -#define EXPECT_OUTCOME_FALSE_3(var, val, expr) \ - EXPECT_OUTCOME_FALSE_NAME(var, val, expr) - -#define EXPECT_OUTCOME_FALSE_2(val, expr) \ - EXPECT_OUTCOME_FALSE_3(UNIQUE_NAME(_r), val, expr) + EXPECT_OUTCOME_TRUE_VOID(BOOST_OUTCOME_TRY_UNIQUE_NAME, expr) #define EXPECT_OUTCOME_FALSE_1(expr) \ - EXPECT_OUTCOME_FALSE_VOID(UNIQUE_NAME(_v), expr) + EXPECT_OUTCOME_FALSE_VOID(BOOST_OUTCOME_TRY_UNIQUE_NAME, expr) /** * Use this macro in GTEST with 2 arguments to assert that getResult() @@ -61,119 +37,11 @@ * EXPECT_OUTCOME_TRUE(val, getResult()); */ #define EXPECT_OUTCOME_TRUE(val, expr) \ - EXPECT_OUTCOME_TRUE_NAME(UNIQUE_NAME(_r), val, expr) - -#define EXPECT_OUTCOME_FALSE(val, expr) \ - EXPECT_OUTCOME_FALSE_NAME(UNIQUE_NAME(_f), val, expr) - -#define EXPECT_OUTCOME_TRUE_MSG_VOID(var, expr, msg) \ - auto && (var) = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << (var).error().message() \ - << "\t" << (msg); - -#define EXPECT_OUTCOME_TRUE_MSG_NAME(var, val, expr, msg) \ - auto && (var) = expr; \ - EXPECT_TRUE(var) << "Line " << __LINE__ << ": " << (var).error().message() \ - << "\t" << (msg); \ - auto && (val) = (var).value(); - -/** - * Use this macro in GTEST with 2 arguments to assert that - * result of expression as outcome::result is value and, - * but the value itself is not necessary. - * If result is error, macro prints corresponding error message - * and appends custom error message specified in msg. - */ -#define EXPECT_OUTCOME_TRUE_MSG_1(expr, msg) \ - EXPECT_OUTCOME_TRUE_MSG_VOID(UNIQUE_NAME(_v), expr, msg) - -/** - * Use this macro in GTEST with 3 arguments to assert that - * result of expression as outcome::result is value and - * immediately get access to this value. - * If result is error, macro prints corresponding error message - * and appends custom error message specified in msg. - */ -#define EXPECT_OUTCOME_TRUE_MSG(val, expr, msg) \ - EXPECT_OUTCOME_TRUE_MSG_NAME(UNIQUE_NAME(_r), val, expr, msg) - -#define _OUTCOME_UNIQUE_NAME_GLUE2(x, y) x##y -#define _OUTCOME_UNIQUE_NAME_GLUE(x, y) _OUTCOME_UNIQUE_NAME_GLUE2(x, y) -#define _OUTCOME_UNIQUE_NAME \ - _OUTCOME_UNIQUE_NAME_GLUE(__outcome_result, __COUNTER__) - -#define _ASSERT_OUTCOME_SUCCESS_TRY(_result_, _expression_) \ - auto &&_result_ = (_expression_); \ - if (not(_result_).has_value()) { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << _result_.error().message() << "'\n" \ - << "Expected: Success"; \ - } - -#define _ASSERT_OUTCOME_SUCCESS(_result_, _variable_, _expression_) \ - _ASSERT_OUTCOME_SUCCESS_TRY(_result_, _expression_); \ - auto &&_variable_ = std::move(_result_.value()); - -#define ASSERT_OUTCOME_SUCCESS(_variable_, _expression_) \ - _ASSERT_OUTCOME_SUCCESS(_OUTCOME_UNIQUE_NAME, _variable_, _expression_) - -#define ASSERT_OUTCOME_SUCCESS_TRY(_expression_) \ - { _ASSERT_OUTCOME_SUCCESS_TRY(_OUTCOME_UNIQUE_NAME, _expression_); } - -#define ASSERT_OUTCOME_SOME_ERROR(_expression_) \ - { \ - auto &&result = (_expression_); \ - if (not result.has_error()) { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Some error"; \ - } \ - } - -#define ASSERT_OUTCOME_ERROR(_expression_, _error_) \ - { \ - auto &&result = (_expression_); \ - if (result.has_error()) { \ - if (result != libp2p::outcome::failure(_error_)) { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << result.error().message() << "'\n" \ - << "Expected: Error '" << make_error_code(_error_).message() \ - << "'"; \ - } \ - } else { \ - GTEST_FATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Error '" << make_error_code(_error_).message() \ - << "'"; \ - } \ - } - -#define EXPECT_OUTCOME_SUCCESS(_result_, _expression_) \ - [[maybe_unused]] auto &&_result_ = (_expression_); \ - if (_result_.has_error()) { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << _result_.error().message() << "'\n" \ - << "Expected: Success"; \ - } - -#define EXPECT_OUTCOME_SOME_ERROR(_result_, _expression_) \ - [[maybe_unused]] auto &&_result_ = (_expression_); \ - if (not _result_.has_error()) { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Some error"; \ - } - -#define EXPECT_OUTCOME_ERROR(_result_, _expression_, _error_) \ - [[maybe_unused]] auto &&_result_ = (_expression_); \ - if (_result_.has_error()) { \ - if (_result_ != libp2p::outcome::failure(_error_)) { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Error '" << _result_.error().message() << "'\n" \ - << "Expected: Error '" << make_error_code(_error_).message() "'"; \ - } \ - } else { \ - GTEST_NONFATAL_FAILURE_("Outcome of: " #_expression_) \ - << " Actual: Success\n" \ - << "Expected: Error '" << make_error_code(_error_).message() << "'"; \ - } + EXPECT_OUTCOME_TRUE_NAME(BOOST_OUTCOME_TRY_UNIQUE_NAME, val, expr) + +#define _EXPECT_EC(tmp, expr, expected) \ + auto &&tmp = expr; \ + EXPECT_TRUE(tmp.has_error()); \ + EXPECT_EQ(tmp.error(), make_error_code(expected)); +#define EXPECT_EC(expr, expected) \ + _EXPECT_EC(BOOST_OUTCOME_TRY_UNIQUE_NAME, expr, expected) diff --git a/test/testutil/printers.hpp b/test/testutil/printers.hpp deleted file mode 100644 index d05877d53..000000000 --- a/test/testutil/printers.hpp +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright Quadrivium LLC - * All Rights Reserved - * SPDX-License-Identifier: Apache-2.0 - */ - -#pragma once - -#include -#include - -#include - -namespace std { - - void PrintTo(const std::vector &v, std::ostream *os) { - *os << libp2p::common::hex_upper(v); - } - -} // namespace std