diff --git a/.github/workflows/ci-expanded.yml b/.github/workflows/ci-expanded.yml index a671c3747..1ed30dd89 100644 --- a/.github/workflows/ci-expanded.yml +++ b/.github/workflows/ci-expanded.yml @@ -229,7 +229,7 @@ jobs: coverage: "" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "dynamic" cc: "gcc-15" @@ -239,7 +239,7 @@ jobs: package: "g++-15 gcc-15" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "static" cc: "gcc-15" @@ -249,7 +249,7 @@ jobs: package: "g++-15 gcc-15" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "dynamic" cc: "gcc-15" @@ -259,7 +259,7 @@ jobs: package: "g++-15 gcc-15" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "static" cc: "gcc-15" @@ -269,7 +269,7 @@ jobs: package: "g++-15 gcc-15" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "dynamic" cc: "gcc-16" @@ -279,7 +279,7 @@ jobs: package: "g++-16 gcc-16" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "static" cc: "gcc-16" @@ -289,7 +289,7 @@ jobs: package: "g++-16 gcc-16" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "dynamic" cc: "gcc-16" @@ -299,7 +299,7 @@ jobs: package: "g++-16 gcc-16" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "static" cc: "gcc-16" @@ -361,7 +361,7 @@ jobs: package: "gcc-14 g++-14" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "static" cc: "gcc-15" @@ -481,15 +481,6 @@ jobs: shell: bash run: | sudo apt-get update - if [[ "${{ matrix.package }}" == *"g++-15"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15"* ]] || - [[ "${{ matrix.package }}" == *"g++-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15-multilib"* ]] || - [[ "${{ matrix.package }}" == *"g++-15-multilib"* ]]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update - fi sudo apt-get install git build-essential autoconf automake libtool pkg-config ${{ matrix.package || '' }} if [[ "${{ matrix.coverage }}" == "lcov" ]]; then sudo apt-get install lcov @@ -1006,7 +997,7 @@ jobs: coverage: "" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "dynamic" cc: "gcc-15" @@ -1016,7 +1007,7 @@ jobs: package: "g++-15 gcc-15" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "static" cc: "gcc-15" @@ -1026,7 +1017,7 @@ jobs: package: "g++-15 gcc-15" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "dynamic" cc: "gcc-15" @@ -1036,7 +1027,7 @@ jobs: package: "g++-15 gcc-15" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "static" cc: "gcc-15" @@ -1046,7 +1037,7 @@ jobs: package: "g++-15 gcc-15" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "dynamic" cc: "gcc-16" @@ -1056,7 +1047,7 @@ jobs: package: "g++-16 gcc-16" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "static" cc: "gcc-16" @@ -1066,7 +1057,7 @@ jobs: package: "g++-16 gcc-16" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "dynamic" cc: "gcc-16" @@ -1076,7 +1067,7 @@ jobs: package: "g++-16 gcc-16" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "static" cc: "gcc-16" @@ -1170,15 +1161,6 @@ jobs: shell: bash run: | sudo apt-get update - if [[ "${{ matrix.package }}" == *"g++-15"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15"* ]] || - [[ "${{ matrix.package }}" == *"g++-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15-multilib"* ]] || - [[ "${{ matrix.package }}" == *"g++-15-multilib"* ]]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update - fi sudo apt-get install git build-essential autoconf automake libtool pkg-config ${{ matrix.package || '' }} if [[ "${{ matrix.coverage }}" == "lcov" ]]; then sudo apt-get install lcov @@ -1493,7 +1475,7 @@ jobs: coverage: "" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-debug-shared" cc: "gcc-15" cxx: "g++-15" @@ -1502,7 +1484,7 @@ jobs: package: "g++-15 gcc-15" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-debug-static" cc: "gcc-15" cxx: "g++-15" @@ -1511,7 +1493,7 @@ jobs: package: "g++-15 gcc-15" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-release-shared" cc: "gcc-15" cxx: "g++-15" @@ -1520,7 +1502,7 @@ jobs: package: "g++-15 gcc-15" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-release-static" cc: "gcc-15" cxx: "g++-15" @@ -1529,7 +1511,7 @@ jobs: package: "g++-15 gcc-15" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-debug-shared" cc: "gcc-16" cxx: "g++-16" @@ -1538,7 +1520,7 @@ jobs: package: "g++-16 gcc-16" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-debug-static" cc: "gcc-16" cxx: "g++-16" @@ -1547,7 +1529,7 @@ jobs: package: "g++-16 gcc-16" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-release-shared" cc: "gcc-16" cxx: "g++-16" @@ -1556,7 +1538,7 @@ jobs: package: "g++-16 gcc-16" options: "--build-skip-tests" - - image: ubuntu-24.04 + - image: ubuntu-26.04 preset: "nix-gnu-release-static" cc: "gcc-16" cxx: "g++-16" @@ -1616,15 +1598,6 @@ jobs: shell: bash run: | sudo apt-get update - if [[ "${{ matrix.package }}" == *"g++-15"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15"* ]] || - [[ "${{ matrix.package }}" == *"g++-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15-multilib"* ]] || - [[ "${{ matrix.package }}" == *"g++-15-multilib"* ]]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update - fi sudo apt-get install git build-essential autoconf automake libtool pkg-config ${{ matrix.package || '' }} if [[ "${{ matrix.coverage }}" == "lcov" ]]; then sudo apt-get install lcov diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49c04027b..7b79e113f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -145,7 +145,7 @@ jobs: package: "gcc-14 g++-14" options: "--enable-isystem" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "release" link: "static" cc: "gcc-15" @@ -229,15 +229,6 @@ jobs: shell: bash run: | sudo apt-get update - if [[ "${{ matrix.package }}" == *"g++-15"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15"* ]] || - [[ "${{ matrix.package }}" == *"g++-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15-multilib"* ]] || - [[ "${{ matrix.package }}" == *"g++-15-multilib"* ]]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update - fi sudo apt-get install git build-essential autoconf automake libtool pkg-config ${{ matrix.package || '' }} if [[ "${{ matrix.coverage }}" == "lcov" ]]; then sudo apt-get install lcov @@ -394,7 +385,7 @@ jobs: coverage: "" options: "" - - image: ubuntu-24.04 + - image: ubuntu-26.04 config: "debug" link: "dynamic" cc: "gcc-16" @@ -455,15 +446,6 @@ jobs: shell: bash run: | sudo apt-get update - if [[ "${{ matrix.package }}" == *"g++-15"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15"* ]] || - [[ "${{ matrix.package }}" == *"g++-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15-multilib"* ]] || - [[ "${{ matrix.package }}" == *"g++-15-multilib"* ]]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update - fi sudo apt-get install git build-essential autoconf automake libtool pkg-config ${{ matrix.package || '' }} if [[ "${{ matrix.coverage }}" == "lcov" ]]; then sudo apt-get install lcov @@ -673,15 +655,6 @@ jobs: shell: bash run: | sudo apt-get update - if [[ "${{ matrix.package }}" == *"g++-15"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15"* ]] || - [[ "${{ matrix.package }}" == *"g++-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-16"* ]] || - [[ "${{ matrix.package }}" == *"gcc-15-multilib"* ]] || - [[ "${{ matrix.package }}" == *"g++-15-multilib"* ]]; then - sudo add-apt-repository ppa:ubuntu-toolchain-r/test -y - sudo apt-get update - fi sudo apt-get install git build-essential autoconf automake libtool pkg-config ${{ matrix.package || '' }} if [[ "${{ matrix.coverage }}" == "lcov" ]]; then sudo apt-get install lcov diff --git a/.gitignore b/.gitignore index 461538162..e50dc73b0 100644 --- a/.gitignore +++ b/.gitignore @@ -79,7 +79,8 @@ obj # GitNexus tool. .gitnexus -AI agent tooling + +# AI agent tooling .claude AGENTS.md CLAUDE.md diff --git a/builds/gnu/Makefile.am b/builds/gnu/Makefile.am index 3ad07594f..7f0386b57 100644 --- a/builds/gnu/Makefile.am +++ b/builds/gnu/Makefile.am @@ -190,6 +190,7 @@ src_libbitcoin_network_la_SOURCES = \ ${srcdir}/../../src/noise/certificate.cpp \ ${srcdir}/../../src/noise/cipher.cpp \ ${srcdir}/../../src/noise/context.cpp \ + ${srcdir}/../../src/noise/stream.cpp \ ${srcdir}/../../src/p2ps/cipher.cpp \ ${srcdir}/../../src/p2ps/stream.cpp \ ${srcdir}/../../src/protocols/protocol.cpp \ @@ -385,6 +386,12 @@ include_bitcoin_network_impl_messages_rpc_HEADERS = \ ${srcdir}/../../include/bitcoin/network/impl/messages/rpc/broadcaster.ipp \ ${srcdir}/../../include/bitcoin/network/impl/messages/rpc/dispatcher.ipp +include_bitcoin_network_impl_noisedir = \ + ${includedir}/bitcoin/network/impl/noise + +include_bitcoin_network_impl_noise_HEADERS = \ + ${srcdir}/../../include/bitcoin/network/impl/noise/stream.ipp + include_bitcoin_network_impl_protocolsdir = \ ${includedir}/bitcoin/network/impl/protocols @@ -632,7 +639,8 @@ include_bitcoin_network_noise_HEADERS = \ ${srcdir}/../../include/bitcoin/network/noise/certificate.hpp \ ${srcdir}/../../include/bitcoin/network/noise/cipher.hpp \ ${srcdir}/../../include/bitcoin/network/noise/context.hpp \ - ${srcdir}/../../include/bitcoin/network/noise/noise.hpp + ${srcdir}/../../include/bitcoin/network/noise/noise.hpp \ + ${srcdir}/../../include/bitcoin/network/noise/stream.hpp include_bitcoin_network_p2psdir = \ ${includedir}/bitcoin/network/p2ps @@ -899,6 +907,7 @@ test_libbitcoin_network_test_SOURCES = \ ${srcdir}/../../test/noise/certificate.cpp \ ${srcdir}/../../test/noise/cipher.cpp \ ${srcdir}/../../test/noise/context.cpp \ + ${srcdir}/../../test/noise/stream.cpp \ ${srcdir}/../../test/noise/vectors.cpp \ ${srcdir}/../../test/p2ps/cipher.cpp \ ${srcdir}/../../test/p2ps/stream.cpp \ diff --git a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj index 9562b2666..0a82369be 100644 --- a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj +++ b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj @@ -281,6 +281,9 @@ $(IntDir)test_noise_context.obj + + $(IntDir)test_noise_stream.obj + $(IntDir)test_p2ps_cipher.obj diff --git a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters index 6b8603257..1cb3dc515 100644 --- a/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters +++ b/builds/msvc/vs2026/libbitcoin-network-test/libbitcoin-network-test.vcxproj.filters @@ -540,6 +540,9 @@ src\noise + + src\noise + src\noise diff --git a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj index f8cc1ed64..06e77195b 100644 --- a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj +++ b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj @@ -280,6 +280,9 @@ $(IntDir)src_noise_context.obj + + $(IntDir)src_noise_stream.obj + $(IntDir)src_p2ps_cipher.obj @@ -534,6 +537,7 @@ + @@ -617,6 +621,7 @@ + diff --git a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters index e86460b23..da4a7b01b 100644 --- a/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters +++ b/builds/msvc/vs2026/libbitcoin-network/libbitcoin-network.vcxproj.filters @@ -55,156 +55,159 @@ {564EB540-D6B6-425C-0000-00000000000F} - + {564EB540-D6B6-425C-0000-000000000001} - + {564EB540-D6B6-425C-0000-000000000002} - + {564EB540-D6B6-425C-0000-000000000003} - + {564EB540-D6B6-425C-0000-000000000004} - + {564EB540-D6B6-425C-0000-000000000005} - + {564EB540-D6B6-425C-0000-000000000006} - + {564EB540-D6B6-425C-0000-000000000007} - + {564EB540-D6B6-425C-0000-000000000008} - + {564EB540-D6B6-425C-0000-000000000009} - + {564EB540-D6B6-425C-0000-000000000010} - + {564EB540-D6B6-425C-0000-0000000000A1} - + {564EB540-D6B6-425C-0000-0000000000B1} - + {564EB540-D6B6-425C-0000-0000000000C1} - + {564EB540-D6B6-425C-0000-0000000000D1} - + {564EB540-D6B6-425C-0000-0000000000E1} - + {564EB540-D6B6-425C-0000-0000000000F1} - + {564EB540-D6B6-425C-0000-000000000002} - + {564EB540-D6B6-425C-0000-000000000003} - + {564EB540-D6B6-425C-0000-000000000004} - + {564EB540-D6B6-425C-0000-000000000005} - + {564EB540-D6B6-425C-0000-000000000006} - + {564EB540-D6B6-425C-0000-000000000007} - + {564EB540-D6B6-425C-0000-000000000008} - + {564EB540-D6B6-425C-0000-000000000009} - + {564EB540-D6B6-425C-0000-000000000010} - + {564EB540-D6B6-425C-0000-000000000011} - + {564EB540-D6B6-425C-0000-0000000000A2} - + {564EB540-D6B6-425C-0000-0000000000B2} - + {564EB540-D6B6-425C-0000-0000000000C2} - + {564EB540-D6B6-425C-0000-0000000000D2} - + {564EB540-D6B6-425C-0000-0000000000E2} - + {564EB540-D6B6-425C-0000-0000000000F2} - + {564EB540-D6B6-425C-0000-000000000003} - + {564EB540-D6B6-425C-0000-000000000004} - + {564EB540-D6B6-425C-0000-000000000005} - + {564EB540-D6B6-425C-0000-000000000006} - + {564EB540-D6B6-425C-0000-000000000007} - + {564EB540-D6B6-425C-0000-000000000008} - + {564EB540-D6B6-425C-0000-000000000009} - + {564EB540-D6B6-425C-0000-000000000010} - + {564EB540-D6B6-425C-0000-000000000011} - + {564EB540-D6B6-425C-0000-000000000012} - + {564EB540-D6B6-425C-0000-0000000000A3} - + {564EB540-D6B6-425C-0000-0000000000B3} - + {564EB540-D6B6-425C-0000-0000000000C3} - + {564EB540-D6B6-425C-0000-0000000000D3} - + {564EB540-D6B6-425C-0000-0000000000E3} - + {564EB540-D6B6-425C-0000-0000000000F3} - + {564EB540-D6B6-425C-0000-000000000004} - + {564EB540-D6B6-425C-0000-000000000005} + + {564EB540-D6B6-425C-0000-000000000006} + @@ -630,6 +633,9 @@ src\noise + + src\noise + src\p2ps @@ -1340,6 +1346,9 @@ include\bitcoin\network\noise + + include\bitcoin\network\noise + include\bitcoin\network\p2ps @@ -1593,6 +1602,9 @@ include\bitcoin\network\impl\messages\rpc + + include\bitcoin\network\impl\noise + include\bitcoin\network\impl\protocols diff --git a/include/bitcoin/network.hpp b/include/bitcoin/network.hpp index 4a967dfe6..8932a37f1 100644 --- a/include/bitcoin/network.hpp +++ b/include/bitcoin/network.hpp @@ -208,6 +208,7 @@ #include #include #include +#include #include #include #include diff --git a/include/bitcoin/network/channels/channel_sv2.hpp b/include/bitcoin/network/channels/channel_sv2.hpp index 40b3bed4a..719d31567 100644 --- a/include/bitcoin/network/channels/channel_sv2.hpp +++ b/include/bitcoin/network/channels/channel_sv2.hpp @@ -30,8 +30,8 @@ namespace libbitcoin { namespace network { -/// Full duplex stratum v2 channel, served over ws/s (by upgrade), one frame -/// to each binary message. +/// Full duplex stratum v2 channel, served over ws (by upgrade), one frame to +/// each binary message, or over tcp (by detection), frames streamed. class BCT_API channel_sv2 : public channel_http { diff --git a/include/bitcoin/network/impl/noise/stream.ipp b/include/bitcoin/network/impl/noise/stream.ipp new file mode 100644 index 000000000..a777bda0e --- /dev/null +++ b/include/bitcoin/network/impl/noise/stream.ipp @@ -0,0 +1,116 @@ +/** + * Copyright (c) 2011-2026 libbitcoin developers + * + * This file is part of libbitcoin. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#ifndef LIBBITCOIN_NETWORK_IMPL_NOISE_STREAM_IPP +#define LIBBITCOIN_NETWORK_IMPL_NOISE_STREAM_IPP + +#include + +namespace libbitcoin { +namespace network { +namespace noise { + +BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT) + +template +void stream::async_read_some(const Buffers& buffers, Handler&& handler) NOEXCEPT +{ + const auto buffer = first(buffers); + const auto data = system::pointer_cast(buffer.data()); + do_read_some({ data, buffer.size() }, + erase(std::forward(handler))); +} + +template +void stream::async_write_some(const Buffers& buffers, + Handler&& handler) NOEXCEPT +{ + do_write_some(flatten(buffers), erase(std::forward(handler))); +} + +template +size_t stream::write_some(const Buffers& buffers, code& ec) NOEXCEPT +{ + return do_write(flatten(buffers), ec); +} + +// private +template +Buffer stream::first(const Buffers& buffers) NOEXCEPT +{ + const auto end = io::buffer_sequence_end(buffers); + for (auto it = io::buffer_sequence_begin(buffers); it != end; ++it) + { + const Buffer buffer{ *it }; + if (is_nonzero(buffer.size())) + return buffer; + } + + return {}; +} + +// private +// The written bytes, gathered only when they span buffers. +template +const_byte_span stream::flatten(const Buffers& buffers) NOEXCEPT +{ + const auto end = io::buffer_sequence_end(buffers); + auto it = io::buffer_sequence_begin(buffers); + while (it != end && is_zero(io::const_buffer{ *it }.size())) + ++it; + + if (it == end) + return {}; + + const io::const_buffer head{ *it }; + const auto data = system::pointer_cast(head.data()); + if (std::next(it) == end) + return { data, head.size() }; + + plaintext_.clear(); + for (; it != end; ++it) + { + const io::const_buffer buffer{ *it }; + const auto bytes = system::pointer_cast(buffer.data()); + plaintext_.insert(plaintext_.cend(), bytes, + std::next(bytes, buffer.size())); + } + + return plaintext_; +} + +// private +template +stream::io_handler stream::erase(Handler&& handler) NOEXCEPT +{ + const auto shared = system::emplace_shared>( + std::forward(handler)); + + return [shared](const code& ec, size_t size) NOEXCEPT + { + std::move(*shared)(ec, size); + }; +} + +BC_POP_WARNING() + +} // namespace noise +} // namespace network +} // namespace libbitcoin + +#endif diff --git a/include/bitcoin/network/impl/tls/stream.ipp b/include/bitcoin/network/impl/tls/stream.ipp index 58a36afd8..b22f7d20c 100644 --- a/include/bitcoin/network/impl/tls/stream.ipp +++ b/include/bitcoin/network/impl/tls/stream.ipp @@ -55,8 +55,7 @@ template Buffer stream::first(const Buffers& buffers) NOEXCEPT { const auto end = io::buffer_sequence_end(buffers); - for (auto it = io::buffer_sequence_begin(buffers); it != end; - ++it) + for (auto it = io::buffer_sequence_begin(buffers); it != end; ++it) { const Buffer buffer{ *it }; if (is_nonzero(buffer.size())) @@ -88,8 +87,8 @@ const_byte_span stream::flatten(const Buffers& buffers) NOEXCEPT for (; it != end && plaintext_.size() < maximum_plaintext; ++it) { const io::const_buffer buffer{ *it }; - const auto size = std::min(buffer.size(), - maximum_plaintext - plaintext_.size()); + const auto span = maximum_plaintext - plaintext_.size(); + const auto size = std::min(buffer.size(), span); const auto bytes = system::pointer_cast(buffer.data()); plaintext_.insert(plaintext_.cend(), bytes, std::next(bytes, size)); } diff --git a/include/bitcoin/network/net/proxy.hpp b/include/bitcoin/network/net/proxy.hpp index b051a8215..d40e693fd 100644 --- a/include/bitcoin/network/net/proxy.hpp +++ b/include/bitcoin/network/net/proxy.hpp @@ -105,6 +105,9 @@ class BCT_API proxy /// Connection was upgraded to encrypted transport (bip324). bool encrypted() const NOEXCEPT; + /// Connection was upgraded to noise transport (sv2). + bool noised() const NOEXCEPT; + /// The socket was upgraded to a websocket. bool websocket() const NOEXCEPT; diff --git a/include/bitcoin/network/net/socket.hpp b/include/bitcoin/network/net/socket.hpp index 7d8fdbdca..9e0a2f224 100644 --- a/include/bitcoin/network/net/socket.hpp +++ b/include/bitcoin/network/net/socket.hpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -226,8 +227,9 @@ class BCT_API socket using http_parser_ptr = std::shared_ptr; /// Latch http vs. tcp from buffered bytes, reading only as required to - /// decide, handler posted to socket strand. No message is consumed. - virtual void detect(http::flat_buffer& buffer, + /// decide, handler posted to socket strand. No message is consumed. Tcp + /// opens with json, or with any byte that cannot open a request if binary. + virtual void detect(http::flat_buffer& buffer, bool binary, count_handler&& handler) NOEXCEPT; /// Read http request from the socket, handler posted to socket strand. @@ -289,6 +291,9 @@ class BCT_API socket /// The socket was upgraded to native ZMTP (in its role). virtual bool zeromq() const NOEXCEPT; + /// The socket was upgraded to noise (sv2). + virtual bool noised() const NOEXCEPT; + /// The socket was upgraded to a websocket. virtual bool websocket() const NOEXCEPT; @@ -320,9 +325,20 @@ class BCT_API socket virtual void set_address(const config::address& address) NOEXCEPT; protected: - using tcp_t = std::variant, ref>; - using socket_t = std::variant; + using tcp_t = std::variant + < + ref, + ref, + ref + >; + using socket_t = std::variant + < + io::socket, + tls::stream, + p2ps::stream, + zmtp::stream, + noise::stream + >; /// Construct. /// ----------------------------------------------------------------------- @@ -462,7 +478,7 @@ class BCT_API socket system::data_chunk payload{}; io::const_buffer data{}; count_handler handler{}; - std::array buffers{}; + std::array buffers{}; bool control{}; bool finish{}; }; @@ -550,7 +566,7 @@ class BCT_API socket count_handler&& handler) NOEXCEPT; // detect (first read) - void do_detect(const ref& buffer, + void do_detect(const ref& buffer, bool binary, const count_handler& handler) NOEXCEPT; // http @@ -626,6 +642,8 @@ class BCT_API socket const result_handler& handler) NOEXCEPT; void handle_detection(const code& ec, const result_handler& handler) NOEXCEPT; + void handle_secure_detection(const code& ec, + const result_handler& handler) NOEXCEPT; // read/write (tcp/ws) void handle_async(const code& ec, size_t size, @@ -655,7 +673,7 @@ class BCT_API socket // detect void handle_detect(const code& ec, size_t size, - const ref& buffer, + const ref& buffer, bool binary, const count_handler& handler) NOEXCEPT; // http/ws (native/rpc) diff --git a/include/bitcoin/network/noise/noise.hpp b/include/bitcoin/network/noise/noise.hpp index 32113f88d..38b531075 100644 --- a/include/bitcoin/network/noise/noise.hpp +++ b/include/bitcoin/network/noise/noise.hpp @@ -22,5 +22,6 @@ #include #include #include +#include #endif diff --git a/include/bitcoin/network/noise/stream.hpp b/include/bitcoin/network/noise/stream.hpp new file mode 100644 index 000000000..f82ed678c --- /dev/null +++ b/include/bitcoin/network/noise/stream.hpp @@ -0,0 +1,147 @@ +/** + * Copyright (c) 2011-2026 libbitcoin developers + * + * This file is part of libbitcoin. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#ifndef LIBBITCOIN_NETWORK_NOISE_STREAM_HPP +#define LIBBITCOIN_NETWORK_NOISE_STREAM_HPP + +#include +#include +#include +#include +#include +#include + +namespace libbitcoin { +namespace network { +namespace noise { + +/// Stratum v2 Noise responder or initiator connection over tcp socket. +/// Application bytes are sv2 frames: each whole written frame is sealed as one +/// transport frame, and each received transport frame is opened to the bytes +/// of its sv2 frame. Calls sequenced on socket executor; read and write chains +/// may overlap each other but not themselves. +class BCT_API stream +{ +public: + DELETE_COPY_MOVE(stream); + + typedef std::function result_handler; + typedef std::function io_handler; + using executor_type = io::socket::executor_type; + + /// Own connected tcp socket as responder, context outlives stream. + stream(io::socket&& socket, const context& context) NOEXCEPT; + + /// Own connected tcp socket as initiator. + stream(io::socket&& socket) NOEXCEPT; + + /// Stream executor and socket. + executor_type get_executor() NOEXCEPT; + io::socket& next_layer() NOEXCEPT; + const io::socket& next_layer() const NOEXCEPT; + + /// Responder static key and certificate (initiator, after handshake). + const cipher::key& static_key() const NOEXCEPT; + const cipher::certificate& certificate() const NOEXCEPT; + + /// Perform handshake (initiator sends act1, responder answers act2). + void async_handshake(result_handler&& handler) NOEXCEPT; + + /// Perform handshake as responder, given act1 prefix bytes consumed by + /// socket (detection). + void async_handshake(const const_byte_span& detected, + result_handler&& handler) NOEXCEPT; + + /// Read received application bytes. + template + void async_read_some(const Buffers& buffers, Handler&& handler) NOEXCEPT; + + /// Write application bytes. + template + void async_write_some(const Buffers& buffers, Handler&& handler) NOEXCEPT; + + /// Write application bytes (blocking), no asynchronous write in progress. + template + size_t write_some(const Buffers& buffers, code& ec) NOEXCEPT; + + /// Complete once written frames are sent (Noise has no close message). + void async_shutdown(result_handler&& handler) NOEXCEPT; + +private: + template + static Buffer first(const Buffers& buffers) NOEXCEPT; + template + const_byte_span flatten(const Buffers& buffers) NOEXCEPT; + template + static io_handler erase(Handler&& handler) NOEXCEPT; + + // handshake + void do_respond(size_t detected, const result_handler& handler) NOEXCEPT; + void handle_act1(const code& ec, + const result_handler& handler) NOEXCEPT; + void do_initiate(const result_handler& handler) NOEXCEPT; + void handle_act1_sent(const code& ec, + const result_handler& handler) NOEXCEPT; + void handle_act2(const code& ec, + const result_handler& handler) NOEXCEPT; + + // read + void do_read_some(const byte_span& out, + const io_handler& handler) NOEXCEPT; + size_t take(const byte_span& out) NOEXCEPT; + void handle_heading(const code& ec, const byte_span& out, + const io_handler& handler) NOEXCEPT; + void handle_payload(const code& ec, size_t length, const byte_span& out, + const io_handler& handler) NOEXCEPT; + + // write + bool seal(const const_byte_span& data) NOEXCEPT; + void do_write_some(const const_byte_span& data, + const io_handler& handler) NOEXCEPT; + size_t do_write(const const_byte_span& data, code& ec) NOEXCEPT; + void flush(const result_handler& handler) NOEXCEPT; + void write_next() NOEXCEPT; + void handle_write(const code& ec, + const std::vector& handlers) NOEXCEPT; + + // These are protected by stream (executor) sequencing. + io::socket socket_; + const context* context_; + std::optional cipher_{}; + cipher::act1 act1_{}; + cipher::act2 act2_{}; + cipher::key static_key_{}; + cipher::certificate certificate_{}; + system::data_chunk input_{}; + system::data_chunk received_{}; + size_t offset_{}; + system::data_chunk plaintext_{}; + system::data_chunk pending_{}; + system::data_chunk output_{}; + system::data_chunk sending_{}; + std::vector waiting_{}; + bool writing_{}; +}; + +} // namespace noise +} // namespace network +} // namespace libbitcoin + +#include + +#endif diff --git a/include/bitcoin/network/settings.hpp b/include/bitcoin/network/settings.hpp index 03c535b11..1b4d04dc4 100644 --- a/include/bitcoin/network/settings.hpp +++ b/include/bitcoin/network/settings.hpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -42,13 +43,22 @@ constexpr auto max_payload = system::possible_narrow_cast( /// Common network configuration settings, properties not thread safe. struct BCT_API settings { + /// Tls and noise contexts, either applied by detection of accepted socket. + struct tls_noise + { + ref tls_context; + ref noise_context; + }; + /// The transport of a socket is selected by its context (none is clear). using transport = std::variant < std::monostate, ref, ref, - ref + ref, + ref, + tls_noise >; struct BCT_API socks5 @@ -193,6 +203,9 @@ struct BCT_API settings /// Thread safe socket tls context (const after initialize). std::unique_ptr context{}; + /// The secured bindings are served by tls (default true). + virtual bool tls_secured() const NOEXCEPT; + /// False if safes, certificate_path, or key_path is empty. bool secure() const NOEXCEPT override; diff --git a/include/bitcoin/network/tls/stream.hpp b/include/bitcoin/network/tls/stream.hpp index 6cc1cb464..a47805597 100644 --- a/include/bitcoin/network/tls/stream.hpp +++ b/include/bitcoin/network/tls/stream.hpp @@ -45,6 +45,12 @@ class BCT_API stream typedef std::function io_handler; using executor_type = io::socket::executor_type; + /// The size of the client hello detection prefix. + static constexpr size_t detection_size = 11; + + /// The prefix opens a client hello (record and handshake headers). + static bool detected_hello(const std::span& prefix) NOEXCEPT; + /// Own connected tcp socket as server or client, context outlives stream. stream(io::socket&& socket, const context& context, bool as_server) NOEXCEPT; @@ -60,6 +66,11 @@ class BCT_API stream /// Perform handshake (client hello sent first). void async_handshake(result_handler&& handler) NOEXCEPT; + /// Perform handshake as server, given client hello prefix bytes consumed + /// by socket (detection). + void async_handshake(const const_byte_span& detected, + result_handler&& handler) NOEXCEPT; + /// Read received application bytes. template void async_read_some(const Buffers& buffers, Handler&& handler) NOEXCEPT; diff --git a/src/channels/channel_http.cpp b/src/channels/channel_http.cpp index b63fea48a..f6d2929fb 100644 --- a/src/channels/channel_http.cpp +++ b/src/channels/channel_http.cpp @@ -704,7 +704,8 @@ std::string channel_http::log_message(const request& request, if (downgraded()) { - const std::string scheme = secure() ? "tls" : "tcp"; + const std::string scheme = secure() ? "tls" : + (noised() ? "noise" : "tcp"); const std::string size = serialize(bytes); return scheme + " (" + size + ") [" + endpoint().to_string() + "]"; } diff --git a/src/channels/channel_sv2.cpp b/src/channels/channel_sv2.cpp index c22e6425c..bd6966621 100644 --- a/src/channels/channel_sv2.cpp +++ b/src/channels/channel_sv2.cpp @@ -85,7 +85,8 @@ void channel_sv2::handle_receive(const code& ec, size_t bytes, // The frame carries parse fault detail (the read code is generic). const auto& body = request->body(); - if (ec && websocket() && !stopped() && body.contains()) + if (ec && (websocket() || downgraded()) && !stopped() && + body.contains()) { const auto& fault = body.get().fault; LOGF("Stratum read failure [" << endpoint() << "] " @@ -102,8 +103,8 @@ void channel_sv2::dispatch(const http::request_ptr& request) NOEXCEPT { BC_ASSERT(stranded()); - // The service is websocket only, a request without upgrade is refused. - if (!websocket()) + // The service is websocket or tcp, a request without upgrade is refused. + if (!websocket() && !downgraded()) { http::response out{ http::status::upgrade_required, request->version() }; out.keep_alive(false); @@ -114,6 +115,13 @@ void channel_sv2::dispatch(const http::request_ptr& request) NOEXCEPT return; } + // Tcp carries no credential, only the websocket upgrade authorizes. + if (downgraded() && !authorized()) + { + stop(error::unauthorized); + return; + } + const auto& body = request->body(); if (!body.contains()) { diff --git a/src/net/proxy.cpp b/src/net/proxy.cpp index 8a1fe67fd..93ef9d0de 100644 --- a/src/net/proxy.cpp +++ b/src/net/proxy.cpp @@ -281,6 +281,11 @@ bool proxy::encrypted() const NOEXCEPT return socket_->encrypted(); } +bool proxy::noised() const NOEXCEPT +{ + return socket_->noised(); +} + bool proxy::websocket() const NOEXCEPT { return socket_->websocket(); diff --git a/src/net/proxy_actions.cpp b/src/net/proxy_actions.cpp index 03485cae8..b5a36eba5 100644 --- a/src/net/proxy_actions.cpp +++ b/src/net/proxy_actions.cpp @@ -524,11 +524,13 @@ void proxy::read(http::flat_buffer& buffer, http::request& request, return; } - // Preselected body is read/write control, so json-rpc body implies + // Preselected body is read/write control, so json-rpc or sv2 body implies // detection, performed before first message is read. - if (!socket_->detected() && request.body().contains()) + const auto& body = request.body(); + const auto binary = body.contains(); + if (!socket_->detected() && (binary || body.contains())) { - socket_->detect(buffer, + socket_->detect(buffer, binary, std::bind(&proxy::handle_detect, shared_from_this(), _1, _2, std::ref(request), std::ref(buffer), std::move(handler))); @@ -579,6 +581,15 @@ void proxy::do_downgrade_read(const ref& request, // A downgraded message carries no request line, so tag it for dispatch. auto& in = request.get(); in.method(http::verb::stream); + + // Sv2 frames are self-delimiting, so they stream into the sv2 body. + if (in.body().contains()) + { + in.body().get().exact = false; + socket_->body_read(buffer.get(), in, counted(count_handler{ handler })); + return; + } + if (!in.body().contains()) in.body() = rpc::request{}; @@ -833,8 +844,9 @@ void proxy::write(http::response&& response, count_handler&& handler, bool bounded) NOEXCEPT { // Downgrade is json-rpc transport, so it writes as one (batch stamping for - // response, deferral while open for notification). - if (socket_->downgraded()) + // response, deferral while open for notification). Sv2 frames are queued + // as http, which writes them without headers. + if (socket_->downgraded() && !response.body().contains()) { auto& body = response.body(); if (body.contains()) diff --git a/src/net/socket.cpp b/src/net/socket.cpp index 9a5b51844..8199e3b99 100644 --- a/src/net/socket.cpp +++ b/src/net/socket.cpp @@ -265,6 +265,12 @@ bool socket::zeromq() const NOEXCEPT return std::holds_alternative(socket_); } +bool socket::noised() const NOEXCEPT +{ + BC_ASSERT(stranded()); + return std::holds_alternative(socket_); +} + // protected bool socket::is_base() const NOEXCEPT { @@ -297,6 +303,10 @@ socket::tcp_t socket::get_tcp() NOEXCEPT [](zmtp::stream&) NOEXCEPT -> socket::tcp_t { std::terminate(); + }, + [](noise::stream& value) NOEXCEPT -> socket::tcp_t + { + return std::ref(value); } }, socket_); } @@ -318,6 +328,10 @@ io::socket& socket::get_base() NOEXCEPT return value.next_layer(); }, [](zmtp::stream& value) NOEXCEPT -> io::socket& + { + return value.next_layer(); + }, + [](noise::stream& value) NOEXCEPT -> io::socket& { return value.next_layer(); } @@ -344,6 +358,10 @@ tls::stream& socket::get_tls() NOEXCEPT std::terminate(); }, [](zmtp::stream&) NOEXCEPT -> tls::stream& + { + std::terminate(); + }, + [](noise::stream&) NOEXCEPT -> tls::stream& { std::terminate(); } @@ -370,6 +388,10 @@ p2ps::stream& socket::get_p2ps() NOEXCEPT return value; }, [](zmtp::stream&) NOEXCEPT -> p2ps::stream& + { + std::terminate(); + }, + [](noise::stream&) NOEXCEPT -> p2ps::stream& { std::terminate(); } @@ -398,6 +420,10 @@ zmtp::stream& socket::get_zmtp() NOEXCEPT [](zmtp::stream& value) NOEXCEPT -> zmtp::stream& { return value; + }, + [](noise::stream&) NOEXCEPT -> zmtp::stream& + { + std::terminate(); } }, socket_); } @@ -644,9 +670,9 @@ void socket::async_write_http(http::response&& response, BC_ASSERT(stranded()); assign_buffer(response.body()); - if (websocket()) + if (websocket() || downgraded()) { - // Body writer processes websocket write just like + // Body writer processes websocket or tcp write just like // http write but without headers. Expected body type // (serializer) is determined by caller-assigned body. body_write(std::move(response), move_copy(handler)); diff --git a/src/net/socket_connect.cpp b/src/net/socket_connect.cpp index 6d1a8e5bd..d734f9e8d 100644 --- a/src/net/socket_connect.cpp +++ b/src/net/socket_connect.cpp @@ -334,6 +334,40 @@ void socket::do_upgrade(const result_handler& handler) NOEXCEPT return; } + if (std::holds_alternative(context_)) + { + // The accepted client is detected as tls or noise before upgrade. + if (!inbound_) + { + handler(error::operation_failed); + return; + } + + io::async_read(get_base(), + detection_.prepare(tls::stream::detection_size), + std::bind(&socket::handle_secure_detection, + shared_from_this(), _1, handler)); + return; + } + + if (std::holds_alternative>(context_)) + { + // Extract to temporary to avoid dangling reference after destruction. + auto socket = std::move(get_base()); + + // Noise context applied to socket, inbound side responding. + auto& stream = inbound_ ? + socket_.emplace(std::move(socket), + std::get>(context_).get()) : + socket_.emplace(std::move(socket)); + + // Posts handler to socket strand. + stream.async_handshake( + std::bind(&socket::handle_handshake, + shared_from_this(), _1, handler)); + return; + } + handler(error::success); } @@ -381,6 +415,51 @@ void socket::handle_detection(const code& ec, shared_from_this(), _1, handler)); } +// Invoked on the socket strand. +void socket::handle_secure_detection(const code& ec, + const result_handler& handler) NOEXCEPT +{ + BC_ASSERT(stranded()); + + if (ec) + { + if (ec == error::unknown) logx("secure detection", ec); + handler(ec); + return; + } + + using namespace system; + constexpr auto size = tls::stream::detection_size; + + // The prefix is consumed by the upgrade (start of client hello or act1). + detection_.commit(size); + const auto data = pointer_cast(detection_.data().data()); + const data_chunk prefix{ data, std::next(data, size) }; + detection_.consume(size); + + // Extract to temporary to avoid dangling reference after destruction. + const auto& contexts = std::get(context_); + auto socket = std::move(get_base()); + + if (tls::stream::detected_hello(prefix)) + { + auto& stream = socket_.emplace(std::move(socket), + contexts.tls_context.get(), true); + + stream.async_handshake(prefix, + std::bind(&socket::handle_handshake, + shared_from_this(), _1, handler)); + return; + } + + auto& stream = socket_.emplace(std::move(socket), + contexts.noise_context.get()); + + stream.async_handshake(prefix, + std::bind(&socket::handle_handshake, + shared_from_this(), _1, handler)); +} + void socket::handle_encrypted_handshake(const code& ec, const result_handler& handler) NOEXCEPT { diff --git a/src/net/socket_http.cpp b/src/net/socket_http.cpp index 857839ef6..3e3ec794c 100644 --- a/src/net/socket_http.cpp +++ b/src/net/socket_http.cpp @@ -53,9 +53,20 @@ constexpr bool is_line_break(char byte) NOEXCEPT return byte == '\r' || byte == '\n'; } +// local +constexpr bool is_token_char(char byte) NOEXCEPT +{ + // A request line opens with its method token (rfc9110 tchar). + return (byte >= '0' && byte <= '9') || (byte >= 'A' && byte <= 'Z') || + (byte >= 'a' && byte <= 'z') || + std::string_view{ "!#$%&'*+-.^_`|~" }.find(byte) != + std::string_view::npos; +} + // local // False implies inconclusive (buffer holds only empty lines). -inline bool detect_json(bool& json, const http::flat_buffer& buffer) NOEXCEPT +inline bool detect_tcp(bool& tcp, const http::flat_buffer& buffer, + bool binary) NOEXCEPT { const auto data = buffer.data(); const auto chars = static_cast(data.data()); @@ -66,32 +77,32 @@ inline bool detect_json(bool& json, const http::flat_buffer& buffer) NOEXCEPT if (is_line_break(byte)) continue; - json = is_json_open(byte); + tcp = binary ? !is_token_char(byte) : is_json_open(byte); return true; } return false; } -void socket::detect(http::flat_buffer& buffer, +void socket::detect(http::flat_buffer& buffer, bool binary, count_handler&& handler) NOEXCEPT { io::dispatch(strand_, std::bind(&socket::do_detect, shared_from_this(), - std::ref(buffer), std::move(handler))); + std::ref(buffer), binary, std::move(handler))); } // private -void socket::do_detect(const ref& buffer, +void socket::do_detect(const ref& buffer, bool binary, const count_handler& handler) NOEXCEPT { BC_ASSERT(stranded()); - bool json{}; - if (detect_json(json, buffer.get())) + bool tcp{}; + if (detect_tcp(tcp, buffer.get(), binary)) { detected_.store(true); - downgraded_.store(json); + downgraded_.store(tcp); handler(error::success, zero); return; } @@ -99,12 +110,12 @@ void socket::do_detect(const ref& buffer, // Tolerated empty lines only, so read more (bounded by the buffer). async_read(buffer.get(), std::bind(&socket::handle_detect, - shared_from_this(), _1, _2, buffer, handler)); + shared_from_this(), _1, _2, buffer, binary, handler)); } // private void socket::handle_detect(const code& ec, size_t size, - const ref& buffer, + const ref& buffer, bool binary, const count_handler& handler) NOEXCEPT { BC_ASSERT(stranded()); @@ -117,7 +128,7 @@ void socket::handle_detect(const code& ec, size_t size, // async_read prepares, the caller commits (as does handle_body_read). buffer.get().commit(size); - do_detect(buffer, handler); + do_detect(buffer, binary, handler); } // HTTP/WS (read). diff --git a/src/noise/stream.cpp b/src/noise/stream.cpp new file mode 100644 index 000000000..7bf3c35b3 --- /dev/null +++ b/src/noise/stream.cpp @@ -0,0 +1,408 @@ +/** + * Copyright (c) 2011-2026 libbitcoin developers + * + * This file is part of libbitcoin. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +#include +#include +#include +#include + +namespace libbitcoin { +namespace network { +namespace noise { + +using namespace system; +using namespace std::placeholders; + +BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT) + +constexpr auto protocol_error = error::protocol_violation; + +static bool payload_length(size_t& out, const const_byte_span& heading) NOEXCEPT +{ + const auto value = messages::sv2::heading::deserialize( + heading.first(cipher::heading_size)); + + if (!value) + return false; + + out = value->message_length; + return true; +} + +// Constructors. +// ---------------------------------------------------------------------------- + +stream::stream(io::socket&& socket, const context& context) NOEXCEPT + : socket_(std::move(socket)), context_(&context) +{ +} + +stream::stream(io::socket&& socket) NOEXCEPT + : socket_(std::move(socket)), context_(nullptr) +{ +} + +// Properties. +// ---------------------------------------------------------------------------- + +stream::executor_type stream::get_executor() NOEXCEPT +{ + return socket_.get_executor(); +} + +io::socket& stream::next_layer() NOEXCEPT +{ + return socket_; +} + +const io::socket& stream::next_layer() const NOEXCEPT +{ + return socket_; +} + +const cipher::key& stream::static_key() const NOEXCEPT +{ + return static_key_; +} + +const cipher::certificate& stream::certificate() const NOEXCEPT +{ + return certificate_; +} + +// Handshake. +// ---------------------------------------------------------------------------- + +void stream::async_handshake(result_handler&& handler) NOEXCEPT +{ + if (is_null(context_)) + do_initiate(std::move(handler)); + else + do_respond(zero, std::move(handler)); +} + +void stream::async_handshake(const const_byte_span& detected, + result_handler&& handler) NOEXCEPT +{ + if (is_null(context_) || detected.size() > act1_.size()) + { + io::post(get_executor(), + std::bind(std::move(handler), code{ error::operation_failed })); + return; + } + + std::copy(detected.begin(), detected.end(), act1_.begin()); + do_respond(detected.size(), std::move(handler)); +} + +// The act1 remainder follows any detected prefix. +void stream::do_respond(size_t detected, + const result_handler& handler) NOEXCEPT +{ + cipher::certificate proof{}; + if (!context_->valid() || !context_->issue(proof, unix_time())) + { + io::post(get_executor(), + std::bind(handler, code{ error::operation_failed })); + return; + } + + cipher_.emplace(context_->static_secret(), context_->static_key(), proof); + const auto remainder = std::span{ act1_ }.subspan(detected); + io::async_read(socket_, io::buffer(remainder.data(), remainder.size()), + std::bind(&stream::handle_act1, + this, _1, handler)); +} + +void stream::handle_act1(const code& ec, + const result_handler& handler) NOEXCEPT +{ + if (ec) + { + handler(ec); + return; + } + + if (!cipher_->respond(act2_, act1_)) + { + handler(protocol_error); + return; + } + + io::async_write(socket_, io::buffer(act2_), + std::bind(handler, _1)); +} + +void stream::do_initiate(const result_handler& handler) NOEXCEPT +{ + cipher_.emplace(); + cipher_->initiate(act1_); + io::async_write(socket_, io::buffer(act1_), + std::bind(&stream::handle_act1_sent, + this, _1, handler)); +} + +void stream::handle_act1_sent(const code& ec, + const result_handler& handler) NOEXCEPT +{ + if (ec) + { + handler(ec); + return; + } + + io::async_read(socket_, io::buffer(act2_), + std::bind(&stream::handle_act2, + this, _1, handler)); +} + +void stream::handle_act2(const code& ec, + const result_handler& handler) NOEXCEPT +{ + if (ec) + { + handler(ec); + return; + } + + handler(cipher_->complete(static_key_, certificate_, act2_) ? + error::success : protocol_error); +} + +// Read. +// ---------------------------------------------------------------------------- + +void stream::do_read_some(const byte_span& out, + const io_handler& handler) NOEXCEPT +{ + if (out.empty() || offset_ < received_.size()) + { + io::post(get_executor(), + std::bind(handler, code{ error::success }, take(out))); + return; + } + + input_.resize(cipher::sealed_heading_size); + io::async_read(socket_, io::buffer(input_), + std::bind(&stream::handle_heading, + this, _1, out, handler)); +} + +// Copy received frame bytes to out, releasing the frame once read. +size_t stream::take(const byte_span& out) NOEXCEPT +{ + const auto size = std::min(out.size(), received_.size() - offset_); + std::copy_n(std::next(received_.begin(), offset_), size, out.begin()); + offset_ += size; + if (offset_ == received_.size()) + { + received_.clear(); + offset_ = zero; + } + + return size; +} + +void stream::handle_heading(const code& ec, const byte_span& out, + const io_handler& handler) NOEXCEPT +{ + if (ec) + { + handler(ec, zero); + return; + } + + size_t length{}; + received_.resize(cipher::heading_size); + if (!cipher_->decrypt_heading(received_, input_) || + !payload_length(length, received_)) + { + handler(protocol_error, zero); + return; + } + + if (is_zero(length)) + { + handler(error::success, take(out)); + return; + } + + input_.resize(cipher::sealed_size(length)); + io::async_read(socket_, io::buffer(input_), + std::bind(&stream::handle_payload, + this, _1, length, out, handler)); +} + +void stream::handle_payload(const code& ec, size_t length, + const byte_span& out, const io_handler& handler) NOEXCEPT +{ + if (ec) + { + handler(ec, zero); + return; + } + + received_.resize(cipher::heading_size + length); + const auto payload = std::span{ received_ }.subspan(cipher::heading_size); + if (!cipher_->decrypt_payload(payload, input_)) + { + handler(protocol_error, zero); + return; + } + + handler(error::success, take(out)); +} + +// Write. +// ---------------------------------------------------------------------------- + +// Seal each whole frame of the written bytes, retaining a partial frame. +bool stream::seal(const const_byte_span& data) NOEXCEPT +{ + pending_.insert(pending_.cend(), data.begin(), data.end()); + while (pending_.size() >= cipher::heading_size) + { + size_t length{}; + if (!payload_length(length, pending_)) + return false; + + const auto frame = cipher::heading_size + length; + if (pending_.size() < frame) + return true; + + const auto start = output_.size(); + const auto sealed = cipher::sealed_heading_size + + cipher::sealed_size(length); + + output_.resize(start + sealed); + const auto out = std::span{ output_ }.subspan(start); + if (!cipher_->encrypt(out, std::span{ pending_ }.first(frame))) + return false; + + pending_.erase(pending_.begin(), std::next(pending_.begin(), frame)); + } + + return true; +} + +void stream::do_write_some(const const_byte_span& data, + const io_handler& handler) NOEXCEPT +{ + if (data.empty()) + { + io::post(get_executor(), + std::bind(handler, code{ error::success }, zero)); + return; + } + + if (!seal(data)) + { + io::post(get_executor(), std::bind(handler, protocol_error, zero)); + return; + } + + const auto size = data.size(); + flush([handler, size](const code& ec) NOEXCEPT + { + handler(ec, ec ? zero : size); + }); +} + +size_t stream::do_write(const const_byte_span& data, code& ec) NOEXCEPT +{ + ec = error::success; + if (writing_) + { + ec = error::operation_failed; + return zero; + } + + if (data.empty()) + return zero; + + if (!seal(data)) + { + ec = protocol_error; + return zero; + } + + io::write(socket_, io::buffer(output_), ec); + output_.clear(); + return ec ? zero : data.size(); +} + +// Shutdown. +// ---------------------------------------------------------------------------- + +void stream::async_shutdown(result_handler&& handler) NOEXCEPT +{ + flush(std::move(handler)); +} + +// Transport. +// ---------------------------------------------------------------------------- + +// The handler completes once all output preceding it is written. +void stream::flush(const result_handler& handler) NOEXCEPT +{ + waiting_.push_back(handler); + if (!writing_) + write_next(); +} + +void stream::write_next() NOEXCEPT +{ + std::vector handlers{}; + handlers.swap(waiting_); + + if (output_.empty()) + { + for (auto& handler: handlers) + io::post(get_executor(), + std::bind(std::move(handler), code{ error::success })); + + return; + } + + writing_ = true; + sending_.swap(output_); + output_.clear(); + io::async_write(socket_, io::buffer(sending_), + std::bind(&stream::handle_write, + this, _1, std::move(handlers))); +} + +void stream::handle_write(const code& ec, + const std::vector& handlers) NOEXCEPT +{ + writing_ = false; + sending_.clear(); + for (const auto& handler: handlers) + handler(ec); + + if (!writing_ && !waiting_.empty()) + write_next(); +} + +BC_POP_WARNING() + +} // namespace noise +} // namespace network +} // namespace libbitcoin diff --git a/src/settings.cpp b/src/settings.cpp index f303a6a37..f57606124 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -275,7 +275,7 @@ code settings::tls_server::initialize_context() NOEXCEPT return error::operation_failed; context = std::make_unique(); - if (safes.empty()) + if (safes.empty() || !tls_secured()) return error::success; if (cert_path.empty()) @@ -317,6 +317,11 @@ code settings::tls_server::initialize_context() NOEXCEPT } BC_POP_WARNING(); +bool settings::tls_server::tls_secured() const NOEXCEPT +{ + return true; +} + bool settings::tls_server::secure() const NOEXCEPT { return !safes.empty() && !cert_path.empty() && !key_path.empty(); diff --git a/src/tls/stream.cpp b/src/tls/stream.cpp index 1fd4e7851..6548ec430 100644 --- a/src/tls/stream.cpp +++ b/src/tls/stream.cpp @@ -90,6 +90,39 @@ void stream::async_handshake(result_handler&& handler) NOEXCEPT this, _1, std::move(handler))); } +void stream::async_handshake(const const_byte_span& detected, + result_handler&& handler) NOEXCEPT +{ + if (!std::holds_alternative(role_) || !context_.is_ready()) + { + const code ec{ code{ error::tls_alert_internal_error } }; + io::post(get_executor(), std::bind(std::move(handler), ec)); + return; + } + + // The detected prefix is the start of the client hello. + connection_->receive(detected); + flush(std::bind(&stream::handle_handshake, + this, _1, std::move(handler))); +} + +// The record (handshake, version 3.x) and handshake (client hello, under 64KiB +// and at least the record's remainder) headers, then legacy version 3.3. +bool stream::detected_hello(const std::span& prefix) NOEXCEPT +{ + if (prefix.size() < detection_size) + return false; + + const size_t record = (size_t{ prefix[3] } << 8) | prefix[4]; + const size_t hello = (size_t{ prefix[7] } << 8) | prefix[8]; + + return prefix[0] == 0x16 && prefix[1] == 0x03 && + prefix[2] >= 0x01 && prefix[2] <= 0x04 && + record >= 4u && record <= 0x4000u && + prefix[5] == 0x01 && prefix[6] == 0x00 && hello >= record - 4u && + prefix[9] == 0x03 && prefix[10] == 0x03; +} + void stream::handle_hello(const code& ec, const result_handler& handler) NOEXCEPT { diff --git a/test/channels/channel_http.cpp b/test/channels/channel_http.cpp index ec9090261..542b3d1fb 100644 --- a/test/channels/channel_http.cpp +++ b/test/channels/channel_http.cpp @@ -220,7 +220,7 @@ BC_FIXTURE_TEST_CASE(socket__detect__json_object__downgraded, http_loopback_fixt { http::flat_buffer buffer{ 4096 }; const auto result = http_make_promise(); - server->detect(buffer, http_complete(result)); + server->detect(buffer, false, http_complete(result)); send(R"({"jsonrpc":"2.0","id":1,"method":"echo","params":[]})" "\n"); BC_REQUIRE_EQUAL(http_await(result), error::success); @@ -232,7 +232,7 @@ BC_FIXTURE_TEST_CASE(socket__detect__leading_line_breaks_json_array__downgraded, { http::flat_buffer buffer{ 4096 }; const auto result = http_make_promise(); - server->detect(buffer, http_complete(result)); + server->detect(buffer, false, http_complete(result)); send("\r\n\n["); BC_REQUIRE_EQUAL(http_await(result), error::success); @@ -244,7 +244,31 @@ BC_FIXTURE_TEST_CASE(socket__detect__http_request__not_downgraded, http_loopback { http::flat_buffer buffer{ 4096 }; const auto result = http_make_promise(); - server->detect(buffer, http_complete(result)); + server->detect(buffer, false, http_complete(result)); + + send(http_get_request); + BC_REQUIRE_EQUAL(http_await(result), error::success); + BC_REQUIRE(server->detected()); + BC_REQUIRE(!server->downgraded()); +} + +BC_FIXTURE_TEST_CASE(socket__detect__binary_sv2_frame__downgraded, http_loopback_fixture) +{ + http::flat_buffer buffer{ 4096 }; + const auto result = http_make_promise(); + server->detect(buffer, true, http_complete(result)); + + send(std::string{ "\x00\x00\x00\x00\x00\x00", 6 }); + BC_REQUIRE_EQUAL(http_await(result), error::success); + BC_REQUIRE(server->detected()); + BC_REQUIRE(server->downgraded()); +} + +BC_FIXTURE_TEST_CASE(socket__detect__binary_http_request__not_downgraded, http_loopback_fixture) +{ + http::flat_buffer buffer{ 4096 }; + const auto result = http_make_promise(); + server->detect(buffer, true, http_complete(result)); send(http_get_request); BC_REQUIRE_EQUAL(http_await(result), error::success); @@ -256,7 +280,7 @@ BC_FIXTURE_TEST_CASE(socket__detect__peer_close__peer_disconnect, http_loopback_ { http::flat_buffer buffer{ 4096 }; const auto result = http_make_promise(); - server->detect(buffer, http_complete(result)); + server->detect(buffer, false, http_complete(result)); code ignore{}; client.shutdown(io::socket::shutdown_type::send, ignore); diff --git a/test/noise/stream.cpp b/test/noise/stream.cpp new file mode 100644 index 000000000..ec0396c4c --- /dev/null +++ b/test/noise/stream.cpp @@ -0,0 +1,270 @@ +/** + * Copyright (c) 2011-2026 libbitcoin developers + * + * This file is part of libbitcoin. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include +#include "../test.hpp" +#include "vectors.hpp" + +BC_AUTO_TEST_SUITE(noise_stream_tests) + +using namespace network::noise; +using system::data_chunk; + +constexpr uint32_t validity = 3600; + +// A core frame of message type one with the given payload. +static data_chunk frame(const data_chunk& payload) +{ + const auto size = payload.size(); + data_chunk out + { + 0x00, 0x00, 0x01, + system::narrow_cast(size), + system::narrow_cast(size >> 8), + system::narrow_cast(size >> 16) + }; + + out.insert(out.end(), payload.begin(), payload.end()); + return out; +} + +struct noise_stream_fixture +{ + DELETE_COPY_MOVE(noise_stream_fixture); + + noise_stream_fixture() NOEXCEPT + { + io::socket server{ service }; + io::socket client{ service }; + io::acceptor acceptor{ service, test::loopback(0) }; + acceptor.async_accept(server, [](const code& ec) NOEXCEPT + { + BC_REQUIRE(!ec); + }); + client.async_connect(acceptor.local_endpoint(), + [](const code& ec) NOEXCEPT + { + BC_REQUIRE(!ec); + }); + + run(); + responder.emplace(std::move(server), instance); + initiator.emplace(std::move(client)); + } + + ~noise_stream_fixture() NOEXCEPT = default; + + void run() NOEXCEPT + { + service.run(); + service.restart(); + } + + void shake(code& responded, code& initiated) NOEXCEPT + { + responder->async_handshake([&](const code& ec) NOEXCEPT + { + responded = ec; + }); + initiator->async_handshake([&](const code& ec) NOEXCEPT + { + initiated = ec; + }); + + run(); + } + + void shake() NOEXCEPT + { + code responded{ error::would_block }; + code initiated{ error::would_block }; + shake(responded, initiated); + BC_REQUIRE(!responded); + BC_REQUIRE(!initiated); + } + + // Each chunk is written by its own write. + code write(stream& to, const std::vector& chunks) NOEXCEPT + { + code result{}; + for (const auto& chunk: chunks) + { + io::async_write(to, io::buffer(chunk), + [&](const code& ec, size_t) NOEXCEPT + { + if (ec) result = ec; + }); + + run(); + } + + return result; + } + + data_chunk read(stream& from, size_t size, code& result) NOEXCEPT + { + data_chunk out(size); + result = error::would_block; + io::async_read(from, io::buffer(out), + [&](const code& ec, size_t) NOEXCEPT + { + result = ec; + }); + + run(); + return out; + } + + io::context service{}; + const context instance + { + sv2_noise::static_secret, sv2_noise::authority_secret, validity + }; + + std::optional responder{}; + std::optional initiator{}; +}; + +BC_FIXTURE_TEST_CASE(noise_stream__handshake__both_sides__success, noise_stream_fixture) +{ + code responded{ error::would_block }; + code initiated{ error::would_block }; + shake(responded, initiated); + BC_REQUIRE(!responded); + BC_REQUIRE(!initiated); +} + +BC_FIXTURE_TEST_CASE(noise_stream__handshake__initiator__authorized_static_key, noise_stream_fixture) +{ + shake(); + system::ec_xonly server{}; + const auto decoded = certificate::to_xonly(server, initiator->static_key()); + const auto verified = certificate::verify(initiator->certificate(), server, sv2_noise::authority_xonly, unix_time()); + BC_REQUIRE(decoded); + BC_REQUIRE(verified); +} + +BC_FIXTURE_TEST_CASE(noise_stream__write__initiator_frame__responder_reads_frame, noise_stream_fixture) +{ + shake(); + const auto expected = frame(system::base16_chunk("00112233445566778899")); + const auto written = write(*initiator, { expected }); + code read_ec{}; + const auto actual = read(*responder, expected.size(), read_ec); + BC_REQUIRE(!written); + BC_REQUIRE(!read_ec); + BC_REQUIRE_EQUAL(actual, expected); +} + +BC_FIXTURE_TEST_CASE(noise_stream__write__responder_frame__initiator_reads_frame, noise_stream_fixture) +{ + shake(); + const auto expected = frame(system::base16_chunk("ffeeddccbbaa")); + const auto written = write(*responder, { expected }); + code read_ec{}; + const auto actual = read(*initiator, expected.size(), read_ec); + BC_REQUIRE(!written); + BC_REQUIRE(!read_ec); + BC_REQUIRE_EQUAL(actual, expected); +} + +BC_FIXTURE_TEST_CASE(noise_stream__write__empty_payload__responder_reads_heading, noise_stream_fixture) +{ + shake(); + const auto expected = frame({}); + const auto written = write(*initiator, { expected }); + code read_ec{}; + const auto actual = read(*responder, expected.size(), read_ec); + BC_REQUIRE(!written); + BC_REQUIRE(!read_ec); + BC_REQUIRE_EQUAL(actual, expected); +} + +BC_FIXTURE_TEST_CASE(noise_stream__write__frame_split_across_writes__responder_reads_frame, noise_stream_fixture) +{ + shake(); + const auto expected = frame(system::base16_chunk("0102030405060708")); + const data_chunk first(expected.begin(), std::next(expected.begin(), 4)); + const data_chunk second(std::next(expected.begin(), 4), expected.end()); + const auto written = write(*initiator, { first, second }); + code read_ec{}; + const auto actual = read(*responder, expected.size(), read_ec); + BC_REQUIRE(!written); + BC_REQUIRE(!read_ec); + BC_REQUIRE_EQUAL(actual, expected); +} + +BC_FIXTURE_TEST_CASE(noise_stream__write__two_frames_one_write__responder_reads_both, noise_stream_fixture) +{ + shake(); + const auto one = frame(system::base16_chunk("aa")); + const auto two = frame(system::base16_chunk("bbcc")); + const auto expected = system::build_chunk({ one, two }); + const auto written = write(*initiator, { expected }); + code read_ec{}; + const auto actual = read(*responder, expected.size(), read_ec); + BC_REQUIRE(!written); + BC_REQUIRE(!read_ec); + BC_REQUIRE_EQUAL(actual, expected); +} + +BC_FIXTURE_TEST_CASE(noise_stream__write__payload_above_chunk__responder_reads_frame, noise_stream_fixture) +{ + shake(); + const auto expected = frame(data_chunk(cipher::chunk_size + 42u, 0x5a)); + const auto written = write(*initiator, { expected }); + code read_ec{}; + const auto actual = read(*responder, expected.size(), read_ec); + BC_REQUIRE(!written); + BC_REQUIRE(!read_ec); + BC_REQUIRE_EQUAL(actual, expected); +} + +BC_FIXTURE_TEST_CASE(noise_stream__read__tampered_heading__protocol_violation, noise_stream_fixture) +{ + shake(); + const data_chunk garbage(cipher::sealed_heading_size, 0x00); + test::write(initiator->next_layer(), io::buffer(garbage)); + code read_ec{}; + read(*responder, cipher::heading_size, read_ec); + BC_REQUIRE_EQUAL(read_ec, error::protocol_violation); +} + +BC_FIXTURE_TEST_CASE(noise_stream__handshake__detected_prefix__initiator_completes, noise_stream_fixture) +{ + cipher client{}; + cipher::act1 act1{}; + cipher::act2 act2{}; + cipher::key key{}; + cipher::certificate proof{}; + data_chunk prefix(tls::stream::detection_size); + code ignore{}; + code responded{ error::would_block }; + client.initiate(act1); + test::write(initiator->next_layer(), io::buffer(act1)); + io::read(responder->next_layer(), io::buffer(prefix), ignore); + responder->async_handshake(prefix, [&](const code& ec) NOEXCEPT { responded = ec; }); + run(); + io::read(initiator->next_layer(), io::buffer(act2), ignore); + const auto completed = client.complete(key, proof, act2); + BC_REQUIRE(!responded); + BC_REQUIRE(completed); + BC_REQUIRE_EQUAL(key, instance.static_key()); +} + +BC_AUTO_TEST_SUITE_END() diff --git a/test/tls/socket.cpp b/test/tls/socket.cpp index 75f959a27..4dd7da15f 100644 --- a/test/tls/socket.cpp +++ b/test/tls/socket.cpp @@ -599,4 +599,29 @@ BC_AUTO_TEST_CASE(tls_socket__read__requested_key_update__exchanged) BC_REQUIRE_EQUAL(peer.read(response.size()), response); } +BC_AUTO_TEST_CASE(tls_stream__detected_hello__client_hello_prefix__true) +{ + BC_REQUIRE(tls::stream::detected_hello(system::base16_chunk("16030100c8010000c40303"))); +} + +BC_AUTO_TEST_CASE(tls_stream__detected_hello__hello_spanning_records__true) +{ + BC_REQUIRE(tls::stream::detected_hello(system::base16_chunk("1603034000010041000303"))); +} + +BC_AUTO_TEST_CASE(tls_stream__detected_hello__other_legacy_version__false) +{ + BC_REQUIRE(!tls::stream::detected_hello(system::base16_chunk("16030100c8010000c40301"))); +} + +BC_AUTO_TEST_CASE(tls_stream__detected_hello__zeros__false) +{ + BC_REQUIRE(!tls::stream::detected_hello(system::data_chunk(tls::stream::detection_size))); +} + +BC_AUTO_TEST_CASE(tls_stream__detected_hello__short_prefix__false) +{ + BC_REQUIRE(!tls::stream::detected_hello(system::base16_chunk("16030100c8010000c403"))); +} + BC_AUTO_TEST_SUITE_END()