Skip to content

Commit

Permalink
Merge bitcoin#30510: multiprocess: Add IPC wrapper for Mining interface
Browse files Browse the repository at this point in the history
1a33281 doc: multiprocess documentation improvements (Ryan Ofsky)
d043950 multiprocess: Add serialization code for BlockValidationState (Ryan Ofsky)
33c2eee multiprocess: Add IPC wrapper for Mining interface (Ryan Ofsky)
06882f8 multiprocess: Add serialization code for vector<char> (Russell Yanofsky)
095286f multiprocess: Add serialization code for CTransaction (Russell Yanofsky)
69dfeb1 multiprocess: update common-types.h to use C++20 concepts (Ryan Ofsky)
206c6e7 build: Make bitcoin_ipc_test depend on bitcoin_ipc (Ryan Ofsky)
070e6a3 depends: Update libmultiprocess library for cmake headers target (Ryan Ofsky)

Pull request description:

  Add Cap'n Proto wrapper for the Mining interface introduced in bitcoin#30200, and its associated types.

  This PR combined with bitcoin#30509 will allow a separate mining process, like the one being implemented in Sjors#48, to connect to the node over IPC, and create, manage, and submit block templates. (bitcoin#30437 shows another simpler demo of a process using the Mining interface.)

  ---

  This PR is part of the [process separation project](bitcoin#28722).

ACKs for top commit:
  achow101:
    ACK 1a33281
  TheCharlatan:
    ACK 1a33281
  itornaza:
    ACK 1a33281

Tree-SHA512: 0791078dd6885dbd81e3d14c75fffff3da8d1277873af379ea6f9633e910c11485bb324e4cde3d936d50d343b16a10b0e8fc1e0fc6d7bdca7f522211da50c01e
  • Loading branch information
achow101 committed Sep 25, 2024
2 parents da612ce + 1a33281 commit 65f6e70
Show file tree
Hide file tree
Showing 17 changed files with 327 additions and 58 deletions.
4 changes: 2 additions & 2 deletions depends/packages/native_libmultiprocess.mk
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package=native_libmultiprocess
$(package)_version=c1b4ab4eb897d3af09bc9b3cc30e2e6fff87f3e2
$(package)_version=015e95f7ebaa47619a213a19801e7fffafc56864
$(package)_download_path=https://github.com/chaincodelabs/libmultiprocess/archive
$(package)_file_name=$($(package)_version).tar.gz
$(package)_sha256_hash=6edf5ad239ca9963c78f7878486fb41411efc9927c6073928a7d6edf947cac4a
$(package)_sha256_hash=4b1266b121337f3f6f37e1863fba91c1a5ee9ad126bcffc6fe6b9ca47ad050a1
$(package)_dependencies=native_capnp

define $(package)_config_cmds
Expand Down
8 changes: 4 additions & 4 deletions doc/design/multiprocess.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ This section describes the major components of the Inter-Process Communication (
- In the generated code, we have C++ client subclasses that inherit from the abstract classes in [`src/interfaces/`](../../src/interfaces/). These subclasses are the workhorses of the IPC mechanism.
- They implement all the methods of the interface, marshalling arguments into a structured format, sending them as requests to the IPC server via a UNIX socket, and handling the responses.
- These subclasses effectively mask the complexity of IPC, presenting a familiar C++ interface to developers.
- Internally, the client subclasses generated by the `mpgen` tool wrap [client classes generated by Cap'n Proto](https://capnproto.org/cxxrpc.html#clients), and use them to send IPC requests.
- Internally, the client subclasses generated by the `mpgen` tool wrap [client classes generated by Cap'n Proto](https://capnproto.org/cxxrpc.html#clients), and use them to send IPC requests. The Cap'n Proto client classes are low-level, with non-blocking methods that use asynchronous I/O and pass request and response objects, while mpgen client subclasses provide normal C++ methods that block while executing and convert between request/response objects and arguments/return values.

### C++ Server Classes in Generated Code
- On the server side, corresponding generated C++ classes receive IPC requests. These server classes are responsible for unmarshalling method arguments, invoking the corresponding methods in the local [`src/interfaces/`](../../src/interfaces/) objects, and creating the IPC response.
Expand All @@ -94,7 +94,7 @@ This section describes the major components of the Inter-Process Communication (
- **Asynchronous I/O and Thread Management**: The library is also responsible for managing I/O and threading. Particularly, it ensures that IPC requests never block each other and that new threads on either side of a connection can always make client calls. It also manages worker threads on the server side of calls, ensuring that calls from the same client thread always execute on the same server thread (to avoid locking issues and support nested callbacks).

### Type Hooks in [`src/ipc/capnp/*-types.h`](../../src/ipc/capnp/)
- **Custom Type Conversions**: In [`src/ipc/capnp/*-types.h`](../../src/ipc/capnp/), function overloads of two `libmultiprocess` C++ functions, `mp::CustomReadField` and `mp::CustomBuildFields`, are defined. These overloads are used for customizing the conversion of specific C++ types to and from Cap’n Proto types.
- **Custom Type Conversions**: In [`src/ipc/capnp/*-types.h`](../../src/ipc/capnp/), function overloads of `libmultiprocess` C++ functions, `mp::CustomReadField`, `mp::CustomBuildField`, `mp::CustomReadMessage` and `mp::CustomBuildMessage`, are defined. These overloads are used for customizing the conversion of specific C++ types to and from Cap’n Proto types.
- **Handling Special Cases**: The `mpgen` tool and `libmultiprocess` library can convert most C++ types to and from Cap’n Proto types automatically, including interface types, primitive C++ types, standard C++ types like `std::vector`, `std::set`, `std::map`, `std::tuple`, and `std::function`, as well as simple C++ structs that consist of aforementioned types and whose fields correspond 1:1 with Cap’n Proto struct fields. For other types, `*-types.h` files provide custom code to convert between C++ and Cap’n Proto data representations.

### Protocol-Agnostic IPC Code in [`src/ipc/`](../../src/ipc/)
Expand Down Expand Up @@ -197,7 +197,7 @@ sequenceDiagram
- Upon receiving the request, the Cap'n Proto dispatching code in the `bitcoin-node` process calls the `getBlockHash` method of the `Chain` [server class](#c-server-classes-in-generated-code).
- The server class is automatically generated by the `mpgen` tool from the [`chain.capnp`](https://github.com/ryanofsky/bitcoin/blob/pr/ipc/src/ipc/capnp/chain.capnp) file in [`src/ipc/capnp/`](../../src/ipc/capnp/).
- The `getBlockHash` method of the generated `Chain` server subclass in `bitcoin-wallet` receives a Cap’n Proto request object with the `height` parameter, and calls the `getBlockHash` method on its local `Chain` object with the provided `height`.
- When the call returns, it encapsulates the return value in a Cap’n Proto response, which it sends back to the `bitcoin-wallet` process,
- When the call returns, it encapsulates the return value in a Cap’n Proto response, which it sends back to the `bitcoin-wallet` process.

5. **Response and Return**
- The `getBlockHash` method of the generated `Chain` client subclass in `bitcoin-wallet` which sent the request now receives the response.
Expand Down Expand Up @@ -232,7 +232,7 @@ This modularization represents an advancement in Bitcoin Core's architecture, of

- **Cap’n Proto struct**: A structured data format used in Cap’n Proto, similar to structs in C++, for organizing and transporting data across different processes.

- **client class (in generated code)**: A C++ class generated from a Cap’n Proto interface which inherits from a Bitcoin core abstract class, and implements each virtual method to send IPC requests to another process. (see also [components section](#c-client-subclasses-in-generated-code))
- **client class (in generated code)**: A C++ class generated from a Cap’n Proto interface which inherits from a Bitcoin Core abstract class, and implements each virtual method to send IPC requests to another process. (see also [components section](#c-client-subclasses-in-generated-code))

- **IPC (inter-process communication)**: Mechanisms that enable processes to exchange requests and data.

Expand Down
4 changes: 3 additions & 1 deletion doc/multiprocess.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ The multiprocess feature requires [Cap'n Proto](https://capnproto.org/) and [lib
```
cd <BITCOIN_SOURCE_DIRECTORY>
make -C depends NO_QT=1 MULTIPROCESS=1
cmake -B build --toolchain=depends/x86_64-pc-linux-gnu/toolchain.cmake
# Set host platform to output of gcc -dumpmachine or clang -dumpmachine or check the depends/ directory for the generated subdirectory name
HOST_PLATFORM="x86_64-pc-linux-gnu"
cmake -B build --toolchain=depends/$HOST_PLATFORM/toolchain.cmake
cmake --build build
build/src/bitcoin-node -regtest -printtoconsole -debug=ipc
BITCOIND=$(pwd)/build/src/bitcoin-node build/test/functional/test_runner.py
Expand Down
16 changes: 16 additions & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,22 @@ if(WITH_MULTIPROCESS)
$<TARGET_NAME_IF_EXISTS:bitcoin_wallet>
)
list(APPEND installable_targets bitcoin-node)

if(BUILD_TESTS)
# bitcoin_ipc_test library target is defined here in src/CMakeLists.txt
# instead of src/test/CMakeLists.txt so capnp files in src/test/ are able to
# reference capnp files in src/ipc/capnp/ by relative path. The Cap'n Proto
# compiler only allows importing by relative path when the importing and
# imported files are underneath the same compilation source prefix, so the
# source prefix must be src/, not src/test/
add_library(bitcoin_ipc_test STATIC EXCLUDE_FROM_ALL
test/ipc_test.cpp
)
target_capnp_sources(bitcoin_ipc_test ${PROJECT_SOURCE_DIR}
test/ipc_test.capnp
)
add_dependencies(bitcoin_ipc_test bitcoin_ipc_headers)
endif()
endif()


Expand Down
7 changes: 6 additions & 1 deletion src/ipc/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
# file COPYING or https://opensource.org/license/mit/.

add_library(bitcoin_ipc STATIC EXCLUDE_FROM_ALL
capnp/mining.cpp
capnp/protocol.cpp
interfaces.cpp
process.cpp
)

target_capnp_sources(bitcoin_ipc ${PROJECT_SOURCE_DIR}
capnp/echo.capnp capnp/init.capnp
capnp/common.capnp
capnp/echo.capnp
capnp/init.capnp
capnp/mining.capnp
)

target_link_libraries(bitcoin_ipc
PRIVATE
core_interface
univalue
)
139 changes: 98 additions & 41 deletions src/ipc/capnp/common-types.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
#define BITCOIN_IPC_CAPNP_COMMON_TYPES_H

#include <clientversion.h>
#include <interfaces/types.h>
#include <primitives/transaction.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>

Expand All @@ -16,76 +19,103 @@

namespace ipc {
namespace capnp {
//! Use SFINAE to define Serializeable<T> trait which is true if type T has a
//! Serialize(stream) method, false otherwise.
template <typename T>
struct Serializable {
private:
template <typename C>
static std::true_type test(decltype(std::declval<C>().Serialize(std::declval<std::nullptr_t&>()))*);
template <typename>
static std::false_type test(...);

public:
static constexpr bool value = decltype(test<T>(nullptr))::value;
};
//! Construct a ParamStream wrapping a data stream with serialization parameters
//! needed to pass transaction objects between bitcoin processes.
//! In the future, more params may be added here to serialize other objects that
//! require serialization parameters. Params should just be chosen to serialize
//! objects completely and ensure that serializing and deserializing objects
//! with the specified parameters produces equivalent objects. It's also
//! harmless to specify serialization parameters here that are not used.
template <typename S>
auto Wrap(S& s)
{
return ParamsStream{s, TX_WITH_WITNESS};
}

//! Use SFINAE to define Unserializeable<T> trait which is true if type T has
//! an Unserialize(stream) method, false otherwise.
//! Detect if type has a deserialize_type constructor, which is
//! used to deserialize types like CTransaction that can't be unserialized into
//! existing objects because they are immutable.
template <typename T>
struct Unserializable {
private:
template <typename C>
static std::true_type test(decltype(std::declval<C>().Unserialize(std::declval<std::nullptr_t&>()))*);
template <typename>
static std::false_type test(...);

public:
static constexpr bool value = decltype(test<T>(nullptr))::value;
};
concept Deserializable = std::is_constructible_v<T, ::deserialize_type, ::DataStream&>;
} // namespace capnp
} // namespace ipc

//! Functions to serialize / deserialize common bitcoin types.
namespace mp {
//! Overload multiprocess library's CustomBuildField hook to allow any
//! serializable object to be stored in a capnproto Data field or passed to a
//! canproto interface. Use Priority<1> so this hook has medium priority, and
//! capnproto interface. Use Priority<1> so this hook has medium priority, and
//! higher priority hooks could take precedence over this one.
template <typename LocalType, typename Value, typename Output>
void CustomBuildField(
TypeList<LocalType>, Priority<1>, InvokeContext& invoke_context, Value&& value, Output&& output,
// Enable if serializeable and if LocalType is not cv or reference
// qualified. If LocalType is cv or reference qualified, it is important to
// fall back to lower-priority Priority<0> implementation of this function
// that strips cv references, to prevent this CustomBuildField overload from
// taking precedence over more narrow overloads for specific LocalTypes.
std::enable_if_t<ipc::capnp::Serializable<LocalType>::value &&
std::is_same_v<LocalType, std::remove_cv_t<std::remove_reference_t<LocalType>>>>* enable = nullptr)
void CustomBuildField(TypeList<LocalType>, Priority<1>, InvokeContext& invoke_context, Value&& value, Output&& output)
// Enable if serializeable and if LocalType is not cv or reference qualified. If
// LocalType is cv or reference qualified, it is important to fall back to
// lower-priority Priority<0> implementation of this function that strips cv
// references, to prevent this CustomBuildField overload from taking precedence
// over more narrow overloads for specific LocalTypes.
requires Serializable<LocalType, DataStream> && std::is_same_v<LocalType, std::remove_cv_t<std::remove_reference_t<LocalType>>>
{
DataStream stream;
value.Serialize(stream);
auto wrapper{ipc::capnp::Wrap(stream)};
value.Serialize(wrapper);
auto result = output.init(stream.size());
memcpy(result.begin(), stream.data(), stream.size());
}

//! Overload multiprocess library's CustomReadField hook to allow any object
//! with an Unserialize method to be read from a capnproto Data field or
//! returned from canproto interface. Use Priority<1> so this hook has medium
//! returned from capnproto interface. Use Priority<1> so this hook has medium
//! priority, and higher priority hooks could take precedence over this one.
template <typename LocalType, typename Input, typename ReadDest>
decltype(auto)
CustomReadField(TypeList<LocalType>, Priority<1>, InvokeContext& invoke_context, Input&& input, ReadDest&& read_dest,
std::enable_if_t<ipc::capnp::Unserializable<LocalType>::value>* enable = nullptr)
decltype(auto) CustomReadField(TypeList<LocalType>, Priority<1>, InvokeContext& invoke_context, Input&& input, ReadDest&& read_dest)
requires Unserializable<LocalType, DataStream> && (!ipc::capnp::Deserializable<LocalType>)
{
return read_dest.update([&](auto& value) {
if (!input.has()) return;
auto data = input.get();
SpanReader stream({data.begin(), data.end()});
value.Unserialize(stream);
auto wrapper{ipc::capnp::Wrap(stream)};
value.Unserialize(wrapper);
});
}

//! Overload multiprocess library's CustomReadField hook to allow any object
//! with a deserialize constructor to be read from a capnproto Data field or
//! returned from capnproto interface. Use Priority<1> so this hook has medium
//! priority, and higher priority hooks could take precedence over this one.
template <typename LocalType, typename Input, typename ReadDest>
decltype(auto) CustomReadField(TypeList<LocalType>, Priority<1>, InvokeContext& invoke_context, Input&& input, ReadDest&& read_dest)
requires ipc::capnp::Deserializable<LocalType>
{
assert(input.has());
auto data = input.get();
SpanReader stream({data.begin(), data.end()});
auto wrapper{ipc::capnp::Wrap(stream)};
return read_dest.construct(::deserialize, wrapper);
}

//! Overload CustomBuildField and CustomReadField to serialize std::chrono
//! parameters and return values as numbers.
template <class Rep, class Period, typename Value, typename Output>
void CustomBuildField(TypeList<std::chrono::duration<Rep, Period>>, Priority<1>, InvokeContext& invoke_context, Value&& value,
Output&& output)
{
static_assert(std::numeric_limits<decltype(output.get())>::lowest() <= std::numeric_limits<Rep>::lowest(),
"capnp type does not have enough range to hold lowest std::chrono::duration value");
static_assert(std::numeric_limits<decltype(output.get())>::max() >= std::numeric_limits<Rep>::max(),
"capnp type does not have enough range to hold highest std::chrono::duration value");
output.set(value.count());
}

template <class Rep, class Period, typename Input, typename ReadDest>
decltype(auto) CustomReadField(TypeList<std::chrono::duration<Rep, Period>>, Priority<1>, InvokeContext& invoke_context,
Input&& input, ReadDest&& read_dest)
{
return read_dest.construct(input.get());
}

//! Overload CustomBuildField and CustomReadField to serialize UniValue
//! parameters and return values as JSON strings.
template <typename Value, typename Output>
void CustomBuildField(TypeList<UniValue>, Priority<1>, InvokeContext& invoke_context, Value&& value, Output&& output)
{
Expand All @@ -103,6 +133,33 @@ decltype(auto) CustomReadField(TypeList<UniValue>, Priority<1>, InvokeContext& i
value.read(std::string_view{data.begin(), data.size()});
});
}

//! Generic ::capnp::Data field builder for any C++ type that can be converted
//! to a span of bytes, like std::vector<char> or std::array<uint8_t>, or custom
//! blob types like uint256 or PKHash with data() and size() methods pointing to
//! bytes.
//!
//! Note: it might make sense to move this function into libmultiprocess, since
//! it is fairly generic. However this would require decreasing its priority so
//! it can be overridden, which would require more changes inside
//! libmultiprocess to avoid conflicting with the Priority<1> CustomBuildField
//! function it already provides for std::vector. Also, it might make sense to
//! provide a CustomReadField counterpart to this function, which could be
//! called to read C++ types that can be constructed from spans of bytes from
//! ::capnp::Data fields. But so far there hasn't been a need for this.
template <typename LocalType, typename Value, typename Output>
void CustomBuildField(TypeList<LocalType>, Priority<2>, InvokeContext& invoke_context, Value&& value, Output&& output)
requires
(std::is_same_v<decltype(output.get()), ::capnp::Data::Builder>) &&
(std::convertible_to<Value, std::span<const std::byte>> ||
std::convertible_to<Value, std::span<const char>> ||
std::convertible_to<Value, std::span<const unsigned char>> ||
std::convertible_to<Value, std::span<const signed char>>)
{
auto data = std::span{value};
auto result = output.init(data.size());
memcpy(result.begin(), data.data(), data.size());
}
} // namespace mp

#endif // BITCOIN_IPC_CAPNP_COMMON_TYPES_H
16 changes: 16 additions & 0 deletions src/ipc/capnp/common.capnp
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright (c) 2024 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.

@0xcd2c6232cb484a28;

using Cxx = import "/capnp/c++.capnp";
$Cxx.namespace("ipc::capnp::messages");

using Proxy = import "/mp/proxy.capnp";
$Proxy.includeTypes("ipc/capnp/common-types.h");

struct BlockRef $Proxy.wrap("interfaces::BlockRef") {
hash @0 :Data;
height @1 :Int32;
}
1 change: 1 addition & 0 deletions src/ipc/capnp/init-types.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
#define BITCOIN_IPC_CAPNP_INIT_TYPES_H

#include <ipc/capnp/echo.capnp.proxy-types.h>
#include <ipc/capnp/mining.capnp.proxy-types.h>

#endif // BITCOIN_IPC_CAPNP_INIT_TYPES_H
3 changes: 3 additions & 0 deletions src/ipc/capnp/init.capnp
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ $Cxx.namespace("ipc::capnp::messages");
using Proxy = import "/mp/proxy.capnp";
$Proxy.include("interfaces/echo.h");
$Proxy.include("interfaces/init.h");
$Proxy.include("interfaces/mining.h");
$Proxy.includeTypes("ipc/capnp/init-types.h");

using Echo = import "echo.capnp";
using Mining = import "mining.capnp";

interface Init $Proxy.wrap("interfaces::Init") {
construct @0 (threadMap: Proxy.ThreadMap) -> (threadMap :Proxy.ThreadMap);
makeEcho @1 (context :Proxy.Context) -> (result :Echo.Echo);
makeMining @2 (context :Proxy.Context) -> (result :Mining.Mining);
}
26 changes: 26 additions & 0 deletions src/ipc/capnp/mining-types.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) 2024 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_IPC_CAPNP_MINING_TYPES_H
#define BITCOIN_IPC_CAPNP_MINING_TYPES_H

#include <interfaces/mining.h>
#include <ipc/capnp/common.capnp.proxy-types.h>
#include <ipc/capnp/common-types.h>
#include <ipc/capnp/mining.capnp.proxy.h>
#include <node/miner.h>
#include <node/types.h>
#include <validation.h>

namespace mp {
// Custom serialization for BlockValidationState.
void CustomBuildMessage(InvokeContext& invoke_context,
const BlockValidationState& src,
ipc::capnp::messages::BlockValidationState::Builder&& builder);
void CustomReadMessage(InvokeContext& invoke_context,
const ipc::capnp::messages::BlockValidationState::Reader& reader,
BlockValidationState& dest);
} // namespace mp

#endif // BITCOIN_IPC_CAPNP_MINING_TYPES_H
Loading

0 comments on commit 65f6e70

Please sign in to comment.