Bitcoin Core 31.99.0
P2P Digital Currency
test_kernel.cpp
Go to the documentation of this file.
1// Copyright (c) 2024-present 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
7#include <util/byte_units.h>
8#include <util/fs.h>
9
10// Boost.Test's SIGSTKSZ alternate stack can be smaller than Linux requires on musl.
11#define BOOST_TEST_DISABLE_ALT_STACK
12#define BOOST_TEST_MODULE Bitcoin Kernel Test Suite
13#include <boost/test/included/unit_test.hpp>
14
16#include <test/util/common.h>
17
18#include <charconv>
19#include <cstdint>
20#include <cstdlib>
21#include <iostream>
22#include <memory>
23#include <optional>
24#include <random>
25#include <ranges>
26#include <span>
27#include <string>
28#include <string_view>
29#include <vector>
30
31using namespace btck;
32
33std::string random_string(uint32_t length)
34{
35 const std::string chars = "0123456789"
36 "abcdefghijklmnopqrstuvwxyz"
37 "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
38
39 static std::random_device rd;
40 static std::default_random_engine dre{rd()};
41 static std::uniform_int_distribution<> distribution(0, chars.size() - 1);
42
43 std::string random;
44 random.reserve(length);
45 for (uint32_t i = 0; i < length; i++) {
46 random += chars[distribution(dre)];
47 }
48 return random;
49}
50
51std::vector<std::byte> hex_string_to_byte_vec(std::string_view hex)
52{
53 std::vector<std::byte> bytes;
54 bytes.reserve(hex.length() / 2);
55
56 for (size_t i{0}; i < hex.length(); i += 2) {
57 uint8_t byte_value;
58 auto [ptr, ec] = std::from_chars(hex.data() + i, hex.data() + i + 2, byte_value, 16);
59
60 if (ec != std::errc{} || ptr != hex.data() + i + 2) {
61 throw std::invalid_argument("Invalid hex character");
62 }
63 bytes.push_back(static_cast<std::byte>(byte_value));
64 }
65 return bytes;
66}
67
68std::string byte_span_to_hex_string_reversed(std::span<const std::byte> bytes)
69{
70 std::ostringstream oss;
71
72 // Iterate in reverse order
73 for (auto it = bytes.rbegin(); it != bytes.rend(); ++it) {
74 oss << std::hex << std::setw(2) << std::setfill('0')
75 << static_cast<unsigned int>(static_cast<uint8_t>(*it));
76 }
77
78 return oss.str();
79}
80
81constexpr auto VERIFY_ALL_PRE_SEGWIT{ScriptVerificationFlags::P2SH | ScriptVerificationFlags::DERSIG |
82 ScriptVerificationFlags::NULLDUMMY | ScriptVerificationFlags::CHECKLOCKTIMEVERIFY |
83 ScriptVerificationFlags::CHECKSEQUENCEVERIFY};
84constexpr auto VERIFY_ALL_PRE_TAPROOT{VERIFY_ALL_PRE_SEGWIT | ScriptVerificationFlags::WITNESS};
85
86void check_equal(std::span<const std::byte> _actual, std::span<const std::byte> _expected, bool equal = true)
87{
88 std::span<const uint8_t> actual{reinterpret_cast<const unsigned char*>(_actual.data()), _actual.size()};
89 std::span<const uint8_t> expected{reinterpret_cast<const unsigned char*>(_expected.data()), _expected.size()};
90 BOOST_CHECK_EQUAL_COLLECTIONS(
91 actual.begin(), actual.end(),
92 expected.begin(), expected.end());
93}
94
96{
97public:
98 void LogMessage(std::string_view message)
99 {
100 std::cout << "kernel: " << message;
101 }
102};
103
105 fs::path m_directory;
106 TestDirectory(std::string directory_name)
107 : m_directory{fs::path{fs::temp_directory_path()} / fs::u8path(directory_name + "_🌽_" + random_string(16))}
108 {
109 fs::create_directories(m_directory);
110 }
111
113 {
114 fs::remove_all(m_directory);
115 }
116};
117
119{
120public:
121 void HeaderTipHandler(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override
122 {
123 BOOST_CHECK_GT(timestamp, 0);
124 }
125
126 void FlushErrorHandler(std::string_view error) override
127 {
128 std::cout << error << std::endl;
129 }
130
131 void FatalErrorHandler(std::string_view error) override
132 {
133 std::cout << error << std::endl;
134 }
135};
136
138{
139public:
140 std::optional<std::vector<std::byte>> m_expected_valid_block = std::nullopt;
141
142 void BlockChecked(Block block, BlockValidationStateView state) override
143 {
144 if (m_expected_valid_block.has_value()) {
145 auto ser_block{block.ToBytes()};
146 check_equal(m_expected_valid_block.value(), ser_block);
147 }
148
149 auto mode{state.GetValidationMode()};
150 switch (mode) {
151 case ValidationMode::VALID: {
152 std::cout << "Valid block" << std::endl;
153 return;
154 }
156 std::cout << "Invalid block: ";
157 auto result{state.GetBlockValidationResult()};
158 switch (result) {
159 case BlockValidationResult::UNSET:
160 std::cout << "initial value. Block has not yet been rejected" << std::endl;
161 break;
162 case BlockValidationResult::HEADER_LOW_WORK:
163 std::cout << "the block header may be on a too-little-work chain" << std::endl;
164 break;
165 case BlockValidationResult::CONSENSUS:
166 std::cout << "invalid by consensus rules (excluding any below reasons)" << std::endl;
167 break;
168 case BlockValidationResult::CACHED_INVALID:
169 std::cout << "this block was cached as being invalid and we didn't store the reason why" << std::endl;
170 break;
171 case BlockValidationResult::INVALID_HEADER:
172 std::cout << "invalid proof of work or time too old" << std::endl;
173 break;
174 case BlockValidationResult::MUTATED:
175 std::cout << "the block's data didn't match the data committed to by the PoW" << std::endl;
176 break;
177 case BlockValidationResult::MISSING_PREV:
178 std::cout << "We don't have the previous block the checked one is built on" << std::endl;
179 break;
180 case BlockValidationResult::INVALID_PREV:
181 std::cout << "A block this one builds on is invalid" << std::endl;
182 break;
183 case BlockValidationResult::TIME_FUTURE:
184 std::cout << "block timestamp was > 2 hours in the future (or our clock is bad)" << std::endl;
185 break;
186 }
187 return;
188 }
189 case ValidationMode::INTERNAL_ERROR: {
190 std::cout << "Internal error" << std::endl;
191 return;
192 }
193 }
194 }
195
196 void BlockConnected(Block block, BlockTreeEntry entry) override
197 {
198 std::cout << "Block connected." << std::endl;
199 }
200
201 void PowValidBlock(BlockTreeEntry entry, Block block) override
202 {
203 std::cout << "Block passed pow verification" << std::endl;
204 }
205
206 void BlockDisconnected(Block block, BlockTreeEntry entry) override
207 {
208 std::cout << "Block disconnected." << std::endl;
209 }
210};
211
213 const ScriptPubkey& spent_script_pubkey,
214 const Transaction& spending_tx,
215 const PrecomputedTransactionData* precomputed_txdata,
216 int64_t amount,
217 unsigned int input_index,
218 bool taproot)
219{
220 auto status = ScriptVerifyStatus::OK;
221
222 if (taproot) {
223 BOOST_CHECK(spent_script_pubkey.Verify(
224 amount,
225 spending_tx,
226 precomputed_txdata,
227 input_index,
229 status));
230 BOOST_CHECK(status == ScriptVerifyStatus::OK);
231 } else {
232 BOOST_CHECK(!spent_script_pubkey.Verify(
233 amount,
234 spending_tx,
235 precomputed_txdata,
236 input_index,
238 status));
239 BOOST_CHECK(status == ScriptVerifyStatus::ERROR_SPENT_OUTPUTS_REQUIRED);
240 }
241
242 BOOST_CHECK(spent_script_pubkey.Verify(
243 amount,
244 spending_tx,
245 precomputed_txdata,
246 input_index,
248 status));
249 BOOST_CHECK(status == ScriptVerifyStatus::OK);
250
251 BOOST_CHECK(spent_script_pubkey.Verify(
252 0,
253 spending_tx,
254 precomputed_txdata,
255 input_index,
257 status));
258 BOOST_CHECK(status == ScriptVerifyStatus::OK);
259}
260
261template <typename T>
262concept HasToBytes = requires(T t) {
263 { t.ToBytes() } -> std::convertible_to<std::span<const std::byte>>;
264};
265
266template <typename T>
267void CheckHandle(T object, T distinct_object)
268{
269 BOOST_CHECK(object.get() != nullptr);
270 BOOST_CHECK(distinct_object.get() != nullptr);
271 BOOST_CHECK(object.get() != distinct_object.get());
272
273 if constexpr (HasToBytes<T>) {
274 const auto object_bytes = object.ToBytes();
275 const auto distinct_bytes = distinct_object.ToBytes();
276 BOOST_CHECK(!std::ranges::equal(object_bytes, distinct_bytes));
277 }
278
279 // Copy constructor
280 T object2(distinct_object);
281 BOOST_CHECK_NE(distinct_object.get(), object2.get());
282 if constexpr (HasToBytes<T>) {
283 check_equal(distinct_object.ToBytes(), object2.ToBytes());
284 }
285
286 // Copy assignment
287 T object3{distinct_object};
288 object2 = object3;
289 BOOST_CHECK_NE(object3.get(), object2.get());
290 if constexpr (HasToBytes<T>) {
291 check_equal(object3.ToBytes(), object2.ToBytes());
292 }
293
294 // Move constructor
295 auto* original_ptr = object2.get();
296 T object4{std::move(object2)};
297 BOOST_CHECK_EQUAL(object4.get(), original_ptr);
298 BOOST_CHECK_EQUAL(object2.get(), nullptr); // NOLINT(bugprone-use-after-move)
299 if constexpr (HasToBytes<T>) {
300 check_equal(object4.ToBytes(), object3.ToBytes());
301 }
302
303 // Move assignment
304 original_ptr = object4.get();
305 object2 = std::move(object4);
306 BOOST_CHECK_EQUAL(object2.get(), original_ptr);
307 BOOST_CHECK_EQUAL(object4.get(), nullptr); // NOLINT(bugprone-use-after-move)
308 if constexpr (HasToBytes<T>) {
309 check_equal(object2.ToBytes(), object3.ToBytes());
310 }
311
312 // Self move-assignment must not destroy the held resource.
313 // Use a reference to avoid -Wself-move warnings.
314 original_ptr = object2.get();
315 auto& object2_ref = object2;
316 object2 = std::move(object2_ref);
317 BOOST_CHECK_EQUAL(object2.get(), original_ptr);
318 if constexpr (HasToBytes<T>) {
319 check_equal(object2.ToBytes(), object3.ToBytes());
320 }
321}
322
323template <typename RangeType>
324 requires std::ranges::random_access_range<RangeType>
325void CheckRange(const RangeType& range, size_t expected_size)
326{
327 using value_type = std::ranges::range_value_t<RangeType>;
328
329 BOOST_CHECK_EQUAL(range.size(), expected_size);
330 BOOST_REQUIRE(range.size() > 0); // Some checks below assume a non-empty range
331 BOOST_REQUIRE(!range.empty());
332
333 BOOST_CHECK(range.begin() != range.end());
334 BOOST_CHECK_EQUAL(std::distance(range.begin(), range.end()), static_cast<std::ptrdiff_t>(expected_size));
335 BOOST_CHECK(range.cbegin() == range.begin());
336 BOOST_CHECK(range.cend() == range.end());
337
338 for (size_t i = 0; i < range.size(); ++i) {
339 BOOST_CHECK_EQUAL(range[i].get(), (*(range.begin() + i)).get());
340 }
341
342 BOOST_CHECK_THROW(range.at(expected_size), std::out_of_range);
343
344 BOOST_CHECK_EQUAL(range.front().get(), range[0].get());
345 BOOST_CHECK_EQUAL(range.back().get(), range[expected_size - 1].get());
346
347 auto it = range.begin();
348 auto it_copy = it;
349 ++it;
350 BOOST_CHECK(it != it_copy);
351 --it;
352 BOOST_CHECK(it == it_copy);
353 it = range.begin();
354 auto old_it = it++;
355 BOOST_CHECK(old_it == range.begin());
356 BOOST_CHECK(it == range.begin() + 1);
357 old_it = it--;
358 BOOST_CHECK(old_it == range.begin() + 1);
359 BOOST_CHECK(it == range.begin());
360
361 it = range.begin();
362 it += 2;
363 BOOST_CHECK(it == range.begin() + 2);
364 it -= 2;
365 BOOST_CHECK(it == range.begin());
366
367 BOOST_CHECK(range.begin() < range.end());
368 BOOST_CHECK(range.begin() <= range.end());
369 BOOST_CHECK(range.end() > range.begin());
370 BOOST_CHECK(range.end() >= range.begin());
371 BOOST_CHECK(range.begin() == range.begin());
372
373 BOOST_CHECK_EQUAL(range.begin()[0].get(), range[0].get());
374
375 size_t count = 0;
376 for (auto rit = range.end(); rit != range.begin();) {
377 --rit;
378 ++count;
379 }
380 BOOST_CHECK_EQUAL(count, expected_size);
381
382 std::vector<value_type> collected;
383 for (const auto& elem : range) {
384 collected.push_back(elem);
385 }
386 BOOST_CHECK_EQUAL(collected.size(), expected_size);
387
388 BOOST_CHECK_EQUAL(std::ranges::size(range), expected_size);
389
390 it = range.begin();
391 auto it2 = 1 + it;
392 BOOST_CHECK(it2 == it + 1);
393}
394
395BOOST_AUTO_TEST_CASE(btck_transaction_tests)
396{
397 auto tx_data{hex_string_to_byte_vec("02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700")};
398 auto tx{Transaction{tx_data}};
399 auto tx_data_2{hex_string_to_byte_vec("02000000000101904f4ee5c87d20090b642f116e458cd6693292ad9ece23e72f15fb6c05b956210500000000fdffffff02e2010000000000002251200839a723933b56560487ec4d67dda58f09bae518ffa7e148313c5696ac837d9f10060000000000002251205826bcdae7abfb1c468204170eab00d887b61ab143464a4a09e1450bdc59a3340140f26e7af574e647355830772946356c27e7bbc773c5293688890f58983499581be84de40be7311a14e6d6422605df086620e75adae84ff06b75ce5894de5e994a00000000")};
400 auto tx2{Transaction{tx_data_2}};
401 CheckHandle(tx, tx2);
402
403 auto invalid_data = hex_string_to_byte_vec("012300");
404 BOOST_CHECK_THROW(Transaction{invalid_data}, std::runtime_error);
405 auto empty_data = hex_string_to_byte_vec("");
406 BOOST_CHECK_THROW(Transaction{empty_data}, std::runtime_error);
407
408 BOOST_CHECK_EQUAL(tx.CountOutputs(), 2);
409 BOOST_CHECK_EQUAL(tx.CountInputs(), 1);
410 BOOST_CHECK_EQUAL(tx.GetLocktime(), 510826);
411 auto broken_tx_data{std::span<std::byte>{tx_data.begin(), tx_data.begin() + 10}};
412 BOOST_CHECK_THROW(Transaction{broken_tx_data}, std::runtime_error);
413 auto input{tx.GetInput(0)};
414 BOOST_CHECK_EQUAL(input.GetSequence(), 0xfffffffe);
415 auto output{tx.GetOutput(tx.CountOutputs() - 1)};
416 BOOST_CHECK_EQUAL(output.Amount(), 42130042);
417 auto script_pubkey{output.GetScriptPubkey()};
418 {
419 auto tx_new{Transaction{tx_data}};
420 // This is safe, because we now use copy assignment
421 TransactionOutput output = tx_new.GetOutput(tx_new.CountOutputs() - 1);
423
424 TransactionOutputView output2 = tx_new.GetOutput(tx_new.CountOutputs() - 1);
425 BOOST_CHECK_NE(output.get(), output2.get());
426 BOOST_CHECK_EQUAL(output.Amount(), output2.Amount());
427 TransactionOutput output3 = output2;
428 BOOST_CHECK_NE(output3.get(), output2.get());
429 BOOST_CHECK_EQUAL(output3.Amount(), output2.Amount());
430
431 // Non-owned view
432 ScriptPubkeyView script2 = output.GetScriptPubkey();
433 BOOST_CHECK_NE(script.get(), script2.get());
434 check_equal(script.ToBytes(), script2.ToBytes());
435
436 // Non-owned to owned
437 ScriptPubkey script3 = script2;
438 BOOST_CHECK_NE(script3.get(), script2.get());
439 check_equal(script3.ToBytes(), script2.ToBytes());
440 }
441 BOOST_CHECK_EQUAL(output.Amount(), 42130042);
442
443 auto tx_roundtrip{Transaction{tx.ToBytes()}};
444 check_equal(tx_roundtrip.ToBytes(), tx_data);
445
446 // The following code is unsafe, but left here to show limitations of the
447 // API, because we preserve the output view beyond the lifetime of the
448 // transaction. The view type wrapper should make this clear to the user.
449 // auto get_output = [&]() -> TransactionOutputView {
450 // auto tx{Transaction{tx_data}};
451 // return tx.GetOutput(0);
452 // };
453 // auto output_new = get_output();
454 // BOOST_CHECK_EQUAL(output_new.Amount(), 20737411);
455
456 int64_t total_amount{0};
457 for (const auto output : tx.Outputs()) {
458 total_amount += output.Amount();
459 }
460 BOOST_CHECK_EQUAL(total_amount, 62867453);
461
462 auto amount = *(tx.Outputs() | std::ranges::views::filter([](const auto& output) {
463 return output.Amount() == 42130042;
464 }) |
465 std::views::transform([](const auto& output) {
466 return output.Amount();
467 })).begin();
468 BOOST_REQUIRE(amount);
469 BOOST_CHECK_EQUAL(amount, 42130042);
470
471 CheckRange(tx.Outputs(), tx.CountOutputs());
472
473 ScriptPubkey script_pubkey_roundtrip{script_pubkey.ToBytes()};
474 check_equal(script_pubkey_roundtrip.ToBytes(), script_pubkey.ToBytes());
475}
476
477BOOST_AUTO_TEST_CASE(btck_script_pubkey)
478{
479 auto script_data{hex_string_to_byte_vec("76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ac")};
480 std::vector<std::byte> script_data_2 = script_data;
481 script_data_2.push_back(std::byte{0x51});
482 ScriptPubkey script{script_data};
483 ScriptPubkey script2{script_data_2};
484 CheckHandle(script, script2);
485
486 std::span<std::byte> empty_data{};
487 ScriptPubkey empty_script{empty_data};
488 CheckHandle(script, empty_script);
489}
490
491BOOST_AUTO_TEST_CASE(btck_transaction_output)
492{
493 ScriptPubkey script{hex_string_to_byte_vec("76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ac")};
494 TransactionOutput output{script, 1};
495 TransactionOutput output2{script, 2};
496 CheckHandle(output, output2);
497}
498
499BOOST_AUTO_TEST_CASE(btck_transaction_input)
500{
501 Transaction tx{hex_string_to_byte_vec("020000000248c03e66fd371c7033196ce24298628e59ebefa00363026044e0f35e0325a65d000000006a473044022004893432347f39beaa280e99da595681ddb20fc45010176897e6e055d716dbfa022040a9e46648a5d10c33ef7cee5e6cf4b56bd513eae3ae044f0039824b02d0f44c012102982331a52822fd9b62e9b5d120da1d248558fac3da3a3c51cd7d9c8ad3da760efeffffffb856678c6e4c3c84e39e2ca818807049d6fba274b42af3c6d3f9d4b6513212d2000000006a473044022068bcedc7fe39c9f21ad318df2c2da62c2dc9522a89c28c8420ff9d03d2e6bf7b0220132afd752754e5cb1ea2fd0ed6a38ec666781e34b0e93dc9a08f2457842cf5660121033aeb9c079ea3e08ea03556182ab520ce5c22e6b0cb95cee6435ee17144d860cdfeffffff0260d50b00000000001976a914363cc8d55ea8d0500de728ef6d63804ddddbdc9888ac67040f00000000001976a914c303bdc5064bf9c9a8b507b5496bd0987285707988ac6acb0700")};
502 TransactionInput input_0 = tx.GetInput(0);
503 TransactionInput input_1 = tx.GetInput(1);
504 CheckHandle(input_0, input_1);
505 CheckRange(tx.Inputs(), tx.CountInputs());
506 OutPoint point_0 = input_0.OutPoint();
507 OutPoint point_1 = input_1.OutPoint();
508 CheckHandle(point_0, point_1);
509
510 WitnessStackView ws_0 = input_0.GetWitnessStack();
511 BOOST_CHECK_EQUAL(ws_0.CountItems(), 0);
512 BOOST_CHECK(ws_0.Items().empty());
513
514 // P2PKH: DER sig + compressed pubkey push.
515 BOOST_CHECK(input_0.GetScriptSig() == hex_string_to_byte_vec("473044022004893432347f39beaa280e99da595681ddb20fc45010176897e6e055d716dbfa022040a9e46648a5d10c33ef7cee5e6cf4b56bd513eae3ae044f0039824b02d0f44c012102982331a52822fd9b62e9b5d120da1d248558fac3da3a3c51cd7d9c8ad3da760e"));
516 BOOST_CHECK(input_1.GetScriptSig() == hex_string_to_byte_vec("473044022068bcedc7fe39c9f21ad318df2c2da62c2dc9522a89c28c8420ff9d03d2e6bf7b0220132afd752754e5cb1ea2fd0ed6a38ec666781e34b0e93dc9a08f2457842cf5660121033aeb9c079ea3e08ea03556182ab520ce5c22e6b0cb95cee6435ee17144d860cd"));
517
518 // P2WSH input: OP_0, sig, sig, redeem_script (0, 71, 71, 105 bytes); no scriptSig.
519 Transaction segwit_tx{hex_string_to_byte_vec("010000000001011f97548fbbe7a0db7588a66e18d803d0089315aa7d4cc28360b6ec50ef36718a0100000000ffffffff02df1776000000000017a9146c002a686959067f4866b8fb493ad7970290ab728757d29f0000000000220020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d04004730440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc014730440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd4355016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000")};
520 TransactionInputView segwit_input = segwit_tx.GetInput(0);
521 WitnessStackView ws = segwit_input.GetWitnessStack();
523 BOOST_CHECK(ws.GetItem(0).empty());
524 BOOST_CHECK(ws.GetItem(1) == hex_string_to_byte_vec("30440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc01"));
525 BOOST_CHECK(ws.GetItem(2) == hex_string_to_byte_vec("30440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd435501"));
526 BOOST_CHECK(ws.GetItem(3) == hex_string_to_byte_vec("52210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae"));
527 auto items = ws.Items();
528 BOOST_CHECK_EQUAL(items.size(), 4);
529 for (size_t i = 0; i < items.size(); ++i) {
530 BOOST_CHECK(items[i] == ws.GetItem(i));
531 }
532 WitnessStack owned_ws_0{ws_0};
533 WitnessStack owned_ws{ws};
534 CheckHandle(owned_ws_0, owned_ws);
535 BOOST_CHECK(segwit_input.GetScriptSig().empty());
536}
537
538BOOST_AUTO_TEST_CASE(btck_precomputed_txdata) {
539 auto tx_data{hex_string_to_byte_vec("02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700")};
540 auto tx{Transaction{tx_data}};
541 auto tx_data_2{hex_string_to_byte_vec("02000000000101904f4ee5c87d20090b642f116e458cd6693292ad9ece23e72f15fb6c05b956210500000000fdffffff02e2010000000000002251200839a723933b56560487ec4d67dda58f09bae518ffa7e148313c5696ac837d9f10060000000000002251205826bcdae7abfb1c468204170eab00d887b61ab143464a4a09e1450bdc59a3340140f26e7af574e647355830772946356c27e7bbc773c5293688890f58983499581be84de40be7311a14e6d6422605df086620e75adae84ff06b75ce5894de5e994a00000000")};
542 auto tx2{Transaction{tx_data_2}};
543 auto precomputed_txdata{PrecomputedTransactionData{
544 /*tx_to=*/tx,
545 /*spent_outputs=*/{},
546 }};
547 auto precomputed_txdata_2{PrecomputedTransactionData{
548 /*tx_to=*/tx2,
549 /*spent_outputs=*/{},
550 }};
551 CheckHandle(precomputed_txdata, precomputed_txdata_2);
552}
553
554BOOST_AUTO_TEST_CASE(btck_script_verify_tests)
555{
556 // Legacy transaction aca326a724eda9a461c10a876534ecd5ae7b27f10f26c3862fb996f80ea2d45d
557 auto legacy_spent_script_pubkey{ScriptPubkey{hex_string_to_byte_vec("76a9144bfbaf6afb76cc5771bc6404810d1cc041a6933988ac")}};
558 auto legacy_spending_tx{Transaction{hex_string_to_byte_vec("02000000013f7cebd65c27431a90bba7f796914fe8cc2ddfc3f2cbd6f7e5f2fc854534da95000000006b483045022100de1ac3bcdfb0332207c4a91f3832bd2c2915840165f876ab47c5f8996b971c3602201c6c053d750fadde599e6f5c4e1963df0f01fc0d97815e8157e3d59fe09ca30d012103699b464d1d8bc9e47d4fb1cdaa89a1c5783d68363c4dbc4b524ed3d857148617feffffff02836d3c01000000001976a914fc25d6d5c94003bf5b0c7b640a248e2c637fcfb088ac7ada8202000000001976a914fbed3d9b11183209a57999d54d59f67c019e756c88ac6acb0700")}};
560 /*spent_script_pubkey=*/legacy_spent_script_pubkey,
561 /*spending_tx=*/legacy_spending_tx,
562 /*precomputed_txdata=*/nullptr,
563 /*amount=*/0,
564 /*input_index=*/0,
565 /*taproot=*/false);
566
567 // Legacy transaction aca326a724eda9a461c10a876534ecd5ae7b27f10f26c3862fb996f80ea2d45d with precomputed_txdata
568 auto legacy_precomputed_txdata{PrecomputedTransactionData{
569 /*tx_to=*/legacy_spending_tx,
570 /*spent_outputs=*/{},
571 }};
573 /*spent_script_pubkey=*/legacy_spent_script_pubkey,
574 /*spending_tx=*/legacy_spending_tx,
575 /*precomputed_txdata=*/&legacy_precomputed_txdata,
576 /*amount=*/0,
577 /*input_index=*/0,
578 /*taproot=*/false);
579
580 // Segwit transaction 1a3e89644985fbbb41e0dcfe176739813542b5937003c46a07de1e3ee7a4a7f3
581 auto segwit_spent_script_pubkey{ScriptPubkey{hex_string_to_byte_vec("0020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d")}};
582 auto segwit_spending_tx{Transaction{hex_string_to_byte_vec("010000000001011f97548fbbe7a0db7588a66e18d803d0089315aa7d4cc28360b6ec50ef36718a0100000000ffffffff02df1776000000000017a9146c002a686959067f4866b8fb493ad7970290ab728757d29f0000000000220020701a8d401c84fb13e6baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d04004730440220565d170eed95ff95027a69b313758450ba84a01224e1f7f130dda46e94d13f8602207bdd20e307f062594022f12ed5017bbf4a055a06aea91c10110a0e3bb23117fc014730440220647d2dc5b15f60bc37dc42618a370b2a1490293f9e5c8464f53ec4fe1dfe067302203598773895b4b16d37485cbe21b337f4e4b650739880098c592553add7dd4355016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000")}};
584 /*spent_script_pubkey=*/segwit_spent_script_pubkey,
585 /*spending_tx=*/segwit_spending_tx,
586 /*precomputed_txdata=*/nullptr,
587 /*amount=*/18393430,
588 /*input_index=*/0,
589 /*taproot=*/false);
590
591 // Segwit transaction 1a3e89644985fbbb41e0dcfe176739813542b5937003c46a07de1e3ee7a4a7f3 with precomputed_txdata
592 auto segwit_precomputed_txdata{PrecomputedTransactionData{
593 /*tx_to=*/segwit_spending_tx,
594 /*spent_outputs=*/{},
595 }};
597 /*spent_script_pubkey=*/segwit_spent_script_pubkey,
598 /*spending_tx=*/segwit_spending_tx,
599 /*precomputed_txdata=*/&segwit_precomputed_txdata,
600 /*amount=*/18393430,
601 /*input_index=*/0,
602 /*taproot=*/false);
603
604 // Taproot transaction 33e794d097969002ee05d336686fc03c9e15a597c1b9827669460fac98799036
605 auto taproot_spent_script_pubkey{ScriptPubkey{hex_string_to_byte_vec("5120339ce7e165e67d93adb3fef88a6d4beed33f01fa876f05a225242b82a631abc0")}};
606 auto taproot_spending_tx{Transaction{hex_string_to_byte_vec("01000000000101d1f1c1f8cdf6759167b90f52c9ad358a369f95284e841d7a2536cef31c0549580100000000fdffffff020000000000000000316a2f49206c696b65205363686e6f7272207369677320616e6420492063616e6e6f74206c69652e204062697462756734329e06010000000000225120a37c3903c8d0db6512e2b40b0dffa05e5a3ab73603ce8c9c4b7771e5412328f90140a60c383f71bac0ec919b1d7dbc3eb72dd56e7aa99583615564f9f99b8ae4e837b758773a5b2e4c51348854c8389f008e05029db7f464a5ff2e01d5e6e626174affd30a00")}};
607 std::vector<TransactionOutput> taproot_spent_outputs;
608 taproot_spent_outputs.emplace_back(taproot_spent_script_pubkey, 88480);
609 auto taproot_precomputed_txdata{PrecomputedTransactionData{
610 /*tx_to=*/taproot_spending_tx,
611 /*spent_outputs=*/taproot_spent_outputs,
612 }};
614 /*spent_script_pubkey=*/taproot_spent_script_pubkey,
615 /*spending_tx=*/taproot_spending_tx,
616 /*precomputed_txdata=*/&taproot_precomputed_txdata,
617 /*amount=*/88480,
618 /*input_index=*/0,
619 /*taproot=*/true);
620
621 // Two-input taproot transaction e8e8320f40c31ed511570e9cdf1d241f8ec9a5cc392e6105240ac8dbea2098de
622 auto taproot2_spent_script_pubkey0{ScriptPubkey{hex_string_to_byte_vec("5120b7da80f57e36930b0515eb09293e25858d13e6b91fee6184943f5a584cb4248e")}};
623 auto taproot2_spent_script_pubkey1{ScriptPubkey{hex_string_to_byte_vec("5120ab78e077d062e7b8acd7063668b4db5355a1b5d5fd2a46a8e98e62e5e63fab77")}};
624 auto taproot2_spending_tx{Transaction{hex_string_to_byte_vec("02000000000102c0f01ead18750892c84b1d4f595149ad38f16847df1fbf490e235b3b78c1f98a0100000000ffffffff456764a19c2682bf5b1567119f06a421849ad1664cf42b5ef95b69d6e2159e9d0000000000ffffffff022202000000000000225120b6c0c2a8ee25a2ae0322ab7f1a06f01746f81f6b90d179c3c2a51a356e6188f1d70e020000000000225120b7da80f57e36930b0515eb09293e25858d13e6b91fee6184943f5a584cb4248e0141933fdc49eb1af1f08ed1e9cf5559259309a8acd25ff1e6999b6955124438aef4fceaa4e6a5f85286631e24837329563595bc3cf4b31e1c687442abb01c4206818101401c9620faf1e8c84187762ad14d04ae3857f59a2f03f1dcbb99290e16dfc572a63b4ea435780a5787af59beb5742fd71cda8a95381517a1ff14b4c67996c4bf8100000000")}};
625 std::vector<TransactionOutput> taproot2_spent_outputs;
626 taproot2_spent_outputs.emplace_back(taproot2_spent_script_pubkey0, 546);
627 taproot2_spent_outputs.emplace_back(taproot2_spent_script_pubkey1, 135125);
628 auto taproot2_precomputed_txdata{PrecomputedTransactionData{
629 /*tx_to=*/taproot2_spending_tx,
630 /*spent_outputs=*/taproot2_spent_outputs,
631 }};
633 /*spent_script_pubkey=*/taproot2_spent_script_pubkey0,
634 /*spending_tx=*/taproot2_spending_tx,
635 /*precomputed_txdata=*/&taproot2_precomputed_txdata,
636 /*amount=*/546,
637 /*input_index=*/0,
638 /*taproot=*/true);
640 /*spent_script_pubkey=*/taproot2_spent_script_pubkey1,
641 /*spending_tx=*/taproot2_spending_tx,
642 /*precomputed_txdata=*/&taproot2_precomputed_txdata,
643 /*amount=*/135125,
644 /*input_index=*/1,
645 /*taproot=*/true);
646}
647
649{
650 btck_LoggingOptions logging_options = {
651 .log_timestamps = true,
652 .log_time_micros = true,
653 .log_threadnames = false,
654 .log_sourcelocations = false,
655 .always_print_category_levels = true,
656 };
657
658 logging_set_options(logging_options);
659 logging_set_level_category(LogCategory::BENCH, LogLevel::TRACE_LEVEL);
663
664 // Check that connecting, connecting another, and then disconnecting and connecting a logger again works.
665 {
666 logging_set_level_category(LogCategory::KERNEL, LogLevel::TRACE_LEVEL);
668 Logger logger{std::make_unique<TestLog>()};
669 Logger logger_2{std::make_unique<TestLog>()};
670 }
671 Logger logger{std::make_unique<TestLog>()};
672}
673
674BOOST_AUTO_TEST_CASE(btck_chainparams_tests)
675{
676 ChainParams params_signet{ChainType::SIGNET};
677 ChainParams params_signet_challenge{hex_string_to_byte_vec("51")};
678 CheckHandle(params_signet, params_signet_challenge);
679}
680
681BOOST_AUTO_TEST_CASE(btck_context_tests)
682{
683 { // test default context
684 Context context{};
685 Context context2{};
686 CheckHandle(context, context2);
687 }
688
689 { // test with context options, but not options set
690 ContextOptions options{};
691 Context context{options};
692 }
693
694 { // test with context options
695 ContextOptions options{};
696 ChainParams params{ChainType::MAINNET};
697 ChainParams regtest_params{ChainType::REGTEST};
698 CheckHandle(params, regtest_params);
699 options.SetChainParams(params);
700 options.SetNotifications(std::make_shared<TestKernelNotifications>());
701 Context context{options};
702 }
703}
704
705BOOST_AUTO_TEST_CASE(btck_block_header_tests)
706{
707 // Block header format: version(4) + prev_hash(32) + merkle_root(32) + timestamp(4) + bits(4) + nonce(4) = 80 bytes
708 BlockHeader header_0{hex_string_to_byte_vec("00e07a26beaaeee2e71d7eb19279545edbaf15de0999983626ec00000000000000000000579cf78b65229bfb93f4a11463af2eaa5ad91780f27f5d147a423bea5f7e4cdf2a47e268b4dd01173a9662ee")};
709 BOOST_CHECK_EQUAL(byte_span_to_hex_string_reversed(header_0.Hash().ToBytes()), "00000000000000000000325c7e14a4ee3b4fcb2343089a839287308a0ddbee4f");
710 BlockHeader header_1{hex_string_to_byte_vec("00c00020e7cb7b4de21d26d55bd384017b8bb9333ac3b2b55bed00000000000000000000d91b4484f801b99f03d36b9d26cfa83420b67f81da12d7e6c1e7f364e743c5ba9946e268b4dd011799c8533d")};
711 CheckHandle(header_0, header_1);
712
713 // Test all header field accessors using mainnet block 1
714 auto mainnet_block_1_header = hex_string_to_byte_vec("010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e36299");
715 BlockHeader header{mainnet_block_1_header};
716 BOOST_CHECK_EQUAL(header.Version(), 1);
717 BOOST_CHECK_EQUAL(header.Timestamp(), 1231469665);
718 BOOST_CHECK_EQUAL(header.Bits(), 0x1d00ffff);
719 BOOST_CHECK_EQUAL(header.Nonce(), 2573394689);
720 BOOST_CHECK_EQUAL(byte_span_to_hex_string_reversed(header.Hash().ToBytes()), "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048");
721 auto prev_hash = header.PrevHash();
722 BOOST_CHECK_EQUAL(byte_span_to_hex_string_reversed(prev_hash.ToBytes()), "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f");
723
724 // Test round-trip serialization of block header
725 auto header_roundtrip{BlockHeader{header.ToBytes()}};
726 check_equal(header_roundtrip.ToBytes(), mainnet_block_1_header);
727
728 auto raw_block = hex_string_to_byte_vec("010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e362990101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000");
729 Block block{raw_block};
730 BlockHeader block_header{block.GetHeader()};
731 BOOST_CHECK_EQUAL(block_header.Version(), 1);
732 BOOST_CHECK_EQUAL(block_header.Timestamp(), 1231469665);
733 BOOST_CHECK_EQUAL(block_header.Bits(), 0x1d00ffff);
734 BOOST_CHECK_EQUAL(block_header.Nonce(), 2573394689);
735 BOOST_CHECK_EQUAL(byte_span_to_hex_string_reversed(block_header.Hash().ToBytes()), "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048");
736
737 // Verify header from block serializes to first 80 bytes of raw block
738 auto block_header_bytes = block_header.ToBytes();
739 BOOST_CHECK_EQUAL(block_header_bytes.size(), 80);
740 check_equal(block_header_bytes, std::span<const std::byte>(raw_block.data(), 80));
741}
742
744{
747 CheckHandle(block, block_100);
749 CheckRange(block_tx.Transactions(), block_tx.CountTransactions());
750 auto transactions{block_tx.Transactions()};
751 auto transactions_copy{transactions};
752 BOOST_CHECK(transactions.begin() == transactions_copy.begin());
753 BOOST_CHECK(transactions.begin() == block_tx.Transactions().begin());
754 auto transaction_it{transactions.begin()};
755 BOOST_CHECK((*transaction_it).Txid() == block_tx.GetTransaction(0).Txid());
756 auto invalid_data = hex_string_to_byte_vec("012300");
757 BOOST_CHECK_THROW(Block{invalid_data}, std::runtime_error);
758 auto empty_data = hex_string_to_byte_vec("");
759 BOOST_CHECK_THROW(Block{empty_data}, std::runtime_error);
760}
761
762Context create_context(std::shared_ptr<TestKernelNotifications> notifications, ChainType chain_type, std::shared_ptr<TestValidationInterface> validation_interface = nullptr)
763{
764 ContextOptions options{};
765 ChainParams params{chain_type};
766 options.SetChainParams(params);
767 options.SetNotifications(notifications);
768 if (validation_interface) {
769 options.SetValidationInterface(validation_interface);
770 }
771 auto context{Context{options}};
772 return context;
773}
774
775BOOST_AUTO_TEST_CASE(btck_chainman_tests)
776{
777 Logger logger{std::make_unique<TestLog>()};
778 auto test_directory{TestDirectory{"chainman_test_bitcoin_kernel"}};
779
780 { // test with default context
781 Context context{};
782 ChainstateManagerOptions chainman_opts{context, PathToString(test_directory.m_directory), PathToString(test_directory.m_directory / "blocks")};
783 ChainMan chainman{context, chainman_opts};
784 }
785
786 { // test with default context options
787 ContextOptions options{};
788 Context context{options};
789 ChainstateManagerOptions chainman_opts{context, PathToString(test_directory.m_directory), PathToString(test_directory.m_directory / "blocks")};
790 ChainMan chainman{context, chainman_opts};
791 }
792 { // null or empty data_directory or blocks_directory are not allowed
793 Context context{};
794 auto valid_dir{PathToString(test_directory.m_directory)};
795 std::vector<std::pair<std::string_view, std::string_view>> illegal_cases{
796 {"", valid_dir},
797 {valid_dir, {nullptr, 0}},
798 {"", ""},
799 {{nullptr, 0}, {nullptr, 0}},
800 };
801 for (auto& [data_dir, blocks_dir] : illegal_cases) {
802 BOOST_CHECK_THROW(ChainstateManagerOptions(context, data_dir, blocks_dir),
803 std::runtime_error);
804 };
805 }
806
807 auto notifications{std::make_shared<TestKernelNotifications>()};
808 auto context{create_context(notifications, ChainType::MAINNET)};
809
810 ChainstateManagerOptions chainman_opts{context, PathToString(test_directory.m_directory), PathToString(test_directory.m_directory / "blocks")};
811 chainman_opts.SetWorkerThreads(4);
812 BOOST_CHECK(!chainman_opts.SetDatabaseCacheBytes(4_MiB - 1));
813 if constexpr (sizeof(void*) == 4) BOOST_CHECK(!chainman_opts.SetDatabaseCacheBytes(2_GiB));
814 BOOST_CHECK(chainman_opts.SetDatabaseCacheBytes(4_MiB));
815 BOOST_CHECK(!chainman_opts.SetWipeDbs(/*wipe_block_tree=*/true, /*wipe_chainstate=*/false));
816 BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/true, /*wipe_chainstate=*/true));
817 BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/true));
818 BOOST_CHECK(chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/false));
819 ChainMan chainman{context, chainman_opts};
820}
821
822std::unique_ptr<ChainMan> create_chainman(TestDirectory& test_directory,
823 bool reindex,
824 bool wipe_chainstate,
825 bool block_tree_db_in_memory,
826 bool chainstate_db_in_memory,
827 Context& context)
828{
829 ChainstateManagerOptions chainman_opts{context, PathToString(test_directory.m_directory), PathToString(test_directory.m_directory / "blocks")};
830
831 if (reindex) {
832 chainman_opts.SetWipeDbs(/*wipe_block_tree=*/reindex, /*wipe_chainstate=*/reindex);
833 }
834 if (wipe_chainstate) {
835 chainman_opts.SetWipeDbs(/*wipe_block_tree=*/false, /*wipe_chainstate=*/wipe_chainstate);
836 }
837 if (block_tree_db_in_memory) {
838 chainman_opts.UpdateBlockTreeDbInMemory(block_tree_db_in_memory);
839 }
840 if (chainstate_db_in_memory) {
841 chainman_opts.UpdateChainstateDbInMemory(chainstate_db_in_memory);
842 }
843
844 auto chainman{std::make_unique<ChainMan>(context, chainman_opts)};
845 return chainman;
846}
847
849{
850 auto notifications{std::make_shared<TestKernelNotifications>()};
851 auto context{create_context(notifications, ChainType::MAINNET)};
852 auto chainman{create_chainman(
853 test_directory, /*reindex=*/true, /*wipe_chainstate=*/false,
854 /*block_tree_db_in_memory=*/false, /*chainstate_db_in_memory=*/false, context)};
855
856 std::vector<std::string> import_files;
857 BOOST_CHECK(chainman->ImportBlocks(import_files));
858
859 // Sanity check some block retrievals
860 auto chain{chainman->GetChain()};
861 BOOST_CHECK_THROW(chain.GetByHeight(1000), std::runtime_error);
862 auto genesis_index{chain.Entries().front()};
863 BOOST_CHECK(!genesis_index.GetPrevious());
864 auto genesis_block_raw{chainman->ReadBlock(genesis_index).value().ToBytes()};
865 auto first_index{chain.GetByHeight(0)};
866 auto first_block_raw{chainman->ReadBlock(genesis_index).value().ToBytes()};
867 check_equal(genesis_block_raw, first_block_raw);
868 auto height{first_index.GetHeight()};
869 BOOST_CHECK_EQUAL(height, 0);
870
871 auto next_index{chain.GetByHeight(first_index.GetHeight() + 1)};
872 BOOST_CHECK(chain.Contains(next_index));
873 auto next_block_data{chainman->ReadBlock(next_index).value().ToBytes()};
874 auto tip_index{chain.Entries().back()};
875 auto tip_block_data{chainman->ReadBlock(tip_index).value().ToBytes()};
876 auto second_index{chain.GetByHeight(1)};
877 auto second_block{chainman->ReadBlock(second_index).value()};
878 auto second_block_data{second_block.ToBytes()};
879 auto second_height{second_index.GetHeight()};
880 BOOST_CHECK_EQUAL(second_height, 1);
881 check_equal(next_block_data, tip_block_data);
882 check_equal(next_block_data, second_block_data);
883
884 auto second_hash{second_index.GetHash()};
885 auto another_second_index{chainman->GetBlockTreeEntry(second_hash)};
886 BOOST_CHECK(another_second_index);
887 auto another_second_height{another_second_index->GetHeight()};
888 auto second_block_hash{second_block.GetHash()};
889 check_equal(second_block_hash.ToBytes(), second_hash.ToBytes());
890 BOOST_CHECK_EQUAL(second_height, another_second_height);
891}
892
894{
895 auto notifications{std::make_shared<TestKernelNotifications>()};
896 auto context{create_context(notifications, ChainType::MAINNET)};
897 auto chainman{create_chainman(
898 test_directory, /*reindex=*/false, /*wipe_chainstate=*/true,
899 /*block_tree_db_in_memory=*/false, /*chainstate_db_in_memory=*/false, context)};
900
901 std::vector<std::string> import_files;
902 import_files.push_back(PathToString(test_directory.m_directory / "blocks" / "blk00000.dat"));
903 BOOST_CHECK(chainman->ImportBlocks(import_files));
904}
905
907{
908 auto notifications{std::make_shared<TestKernelNotifications>()};
909 auto validation_interface{std::make_shared<TestValidationInterface>()};
910 auto context{create_context(notifications, ChainType::MAINNET, validation_interface)};
911 auto chainman{create_chainman(
912 test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
913 /*block_tree_db_in_memory=*/false, /*chainstate_db_in_memory=*/false, context)};
914
915 // mainnet block 1
916 auto raw_block = hex_string_to_byte_vec("010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e362990101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000");
917 Block block{raw_block};
918 BlockHeader header{block.GetHeader()};
919 TransactionView tx{block.GetTransaction(block.CountTransactions() - 1)};
920 BOOST_CHECK_EQUAL(byte_span_to_hex_string_reversed(tx.Txid().ToBytes()), "0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098");
921 BOOST_CHECK_EQUAL(header.Version(), 1);
922 BOOST_CHECK_EQUAL(header.Timestamp(), 1231469665);
923 BOOST_CHECK_EQUAL(header.Bits(), 0x1d00ffff);
924 BOOST_CHECK_EQUAL(header.Nonce(), 2573394689);
925 BOOST_CHECK_EQUAL(tx.CountInputs(), 1);
926 Transaction tx2 = tx;
928 for (auto transaction : block.Transactions()) {
929 BOOST_CHECK_EQUAL(transaction.CountInputs(), 1);
930 }
931 auto output_counts = *(block.Transactions() | std::views::transform([](const auto& tx) {
932 return tx.CountOutputs();
933 })).begin();
934 BOOST_CHECK_EQUAL(output_counts, 1);
935
936 validation_interface->m_expected_valid_block.emplace(raw_block);
937 auto ser_block{block.ToBytes()};
938 check_equal(ser_block, raw_block);
939 bool new_block = false;
940 BOOST_CHECK(chainman->ProcessBlock(block, &new_block));
941 BOOST_CHECK(new_block);
942
943 validation_interface->m_expected_valid_block = std::nullopt;
944 new_block = false;
946 BOOST_CHECK(!chainman->ProcessBlock(invalid_block, &new_block));
947 BOOST_CHECK(!new_block);
948
949 auto chain{chainman->GetChain()};
950 BOOST_CHECK_EQUAL(chain.Height(), 1);
951 auto tip{chain.Entries().back()};
952 auto read_block{chainman->ReadBlock(tip)};
953 BOOST_REQUIRE(read_block);
954 check_equal(read_block.value().ToBytes(), raw_block);
955
956 // Check that we can read the previous block
957 BlockTreeEntry tip_2{*tip.GetPrevious()};
958 Block read_block_2{*chainman->ReadBlock(tip_2)};
959 BOOST_CHECK_EQUAL(chainman->ReadBlockSpentOutputs(tip_2).Count(), 0);
960 BOOST_CHECK_EQUAL(chainman->ReadBlockSpentOutputs(tip).Count(), 0);
961
962 // It should be an error if we go another block back, since the genesis has no ancestor
963 BOOST_CHECK(!tip_2.GetPrevious());
964
965 // If we try to validate it again, it should be a duplicate
966 BOOST_CHECK(chainman->ProcessBlock(block, &new_block));
967 BOOST_CHECK(!new_block);
968}
969
970BOOST_AUTO_TEST_CASE(btck_check_block_context_free)
971{
972 constexpr size_t MERKLE_ROOT_OFFSET{4 + 32};
973 constexpr size_t NBITS_OFFSET{4 + 32 + 32 + 4};
974 constexpr size_t COINBASE_PREVOUT_N_OFFSET{4 + 32 + 32 + 4 + 4 + 4 + 1 + 4 + 1 + 32};
975
976 // Mainnet block 1
977 auto raw_block = hex_string_to_byte_vec("010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e362990101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781e62294721166bf621e73a82cbf2342c858eeac00000000");
978
979 // Context-free block checks still need consensus params for the optional
980 // proof-of-work validation path.
981 ChainParams mainnet_params{ChainType::MAINNET};
982 auto consensus_params = mainnet_params.GetConsensusParams();
983
984 Block block{raw_block};
986
987 BOOST_CHECK(block.Check(consensus_params, BlockCheckFlags::BASE, state));
988 BOOST_CHECK(state.GetValidationMode() == ValidationMode::VALID);
989
990 BOOST_CHECK(block.Check(consensus_params, BlockCheckFlags::ALL, state));
991 BOOST_CHECK(state.GetValidationMode() == ValidationMode::VALID);
992
993 auto bad_merkle_block_data = raw_block;
994 bad_merkle_block_data[MERKLE_ROOT_OFFSET] ^= std::byte{0x01};
995 Block bad_merkle_block{bad_merkle_block_data};
996
997 BOOST_CHECK(!bad_merkle_block.Check(consensus_params, BlockCheckFlags::MERKLE, state));
999 BOOST_CHECK(state.GetBlockValidationResult() == BlockValidationResult::MUTATED);
1000
1001 BOOST_CHECK(bad_merkle_block.Check(consensus_params, BlockCheckFlags::BASE, state));
1002 BOOST_CHECK(state.GetValidationMode() == ValidationMode::VALID);
1003
1004 auto bad_pow_block_data = raw_block;
1005 bad_pow_block_data[NBITS_OFFSET + 3] = std::byte{0x1c};
1006 Block bad_pow_block{bad_pow_block_data};
1007
1008 BOOST_CHECK(!bad_pow_block.Check(consensus_params, BlockCheckFlags::POW, state));
1010 BOOST_CHECK(state.GetBlockValidationResult() == BlockValidationResult::INVALID_HEADER);
1011
1012 BOOST_CHECK(bad_pow_block.Check(consensus_params, BlockCheckFlags::MERKLE, state));
1013 BOOST_CHECK(state.GetValidationMode() == ValidationMode::VALID);
1014
1015 auto bad_base_block_data = raw_block;
1016 bad_base_block_data[COINBASE_PREVOUT_N_OFFSET] = std::byte{0x00};
1017 Block bad_base_block{bad_base_block_data};
1018
1019 BOOST_CHECK(!bad_base_block.Check(consensus_params, BlockCheckFlags::BASE, state));
1021 BOOST_CHECK(state.GetBlockValidationResult() == BlockValidationResult::CONSENSUS);
1022
1023 // Test with invalid truncated block data.
1024 auto truncated_block_data = hex_string_to_byte_vec("010000006fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e61bc6649ffff001d01e36299");
1025 BOOST_CHECK_EXCEPTION(Block{truncated_block_data}, std::runtime_error,
1026 HasReason{"failed to instantiate btck object"});
1027}
1028
1029BOOST_AUTO_TEST_CASE(btck_chainman_mainnet_tests)
1030{
1031 auto test_directory{TestDirectory{"mainnet_test_bitcoin_kernel"}};
1032 chainman_mainnet_validation_test(test_directory);
1033 chainman_reindex_test(test_directory);
1034 chainman_reindex_chainstate_test(test_directory);
1035}
1036
1037BOOST_AUTO_TEST_CASE(btck_block_hash_tests)
1038{
1039 std::array<std::byte, 32> test_hash;
1040 std::array<std::byte, 32> test_hash_2;
1041 for (int i = 0; i < 32; ++i) {
1042 test_hash[i] = static_cast<std::byte>(i);
1043 test_hash_2[i] = static_cast<std::byte>(i + 1);
1044 }
1045 BlockHash block_hash{test_hash};
1046 BlockHash block_hash_2{test_hash_2};
1047 BOOST_CHECK(block_hash != block_hash_2);
1048 BOOST_CHECK(block_hash == block_hash);
1049 CheckHandle(block_hash, block_hash_2);
1050}
1051
1052BOOST_AUTO_TEST_CASE(btck_block_tree_entry_tests)
1053{
1054 auto test_directory{TestDirectory{"block_tree_entry_test_bitcoin_kernel"}};
1055 auto notifications{std::make_shared<TestKernelNotifications>()};
1056 auto context{create_context(notifications, ChainType::REGTEST)};
1057 auto chainman{create_chainman(
1058 test_directory,
1059 /*reindex=*/false,
1060 /*wipe_chainstate=*/false,
1061 /*block_tree_db_in_memory=*/true,
1062 /*chainstate_db_in_memory=*/true,
1063 context)};
1064
1065 // Process a couple of blocks
1066 for (size_t i{0}; i < 3; i++) {
1068 bool new_block{false};
1069 chainman->ProcessBlock(block, &new_block);
1070 BOOST_CHECK(new_block);
1071 }
1072
1073 auto chain{chainman->GetChain()};
1074 auto entry_0{chain.GetByHeight(0)};
1075 auto entry_1{chain.GetByHeight(1)};
1076 auto entry_2{chain.GetByHeight(2)};
1077
1078 // Test inequality
1079 BOOST_CHECK(entry_0 != entry_1);
1080 BOOST_CHECK(entry_1 != entry_2);
1081 BOOST_CHECK(entry_0 != entry_2);
1082
1083 // Test equality with same entry
1084 BOOST_CHECK(entry_0 == chain.GetByHeight(0));
1085 BOOST_CHECK(entry_0 == BlockTreeEntry{entry_0});
1086 BOOST_CHECK(entry_1 == entry_1);
1087
1088 // Test GetPrevious
1089 auto prev{entry_1.GetPrevious()};
1090 BOOST_CHECK(prev.has_value());
1091 BOOST_CHECK(prev.value() == entry_0);
1092
1093 // Test GetAncestor
1094 BOOST_CHECK(entry_2.GetAncestor(2) == entry_2);
1095 BOOST_CHECK(entry_2.GetAncestor(1) == entry_1);
1096 BOOST_CHECK(entry_2.GetAncestor(0) == entry_0);
1097}
1098
1099BOOST_AUTO_TEST_CASE(btck_chainman_in_memory_tests)
1100{
1101 auto in_memory_test_directory{TestDirectory{"in-memory_test_bitcoin_kernel"}};
1102
1103 auto notifications{std::make_shared<TestKernelNotifications>()};
1104 auto context{create_context(notifications, ChainType::REGTEST)};
1105 auto chainman{create_chainman(
1106 in_memory_test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
1107 /*block_tree_db_in_memory=*/true, /*chainstate_db_in_memory=*/true, context)};
1108
1109 for (auto& raw_block : REGTEST_BLOCK_DATA) {
1110 Block block{hex_string_to_byte_vec(raw_block)};
1111 bool new_block{false};
1112 chainman->ProcessBlock(block, &new_block);
1113 BOOST_CHECK(new_block);
1114 }
1115
1116 BOOST_CHECK(fs::exists(in_memory_test_directory.m_directory / "blocks"));
1117 BOOST_CHECK(!fs::exists(in_memory_test_directory.m_directory / "blocks" / "index"));
1118 BOOST_CHECK(!fs::exists(in_memory_test_directory.m_directory / "chainstate"));
1119
1120 BOOST_CHECK(context.interrupt());
1121}
1122
1123BOOST_AUTO_TEST_CASE(btck_chainman_regtest_tests)
1124{
1125 auto test_directory{TestDirectory{"regtest_test_bitcoin_kernel"}};
1126
1127 auto notifications{std::make_shared<TestKernelNotifications>()};
1128 auto context{create_context(notifications, ChainType::REGTEST)};
1129
1130 {
1131 auto chainman{create_chainman(
1132 test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
1133 /*block_tree_db_in_memory=*/false, /*chainstate_db_in_memory=*/false, context)};
1134 for (const auto& data : REGTEST_BLOCK_DATA) {
1136 BlockHeader header = block.GetHeader();
1137 BlockValidationState state = chainman->ProcessBlockHeader(header);
1138 BOOST_CHECK(state.GetValidationMode() == ValidationMode::VALID);
1139 BOOST_CHECK(state.GetBlockValidationResult() == BlockValidationResult::UNSET);
1140 BlockTreeEntry entry{*chainman->GetBlockTreeEntry(header.Hash())};
1141 BOOST_CHECK(!chainman->GetChain().Contains(entry));
1142 BlockTreeEntry best_entry{chainman->GetBestEntry()};
1143 BlockHash hash{entry.GetHash()};
1144 BOOST_CHECK(hash == best_entry.GetHeader().Hash());
1145 }
1146 }
1147
1148 // Validate 206 regtest blocks in total.
1149 // Stop halfway to check that it is possible to continue validating starting
1150 // from prior state.
1151 const size_t mid{REGTEST_BLOCK_DATA.size() / 2};
1152
1153 {
1154 auto chainman{create_chainman(
1155 test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
1156 /*block_tree_db_in_memory=*/false, /*chainstate_db_in_memory=*/false, context)};
1157 for (size_t i{0}; i < mid; i++) {
1159 bool new_block{false};
1160 BOOST_CHECK(chainman->ProcessBlock(block, &new_block));
1161 BOOST_CHECK(new_block);
1162 }
1163 }
1164
1165 auto chainman{create_chainman(
1166 test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
1167 /*block_tree_db_in_memory=*/false, /*chainstate_db_in_memory=*/false, context)};
1168
1169 for (size_t i{mid}; i < REGTEST_BLOCK_DATA.size(); i++) {
1171 bool new_block{false};
1172 BOOST_CHECK(chainman->ProcessBlock(block, &new_block));
1173 BOOST_CHECK(new_block);
1174 }
1175
1176 auto chain = chainman->GetChain();
1177 auto tip = chain.Entries().back();
1178 auto read_block = chainman->ReadBlock(tip).value();
1179 check_equal(read_block.ToBytes(), hex_string_to_byte_vec(REGTEST_BLOCK_DATA[REGTEST_BLOCK_DATA.size() - 1]));
1180
1181 auto tip_2 = tip.GetPrevious().value();
1182 auto read_block_2 = chainman->ReadBlock(tip_2).value();
1183 check_equal(read_block_2.ToBytes(), hex_string_to_byte_vec(REGTEST_BLOCK_DATA[REGTEST_BLOCK_DATA.size() - 2]));
1184
1185 Txid txid = read_block.Transactions()[0].Txid();
1186 Txid txid_2 = read_block_2.Transactions()[0].Txid();
1187 BOOST_CHECK(txid != txid_2);
1188 BOOST_CHECK(txid == txid);
1189 CheckHandle(txid, txid_2);
1190
1191 auto find_transaction = [&chainman](const TxidView& target_txid) -> std::optional<Transaction> {
1192 auto chain = chainman->GetChain();
1193 for (const auto block_tree_entry : chain.Entries()) {
1194 auto block{chainman->ReadBlock(block_tree_entry)};
1195 for (const TransactionView transaction : block->Transactions()) {
1196 if (transaction.Txid() == target_txid) {
1197 return Transaction{transaction};
1198 }
1199 }
1200 }
1201 return std::nullopt;
1202 };
1203
1204 for (const auto block_tree_entry : chain.Entries()) {
1205 auto block{chainman->ReadBlock(block_tree_entry)};
1206 for (const auto transaction : block->Transactions()) {
1207 std::vector<TransactionInput> inputs;
1208 std::vector<TransactionOutput> spent_outputs;
1209 for (const auto input : transaction.Inputs()) {
1210 OutPointView point = input.OutPoint();
1211 if (point.index() == std::numeric_limits<uint32_t>::max()) {
1212 continue;
1213 }
1214 inputs.emplace_back(input);
1215 BOOST_CHECK(point.Txid() != transaction.Txid());
1216 std::optional<Transaction> tx = find_transaction(point.Txid());
1217 BOOST_CHECK(tx.has_value());
1218 BOOST_CHECK(point.Txid() == tx->Txid());
1219 spent_outputs.emplace_back(tx->GetOutput(point.index()));
1220 }
1221 BOOST_CHECK(inputs.size() == spent_outputs.size());
1222 ScriptVerifyStatus status = ScriptVerifyStatus::OK;
1223 const PrecomputedTransactionData precomputed_txdata{transaction, spent_outputs};
1224 for (size_t i{0}; i < inputs.size(); ++i) {
1225 BOOST_CHECK(spent_outputs[i].GetScriptPubkey().Verify(spent_outputs[i].Amount(), transaction, &precomputed_txdata, i, ScriptVerificationFlags::ALL, status));
1226 }
1227 }
1228 }
1229
1230 // Read spent outputs for current tip and its previous block
1231 BlockSpentOutputs block_spent_outputs{chainman->ReadBlockSpentOutputs(tip)};
1232 BlockSpentOutputs block_spent_outputs_prev{chainman->ReadBlockSpentOutputs(*tip.GetPrevious())};
1233 CheckHandle(block_spent_outputs, block_spent_outputs_prev);
1234 CheckRange(block_spent_outputs_prev.TxsSpentOutputs(), block_spent_outputs_prev.Count());
1235 BOOST_CHECK_EQUAL(block_spent_outputs.Count(), 1);
1236
1237 // Get transaction spent outputs from the last transaction in the two blocks
1238 TransactionSpentOutputsView transaction_spent_outputs{block_spent_outputs.GetTxSpentOutputs(block_spent_outputs.Count() - 1)};
1239 TransactionSpentOutputs owned_transaction_spent_outputs{transaction_spent_outputs};
1240 TransactionSpentOutputs owned_transaction_spent_outputs_prev{block_spent_outputs_prev.GetTxSpentOutputs(block_spent_outputs_prev.Count() - 1)};
1241 CheckHandle(owned_transaction_spent_outputs, owned_transaction_spent_outputs_prev);
1242 CheckRange(transaction_spent_outputs.Coins(), transaction_spent_outputs.Count());
1243
1244 // Get the last coin from the transaction spent outputs
1245 CoinView coin{transaction_spent_outputs.GetCoin(transaction_spent_outputs.Count() - 1)};
1246 BOOST_CHECK(!coin.IsCoinbase());
1247 Coin owned_coin{coin};
1248 Coin owned_coin_prev{owned_transaction_spent_outputs_prev.GetCoin(owned_transaction_spent_outputs_prev.Count() - 1)};
1249 CheckHandle(owned_coin, owned_coin_prev);
1250
1251 // Validate coin properties
1252 TransactionOutputView output = coin.GetOutput();
1253 uint32_t coin_height = coin.GetConfirmationHeight();
1254 BOOST_CHECK_EQUAL(coin_height, 143);
1255 BOOST_CHECK_EQUAL(output.Amount(), 3949990974);
1256
1257 // Test script pubkey serialization
1258 auto script_pubkey = output.GetScriptPubkey();
1259 auto script_pubkey_bytes{script_pubkey.ToBytes()};
1260 BOOST_CHECK_EQUAL(script_pubkey_bytes.size(), 34);
1261 auto round_trip_script_pubkey{ScriptPubkey(script_pubkey_bytes)};
1262 BOOST_CHECK_EQUAL(round_trip_script_pubkey.ToBytes().size(), 34);
1263
1264 for (const auto tx_spent_outputs : block_spent_outputs.TxsSpentOutputs()) {
1265 for (const auto coins : tx_spent_outputs.Coins()) {
1266 BOOST_CHECK_GT(coins.GetOutput().Amount(), 1);
1267 }
1268 }
1269
1270 CheckRange(chain.Entries(), chain.CountEntries());
1271
1272 for (const BlockTreeEntry entry : chain.Entries()) {
1273 std::optional<Block> block{chainman->ReadBlock(entry)};
1274 if (block) {
1275 for (const TransactionView transaction : block->Transactions()) {
1276 for (const TransactionOutputView output : transaction.Outputs()) {
1277 // skip data carrier outputs
1278 if ((unsigned char)output.GetScriptPubkey().ToBytes()[0] == 0x6a) {
1279 continue;
1280 }
1281 BOOST_CHECK_GT(output.Amount(), 1);
1282 }
1283 }
1284 }
1285 }
1286
1287 int32_t count{0};
1288 for (const auto entry : chain.Entries()) {
1289 BOOST_CHECK_EQUAL(entry.GetHeight(), count);
1290 ++count;
1291 }
1292 BOOST_CHECK_EQUAL(count, chain.CountEntries());
1293
1294
1295 fs::remove(test_directory.m_directory / "blocks" / "blk00000.dat");
1296 BOOST_CHECK(!chainman->ReadBlock(tip_2).has_value());
1297 fs::remove(test_directory.m_directory / "blocks" / "rev00000.dat");
1298 BOOST_CHECK_THROW(chainman->ReadBlockSpentOutputs(tip), std::runtime_error);
1299}
1300
1301// -----------------------------------------------------------------------------
1302// CheckTransaction tests
1303//
1304// Transaction hex below is copied from src/test/data/tx_invalid.json (entries
1305// marked "BADTX") and tx_valid.json. CheckTransaction performs only basic context-free
1306// consensus checks and can only produce two outcomes:
1307// - VALID (ValidationMode::VALID, TxValidationResult::UNSET)
1308// - INVALID (ValidationMode::INVALID, TxValidationResult::CONSENSUS)
1309// Other TxValidationResult values are set by higher-level validation and are
1310// not reachable through btck_transaction_check.
1311// -----------------------------------------------------------------------------
1312BOOST_AUTO_TEST_CASE(btck_transaction_check_tests)
1313{
1314 using namespace btck;
1315
1316 constexpr std::string_view valid_tx_hex{
1317 "01000000010001000000000000000000000000000000000000000000000000000000000000"
1318 "000000006a473044022067288ea50aa799543a536ff9306f8e1cba05b9c6b10951175b92"
1319 "4f96732555ed022026d7b5265f38d21541519e4a1e55044d5b9e17e15cdbaf29ae3792e9"
1320 "9e883e7a012103ba8c8b86dea131c22ab967e6dd99bdae8eff7a1f75a2c35f1f944109e3"
1321 "fe5e22ffffffff010000000000000000015100000000"};
1322 constexpr std::string_view no_outputs_tx_hex{
1323 "01000000010001000000000000000000000000000000000000000000000000000000000000"
1324 "000000006d483045022100f16703104aab4e4088317c862daec83440242411b039d14280e0"
1325 "3dd33b487ab802201318a7be236672c5c56083eb7a5a195bc57a40af7923ff8545016cd3b5"
1326 "71e2a601232103c40e5d339df3f30bf753e7e04450ae4ef76c9e45587d1d993bdc4cd06f06"
1327 "51c7acffffffff0000000000"};
1328
1329 auto expect_valid = [](std::string_view hex) {
1333 BOOST_CHECK(st.GetValidationMode() == ValidationMode::VALID);
1334 BOOST_CHECK(st.GetTxValidationResult() == TxValidationResult::UNSET);
1335 };
1336
1337 auto expect_invalid = [](std::string_view hex) {
1340 BOOST_CHECK(!CheckTransaction(tx, st));
1342 BOOST_CHECK(st.GetTxValidationResult() == TxValidationResult::CONSENSUS);
1343 };
1344
1345 // Valid: simple 1-in 1-out transaction (from tx_valid.json)
1346 expect_valid(valid_tx_hex);
1347
1348 // Valid coinbase with scriptSig size 2 (from tx_valid.json)
1349 expect_valid(
1350 "01000000010000000000000000000000000000000000000000000000000000000000000000"
1351 "ffffffff025151ffffffff010000000000000000015100000000");
1352
1353 // No outputs (BADTX from tx_invalid.json)
1354 expect_invalid(no_outputs_tx_hex);
1355
1356 {
1357 Transaction valid_tx{hex_string_to_byte_vec(valid_tx_hex)};
1358 Transaction invalid_tx{hex_string_to_byte_vec(no_outputs_tx_hex)};
1359 TxValidationState state;
1360
1361 BOOST_CHECK(btck_transaction_check(valid_tx.get(), state.get()) == 1);
1362 BOOST_CHECK(state.GetValidationMode() == ValidationMode::VALID);
1363 BOOST_CHECK(state.GetTxValidationResult() == TxValidationResult::UNSET);
1364
1365 BOOST_CHECK(btck_transaction_check(invalid_tx.get(), state.get()) == 0);
1367 BOOST_CHECK(state.GetTxValidationResult() == TxValidationResult::CONSENSUS);
1368 }
1369
1370 // Negative output (BADTX)
1371 expect_invalid(
1372 "01000000010001000000000000000000000000000000000000000000000000000000000000"
1373 "000000006d4830450220063222cbb128731fc09de0d7323746539166544d6c1df84d867cce"
1374 "a84bcc8903022100bf568e8552844de664cd41648a031554327aa8844af34b4f27397c65b9"
1375 "2c04de0123210243ec37dee0e2e053a9c976f43147e79bc7d9dc606ea51010af1ac80db6b0"
1376 "69e1acffffffff01ffffffffffffffff015100000000");
1377
1378 // MAX_MONEY + 1 output (BADTX)
1379 expect_invalid(
1380 "01000000010001000000000000000000000000000000000000000000000000000000000000"
1381 "000000006e493046022100e1eadba00d9296c743cb6ecc703fd9ddc9b3cd12906176a226ae"
1382 "4c18d6b00796022100a71aef7d2874deff681ba6080f1b278bac7bb99c61b08a85f4311970"
1383 "ffe7f63f012321030c0588dc44d92bdcbf8e72093466766fdc265ead8db64517b0c542275b"
1384 "70fffbacffffffff010140075af0750700015100000000");
1385
1386 // MAX_MONEY output + 1 output: sum exceeds MAX_MONEY (BADTX)
1387 expect_invalid(
1388 "01000000010001000000000000000000000000000000000000000000000000000000000000"
1389 "000000006d483045022027deccc14aa6668e78a8c9da3484fbcd4f9dcc9bb7d1b85146314b"
1390 "21b9ae4d86022100d0b43dece8cfb07348de0ca8bc5b86276fa88f7f2138381128b7c36ab2"
1391 "e42264012321029bb13463ddd5d2cc05da6e84e37536cb9525703cfd8f43afdb414988987a"
1392 "92f6acffffffff020040075af075070001510001000000000000015100000000");
1393
1394 // Duplicate inputs (BADTX)
1395 expect_invalid(
1396 "01000000020001000000000000000000000000000000000000000000000000000000000000"
1397 "000000006c47304402204bb1197053d0d7799bf1b30cd503c44b58d6240cccbdc85b6fe76d"
1398 "087980208f02204beeed78200178ffc6c74237bb74b3f276bbb4098b5605d814304fe128bf"
1399 "1431012321039e8815e15952a7c3fada1905f8cf55419837133bd7756c0ef14fc8dfe50c0d"
1400 "eaacffffffff0001000000000000000000000000000000000000000000000000000000000000"
1401 "000000006c47304402202306489afef52a6f62e90bf750bbcdf40c06f5c6b138286e6b6b8617"
1402 "6bb9341802200dba98486ea68380f47ebb19a7df173b99e6bc9c681d6ccf3bde31465d1f16"
1403 "b3012321039e8815e15952a7c3fada1905f8cf55419837133bd7756c0ef14fc8dfe50c0dea"
1404 "acffffffff010000000000000000015100000000");
1405
1406 // Coinbase with scriptSig size 1: too small (BADTX)
1407 expect_invalid(
1408 "01000000010000000000000000000000000000000000000000000000000000000000000000"
1409 "ffffffff0151ffffffff010000000000000000015100000000");
1410
1411 // Coinbase with scriptSig size 101: too large (BADTX)
1412 expect_invalid(
1413 "01000000010000000000000000000000000000000000000000000000000000000000000000"
1414 "ffffffff6551515151515151515151515151515151515151515151515151515151515151515151"
1415 "515151515151515151515151515151515151515151515151515151515151515151515151515151"
1416 "51515151515151515151515151515151515151515151515151515151ffffffff01000000000000"
1417 "0000015100000000");
1418
1419 // Null prevout in non-coinbase: two inputs, one is null (BADTX)
1420 expect_invalid(
1421 "01000000020000000000000000000000000000000000000000000000000000000000000000"
1422 "ffffffff00ffffffff000100000000000000000000000000000000000000000000000000000000"
1423 "00000000000000ffffffff010000000000000000015100000000");
1424}
1425
1427{
1428public:
1429 explicit KernelMockTime(std::chrono::seconds timestamp) { set(timestamp); }
1431 {
1432 set_mock_time(std::chrono::seconds{0});
1433 }
1434
1437
1438 void set(std::chrono::seconds timestamp) { set_mock_time(timestamp); }
1439};
1440
1441BOOST_AUTO_TEST_CASE(btck_set_mock_time_tests)
1442{
1443 // Out-of-range timestamps throw
1444 BOOST_CHECK_EXCEPTION(set_mock_time(std::chrono::seconds{-1}), std::runtime_error, HasReason("timestamp out of range"));
1445 constexpr std::chrono::seconds max_time{std::numeric_limits<uint32_t>::max()};
1446 BOOST_CHECK_EXCEPTION(set_mock_time(max_time + std::chrono::seconds{1}), std::runtime_error, HasReason("timestamp out of range"));
1447
1448 // Confirm the mock time actually takes effect by exercising the header future-time check
1449 auto test_directory{TestDirectory{"set_mock_time_test_bitcoin_kernel"}};
1450 auto notifications{std::make_shared<TestKernelNotifications>()};
1451 auto context{create_context(notifications, ChainType::REGTEST)};
1452 auto chainman{create_chainman(
1453 test_directory, /*reindex=*/false, /*wipe_chainstate=*/false,
1454 /*block_tree_db_in_memory=*/true, /*chainstate_db_in_memory=*/true, context)};
1455
1457 BlockHeader header{block.GetHeader()};
1458 const std::chrono::seconds block_time{header.Timestamp()};
1459
1460 // With the time set 3h before the header, the kernel must see the header as >2h in the future and reject it
1461 KernelMockTime mock_time{block_time - std::chrono::hours{3}};
1462 BlockValidationState future_state{chainman->ProcessBlockHeader(header)};
1463 BOOST_CHECK(future_state.GetValidationMode() == ValidationMode::INVALID);
1464 BOOST_CHECK(future_state.GetBlockValidationResult() == BlockValidationResult::TIME_FUTURE);
1465
1466 // At the upper bound the header is far in the past and must be accepted; this also
1467 // confirms the future-time check's "now + 2h" computation doesn't overflow when now is at its max.
1468 mock_time.set(max_time);
1469 BlockValidationState ok_state{chainman->ProcessBlockHeader(header)};
1470 BOOST_CHECK(ok_state.GetValidationMode() == ValidationMode::VALID);
1471 BOOST_CHECK(ok_state.GetBlockValidationResult() == BlockValidationResult::UNSET);
1472}
int btck_transaction_check(const btck_Transaction *tx, btck_TxValidationState *validation_state)
constexpr std::array< std::string_view, 206 > REGTEST_BLOCK_DATA
Definition: block_data.h:9
BOOST_CHECK_EXCEPTION predicates to check the specific validation error.
Definition: common.h:19
KernelMockTime(std::chrono::seconds timestamp)
void set(std::chrono::seconds timestamp)
KernelMockTime & operator=(const KernelMockTime &)=delete
KernelMockTime(const KernelMockTime &)=delete
void HeaderTipHandler(SynchronizationState state, int64_t height, int64_t timestamp, bool presync) override
void FlushErrorHandler(std::string_view error) override
void FatalErrorHandler(std::string_view error) override
void LogMessage(std::string_view message)
Definition: test_kernel.cpp:98
void PowValidBlock(BlockTreeEntry entry, Block block) override
void BlockDisconnected(Block block, BlockTreeEntry entry) override
std::optional< std::string > m_expected_valid_block
void BlockChecked(Block block, BlockValidationStateView state) override
void BlockConnected(Block block, BlockTreeEntry entry) override
std::array< std::byte, 80 > ToBytes() const
std::vector< std::byte > ToBytes() const
std::optional< BlockTreeEntry > GetPrevious() const
ValidationMode GetValidationMode() const
BlockValidationResult GetBlockValidationResult() const
ConsensusParamsView GetConsensusParams() const
void SetWorkerThreads(int worker_threads)
uint32_t index() const
std::vector< std::byte > ToBytes() const
bool Verify(int64_t amount, const Transaction &tx_to, const PrecomputedTransactionData *precomputed_txdata, unsigned int input_index, ScriptVerificationFlags flags, ScriptVerifyStatus &status) const
std::vector< std::byte > ToBytes() const
WitnessStackView GetWitnessStack() const
std::vector< std::byte > GetScriptSig() const
ScriptPubkeyView GetScriptPubkey() const
TxValidationResult GetTxValidationResult() const
ValidationMode GetValidationMode() const
Txid(const TxidView &view)
const CType * get() const
std::vector< std::byte > GetItem(size_t index) const
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
static bool exists(const path &p)
Definition: fs.h:96
#define T(expected, seed, data)
BOOST_CHECK_GT(excessive_headers.size(), MAX_HEADERS_SIZE)
BOOST_CHECK_EQUAL(headers.FindFirst("key"), "value")
BOOST_CHECK_EXCEPTION(HTTPHeaders{}.Read(reader), std::runtime_error, HasReason{"Empty HTTP header name"})
@ ALL
Definition: categories.h:48
@ VALIDATION
Definition: categories.h:36
@ BENCH
Definition: categories.h:20
@ KERNEL
Definition: categories.h:46
void set_mock_time(std::chrono::seconds timestamp)
void logging_set_options(const btck_LoggingOptions &logging_options)
void logging_set_level_category(LogCategory category, LogLevel level)
void logging_enable_category(LogCategory category)
void logging_disable_category(LogCategory category)
const auto INVALID
A stack representing the lack of any (dis)satisfactions.
Definition: miniscript.h:353
#define BOOST_CHECK_THROW(stmt, excMatch)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:16
static bool Verify(const CScript &scriptSig, const CScript &scriptPubKey, bool fStrict, ScriptError &err)
fs::path m_directory
TestDirectory(std::string directory_name)
Options controlling the format of log messages.
int log_timestamps
Prepend a timestamp to log messages.
std::string byte_span_to_hex_string_reversed(std::span< const std::byte > bytes)
Definition: test_kernel.cpp:68
void chainman_reindex_chainstate_test(TestDirectory &test_directory)
Context create_context(std::shared_ptr< TestKernelNotifications > notifications, ChainType chain_type, std::shared_ptr< TestValidationInterface > validation_interface=nullptr)
void run_verify_test(const ScriptPubkey &spent_script_pubkey, const Transaction &spending_tx, const PrecomputedTransactionData *precomputed_txdata, int64_t amount, unsigned int input_index, bool taproot)
std::vector< std::byte > hex_string_to_byte_vec(std::string_view hex)
Definition: test_kernel.cpp:51
void chainman_reindex_test(TestDirectory &test_directory)
BOOST_AUTO_TEST_CASE(btck_transaction_tests)
void check_equal(std::span< const std::byte > _actual, std::span< const std::byte > _expected, bool equal=true)
Definition: test_kernel.cpp:86
void CheckHandle(T object, T distinct_object)
std::unique_ptr< ChainMan > create_chainman(TestDirectory &test_directory, bool reindex, bool wipe_chainstate, bool block_tree_db_in_memory, bool chainstate_db_in_memory, Context &context)
constexpr auto VERIFY_ALL_PRE_SEGWIT
Definition: test_kernel.cpp:81
void CheckRange(const RangeType &range, size_t expected_size)
void chainman_mainnet_validation_test(TestDirectory &test_directory)
std::string random_string(uint32_t length)
Definition: test_kernel.cpp:33
constexpr auto VERIFY_ALL_PRE_TAPROOT
Definition: test_kernel.cpp:84
static int count
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:19