Skip to content

Commit 1e9d367

Browse files
committed
Merge bitcoin/bitcoin#28423: kernel: Remove protocol.h/netaddress.h/compat.h from kernel headers
d506765 [refactor] Remove compat.h from kernel headers (TheCharlatan) 36193af [refactor] Remove netaddress.h from kernel headers (TheCharlatan) 2b08c55 [refactor] Add CChainParams member to CConnman (TheCharlatan) f0d1d8b [refactor] Add missing includes for next commit (TheCharlatan) 534b314 kernel: Move MessageStartChars to its own file (TheCharlatan) 9be330b [refactor] Define MessageStartChars as std::array (TheCharlatan) 37e2b01 [refactor] Allow std::array<std::byte, N> in serialize.h (MarcoFalke) Pull request description: This removes the non-consensus critical `protocol.h` and `netaddress.h` headers from the kernel headers. With this patch, they are no longer required to include in order to use the libbitcoinkernel library. This also allows for the removal of the `compat.h` header from the kernel headers. As an added future benefit it also reduces the number of of kernel headers that include the platform specific `bitcoin-config.h`. For those interested, the currently required kernel headers can be inspected visually with the [sourcetrail](https://github.com/CoatiSoftware/Sourcetrail) tool by looking at the required includes of `bitcoin-chainstate.cpp`. --- This is part of the [libbitcoinkernel project](bitcoin/bitcoin#27587), namely its stage 1 step 3: Decouple most non-consensus headers from libbitcoinkernel. ACKs for top commit: stickies-v: re-ACK d506765 hebasto: ACK d506765. ajtowns: utACK d506765 MarcoFalke: lgtm ACK d506765 🍛 Tree-SHA512: 6f90ea510a302c2927e84d16900e89997c39b8ff3ce9d4effeb8a134bd29cc52bd9e81e51aaa11f7496bad00025b78a58b88c5a9e0bb3f4ebbe9a76309215fb7
2 parents 744e0e3 + d506765 commit 1e9d367

31 files changed

+90
-53
lines changed

src/Makefile.am

+1
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ BITCOIN_CORE_H = \
191191
kernel/mempool_options.h \
192192
kernel/mempool_persist.h \
193193
kernel/mempool_removal_reason.h \
194+
kernel/messagestartchars.h \
194195
kernel/notifications_interface.h \
195196
kernel/validation_cache_sizes.h \
196197
key.h \

src/addrdb.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,10 @@ void DeserializeDB(Stream& stream, Data&& data, bool fCheckSum = true)
9090
{
9191
HashVerifier verifier{stream};
9292
// de-serialize file header (network specific magic number) and ..
93-
unsigned char pchMsgTmp[4];
93+
MessageStartChars pchMsgTmp;
9494
verifier >> pchMsgTmp;
9595
// ... verify the network matches ours
96-
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
96+
if (pchMsgTmp != Params().MessageStart()) {
9797
throw std::runtime_error{"Invalid network magic number"};
9898
}
9999

src/bench/block_assemble.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <consensus/validation.h>
77
#include <crypto/sha256.h>
88
#include <node/miner.h>
9+
#include <random.h>
910
#include <test/util/mining.h>
1011
#include <test/util/script.h>
1112
#include <test/util/setup_common.h>

src/bench/duplicate_inputs.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include <consensus/merkle.h>
88
#include <consensus/validation.h>
99
#include <pow.h>
10+
#include <random.h>
1011
#include <test/util/setup_common.h>
1112
#include <txmempool.h>
1213
#include <validation.h>

src/bench/mempool_stress.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include <bench/bench.h>
66
#include <kernel/mempool_entry.h>
77
#include <policy/policy.h>
8+
#include <random.h>
89
#include <test/util/setup_common.h>
910
#include <txmempool.h>
1011
#include <util/chaintype.h>

src/bitcoin-chainstate.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include <node/blockstorage.h>
2323
#include <node/caches.h>
2424
#include <node/chainstate.h>
25+
#include <random.h>
2526
#include <scheduler.h>
2627
#include <script/sigcache.h>
2728
#include <util/chaintype.h>

src/bitcoin-util.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
#include <core_io.h>
1818
#include <streams.h>
1919
#include <util/exception.h>
20+
#include <util/strencodings.h>
2021
#include <util/translation.h>
2122
#include <version.h>
2223

src/init.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1223,7 +1223,7 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)
12231223
assert(!node.connman);
12241224
node.connman = std::make_unique<CConnman>(GetRand<uint64_t>(),
12251225
GetRand<uint64_t>(),
1226-
*node.addrman, *node.netgroupman, args.GetBoolArg("-networkactive", true));
1226+
*node.addrman, *node.netgroupman, chainparams, args.GetBoolArg("-networkactive", true));
12271227

12281228
assert(!node.fee_estimator);
12291229
// Don't initialize fee estimation with old data if we don't relay transactions,

src/kernel/chainparams.cpp

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <consensus/merkle.h>
1111
#include <consensus/params.h>
1212
#include <hash.h>
13+
#include <kernel/messagestartchars.h>
1314
#include <logging.h>
1415
#include <primitives/block.h>
1516
#include <primitives/transaction.h>
@@ -359,7 +360,7 @@ class SigNetParams : public CChainParams {
359360
HashWriter h{};
360361
h << consensus.signet_challenge;
361362
uint256 hash = h.GetHash();
362-
memcpy(pchMessageStart, hash.begin(), 4);
363+
std::copy_n(hash.begin(), 4, pchMessageStart.begin());
363364

364365
nDefaultPort = 38333;
365366
nPruneAfterHeight = 1000;

src/kernel/chainparams.h

+3-13
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@
77
#define BITCOIN_KERNEL_CHAINPARAMS_H
88

99
#include <consensus/params.h>
10-
#include <netaddress.h>
10+
#include <kernel/messagestartchars.h>
1111
#include <primitives/block.h>
12-
#include <protocol.h>
1312
#include <uint256.h>
1413
#include <util/chaintype.h>
1514
#include <util/hash_type.h>
@@ -87,17 +86,8 @@ class CChainParams
8786
};
8887

8988
const Consensus::Params& GetConsensus() const { return consensus; }
90-
const CMessageHeader::MessageStartChars& MessageStart() const { return pchMessageStart; }
89+
const MessageStartChars& MessageStart() const { return pchMessageStart; }
9190
uint16_t GetDefaultPort() const { return nDefaultPort; }
92-
uint16_t GetDefaultPort(Network net) const
93-
{
94-
return net == NET_I2P ? I2P_SAM31_PORT : GetDefaultPort();
95-
}
96-
uint16_t GetDefaultPort(const std::string& addr) const
97-
{
98-
CNetAddr a;
99-
return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) : GetDefaultPort();
100-
}
10191

10292
const CBlock& GenesisBlock() const { return genesis; }
10393
/** Default value for -checkmempool and -checkblockindex argument */
@@ -165,7 +155,7 @@ class CChainParams
165155
CChainParams() {}
166156

167157
Consensus::Params consensus;
168-
CMessageHeader::MessageStartChars pchMessageStart;
158+
MessageStartChars pchMessageStart;
169159
uint16_t nDefaultPort;
170160
uint64_t nPruneAfterHeight;
171161
uint64_t m_assumed_blockchain_size;

src/kernel/messagestartchars.h

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright (c) 2023 The Bitcoin Core developers
2+
// Distributed under the MIT software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
5+
#ifndef BITCOIN_KERNEL_MESSAGESTARTCHARS_H
6+
#define BITCOIN_KERNEL_MESSAGESTARTCHARS_H
7+
8+
#include <array>
9+
#include <cstdint>
10+
11+
using MessageStartChars = std::array<uint8_t, 4>;
12+
13+
#endif // BITCOIN_KERNEL_MESSAGESTARTCHARS_H

src/key_io.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <bech32.h>
99
#include <script/interpreter.h>
1010
#include <script/solver.h>
11+
#include <tinyformat.h>
1112
#include <util/strencodings.h>
1213

1314
#include <algorithm>

src/net.cpp

+21-10
Original file line numberDiff line numberDiff line change
@@ -470,8 +470,8 @@ CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCo
470470
Ticks<HoursDouble>(pszDest ? 0h : Now<NodeSeconds>() - addrConnect.nTime));
471471

472472
// Resolve
473-
const uint16_t default_port{pszDest != nullptr ? Params().GetDefaultPort(pszDest) :
474-
Params().GetDefaultPort()};
473+
const uint16_t default_port{pszDest != nullptr ? GetDefaultPort(pszDest) :
474+
m_params.GetDefaultPort()};
475475
if (pszDest) {
476476
const std::vector<CService> resolved{Lookup(pszDest, default_port, fNameLookup && !HaveNameProxy(), 256)};
477477
if (!resolved.empty()) {
@@ -730,7 +730,7 @@ V1Transport::V1Transport(const NodeId node_id, int nTypeIn, int nVersionIn) noex
730730
m_node_id(node_id), hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn)
731731
{
732732
assert(std::size(Params().MessageStart()) == std::size(m_magic_bytes));
733-
std::copy(std::begin(Params().MessageStart()), std::end(Params().MessageStart()), m_magic_bytes);
733+
m_magic_bytes = Params().MessageStart();
734734
LOCK(m_recv_mutex);
735735
Reset();
736736
}
@@ -759,7 +759,7 @@ int V1Transport::readHeader(Span<const uint8_t> msg_bytes)
759759
}
760760

761761
// Check start string, network magic
762-
if (memcmp(hdr.pchMessageStart, m_magic_bytes, CMessageHeader::MESSAGE_START_SIZE) != 0) {
762+
if (hdr.pchMessageStart != m_magic_bytes) {
763763
LogPrint(BCLog::NET, "Header error: Wrong MessageStart %s received, peer=%d\n", HexStr(hdr.pchMessageStart), m_node_id);
764764
return -1;
765765
}
@@ -1144,7 +1144,7 @@ bool V2Transport::ProcessReceivedKeyBytes() noexcept
11441144
// they receive our uniformly random key and garbage, but detecting this case specially
11451145
// means we can log it.
11461146
static constexpr std::array<uint8_t, 12> MATCH = {'v', 'e', 'r', 's', 'i', 'o', 'n', 0, 0, 0, 0, 0};
1147-
static constexpr size_t OFFSET = sizeof(CMessageHeader::MessageStartChars);
1147+
static constexpr size_t OFFSET = std::tuple_size_v<MessageStartChars>;
11481148
if (!m_initiating && m_recv_buffer.size() >= OFFSET + MATCH.size()) {
11491149
if (std::equal(MATCH.begin(), MATCH.end(), m_recv_buffer.begin() + OFFSET)) {
11501150
LogPrint(BCLog::NET, "V2 transport error: V1 peer with wrong MessageStart %s\n",
@@ -2184,7 +2184,7 @@ void CConnman::WakeMessageHandler()
21842184
void CConnman::ThreadDNSAddressSeed()
21852185
{
21862186
FastRandomContext rng;
2187-
std::vector<std::string> seeds = Params().DNSSeeds();
2187+
std::vector<std::string> seeds = m_params.DNSSeeds();
21882188
Shuffle(seeds.begin(), seeds.end(), rng);
21892189
int seeds_right_now = 0; // Number of seeds left before testing if we have enough connections
21902190
int found = 0;
@@ -2275,7 +2275,7 @@ void CConnman::ThreadDNSAddressSeed()
22752275
const auto addresses{LookupHost(host, nMaxIPs, true)};
22762276
if (!addresses.empty()) {
22772277
for (const CNetAddr& ip : addresses) {
2278-
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
2278+
CAddress addr = CAddress(CService(ip, m_params.GetDefaultPort()), requiredServiceBits);
22792279
addr.nTime = rng.rand_uniform_delay(Now<NodeSeconds>() - 3 * 24h, -4 * 24h); // use a random age between 3 and 7 days old
22802280
vAdd.push_back(addr);
22812281
found++;
@@ -2480,7 +2480,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
24802480
}
24812481

24822482
if (add_fixed_seeds_now) {
2483-
std::vector<CAddress> seed_addrs{ConvertSeeds(Params().FixedSeeds())};
2483+
std::vector<CAddress> seed_addrs{ConvertSeeds(m_params.FixedSeeds())};
24842484
// We will not make outgoing connections to peers that are unreachable
24852485
// (e.g. because of -onlynet configuration).
24862486
// Therefore, we do not add them to addrman in the first place.
@@ -2769,7 +2769,7 @@ std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo() const
27692769
}
27702770

27712771
for (const std::string& strAddNode : lAddresses) {
2772-
CService service(LookupNumeric(strAddNode, Params().GetDefaultPort(strAddNode)));
2772+
CService service(LookupNumeric(strAddNode, GetDefaultPort(strAddNode)));
27732773
AddedNodeInfo addedNode{strAddNode, CService(), false, false};
27742774
if (service.IsValid()) {
27752775
// strAddNode is an IP:port
@@ -3075,11 +3075,12 @@ void CConnman::SetNetworkActive(bool active)
30753075
}
30763076

30773077
CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In, AddrMan& addrman_in,
3078-
const NetGroupManager& netgroupman, bool network_active)
3078+
const NetGroupManager& netgroupman, const CChainParams& params, bool network_active)
30793079
: addrman(addrman_in)
30803080
, m_netgroupman{netgroupman}
30813081
, nSeed0(nSeed0In)
30823082
, nSeed1(nSeed1In)
3083+
, m_params(params)
30833084
{
30843085
SetTryNewOutboundPeer(false);
30853086

@@ -3093,6 +3094,16 @@ NodeId CConnman::GetNewNodeId()
30933094
return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
30943095
}
30953096

3097+
uint16_t CConnman::GetDefaultPort(Network net) const
3098+
{
3099+
return net == NET_I2P ? I2P_SAM31_PORT : m_params.GetDefaultPort();
3100+
}
3101+
3102+
uint16_t CConnman::GetDefaultPort(const std::string& addr) const
3103+
{
3104+
CNetAddr a;
3105+
return a.SetSpecial(addr) ? GetDefaultPort(a.GetNetwork()) : m_params.GetDefaultPort();
3106+
}
30963107

30973108
bool CConnman::Bind(const CService& addr_, unsigned int flags, NetPermissionFlags permissions)
30983109
{

src/net.h

+10-3
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,16 @@
1010
#include <chainparams.h>
1111
#include <common/bloom.h>
1212
#include <compat/compat.h>
13-
#include <node/connection_types.h>
1413
#include <consensus/amount.h>
1514
#include <crypto/siphash.h>
1615
#include <hash.h>
1716
#include <i2p.h>
17+
#include <kernel/messagestartchars.h>
1818
#include <net_permissions.h>
1919
#include <netaddress.h>
2020
#include <netbase.h>
2121
#include <netgroup.h>
22+
#include <node/connection_types.h>
2223
#include <policy/feerate.h>
2324
#include <protocol.h>
2425
#include <random.h>
@@ -46,6 +47,7 @@
4647

4748
class AddrMan;
4849
class BanMan;
50+
class CChainParams;
4951
class CNode;
5052
class CScheduler;
5153
struct bilingual_str;
@@ -360,7 +362,7 @@ class Transport {
360362
class V1Transport final : public Transport
361363
{
362364
private:
363-
CMessageHeader::MessageStartChars m_magic_bytes;
365+
MessageStartChars m_magic_bytes;
364366
const NodeId m_node_id; // Only for logging
365367
mutable Mutex m_recv_mutex; //!< Lock for receive state
366368
mutable CHash256 hasher GUARDED_BY(m_recv_mutex);
@@ -1080,7 +1082,7 @@ class CConnman
10801082
}
10811083

10821084
CConnman(uint64_t seed0, uint64_t seed1, AddrMan& addrman, const NetGroupManager& netgroupman,
1083-
bool network_active = true);
1085+
const CChainParams& params, bool network_active = true);
10841086

10851087
~CConnman();
10861088

@@ -1356,6 +1358,9 @@ class CConnman
13561358
// Whether the node should be passed out in ForEach* callbacks
13571359
static bool NodeFullyConnected(const CNode* pnode);
13581360

1361+
uint16_t GetDefaultPort(Network net) const;
1362+
uint16_t GetDefaultPort(const std::string& addr) const;
1363+
13591364
// Network usage totals
13601365
mutable Mutex m_total_bytes_sent_mutex;
13611366
std::atomic<uint64_t> nTotalBytesRecv{0};
@@ -1565,6 +1570,8 @@ class CConnman
15651570
std::vector<CNode*> m_nodes_copy;
15661571
};
15671572

1573+
const CChainParams& m_params;
1574+
15681575
friend struct ConnmanTestMsg;
15691576
};
15701577

src/node/blockstorage.cpp

+4-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include <flatfile.h>
1212
#include <hash.h>
1313
#include <kernel/chainparams.h>
14+
#include <kernel/messagestartchars.h>
1415
#include <logging.h>
1516
#include <pow.h>
1617
#include <reverse_iterator.h>
@@ -21,6 +22,7 @@
2122
#include <util/batchpriority.h>
2223
#include <util/fs.h>
2324
#include <util/signalinterrupt.h>
25+
#include <util/strencodings.h>
2426
#include <util/translation.h>
2527
#include <validation.h>
2628

@@ -927,12 +929,12 @@ bool BlockManager::ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatF
927929
}
928930

929931
try {
930-
CMessageHeader::MessageStartChars blk_start;
932+
MessageStartChars blk_start;
931933
unsigned int blk_size;
932934

933935
filein >> blk_start >> blk_size;
934936

935-
if (memcmp(blk_start, GetParams().MessageStart(), CMessageHeader::MESSAGE_START_SIZE)) {
937+
if (blk_start != GetParams().MessageStart()) {
936938
return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
937939
HexStr(blk_start),
938940
HexStr(GetParams().MessageStart()));

src/node/blockstorage.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
#include <kernel/blockmanager_opts.h>
1212
#include <kernel/chainparams.h>
1313
#include <kernel/cs_main.h>
14-
#include <protocol.h>
14+
#include <kernel/messagestartchars.h>
1515
#include <sync.h>
1616
#include <util/fs.h>
1717
#include <util/hasher.h>
@@ -73,7 +73,7 @@ static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
7373
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
7474

7575
/** Size of header written by WriteBlockToDisk before a serialized CBlock */
76-
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE = CMessageHeader::MESSAGE_START_SIZE + sizeof(unsigned int);
76+
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE = std::tuple_size_v<MessageStartChars> + sizeof(unsigned int);
7777

7878
extern std::atomic_bool fReindex;
7979

src/protocol.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ const static std::vector<std::string> g_all_net_message_types{
9292

9393
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
9494
{
95-
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
95+
pchMessageStart = pchMessageStartIn;
9696

9797
// Copy the command name
9898
size_t i = 0;

0 commit comments

Comments
 (0)