From 6ce9fb1d0519a2708135f3eb7da8516e1bbada66 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Fri, 4 Dec 2026 15:05:56 +0000 Subject: [PATCH 1/3] Prep release/7.x context for clean cherry-pick of #8921 Temporarily align conflicting context in cft.h and test files with 25eaec325^ so #8921 cherry-picks cleanly. Reverted in the follow-up fixup commit. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8734db1e936445abbf809bd1a0477afa --- src/consensus/aft/cft.h | 3 + src/consensus/aft/test/main.cpp | 674 +++++++++++++ .../aft/test/view_straddling_common.h | 45 +- .../aft/test/view_straddling_history.cpp | 32 +- .../aft/test/view_straddling_rollback.cpp | 60 +- src/js/test/js.cpp | 451 ++++++++- src/kv/test/kv_serialisation.cpp | 25 +- src/kv/test/kv_test.cpp | 917 ++++++++++++++++-- src/node/rpc/test/node_frontend_test.cpp | 519 +++++++++- src/node/test/historical_queries.cpp | 301 ++++-- src/node/test/history.cpp | 473 ++++++++- src/node/test/snapshotter.cpp | 55 +- 12 files changed, 3215 insertions(+), 340 deletions(-) diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 159a68989038..204a8ac4c5a1 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -20,6 +20,7 @@ #include "tasks/periodic_task_owner.h" #include +#include #include #include #include @@ -2023,6 +2024,8 @@ namespace aft return; } + trace::tick(*state); + state->leadership_state.store(ccf::kv::LeadershipState::PreVoteCandidate); leader_id.reset(); diff --git a/src/consensus/aft/test/main.cpp b/src/consensus/aft/test/main.cpp index e49147a0b396..7ad54e2dfaae 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -1,7 +1,10 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. +#include "kv/store.h" +#include "kv/test/stub_consensus.h" #include "node/commit_callback_subsystem.h" +#include "service/tables/signatures.h" #include "test_common.h" #include @@ -57,6 +60,91 @@ DOCTEST_TEST_CASE( DOCTEST_CHECK(calls.size() == 3); } +DOCTEST_TEST_CASE( + "Retirement nomination excludes every peer confirmed in the batch" * + doctest::test_suite("retirement")) +{ + for (const auto self_id : {"1", "3"}) + { + const ccf::NodeId self{self_id}; + DOCTEST_INFO("Primary ID: ", self); + const ccf::NodeId survivor{"0"}; + const ccf::NodeId retiring_peer{"2"}; + auto kv_store = std::make_shared(self); + auto state = std::make_shared(self); + TCft cft( + cft_settings, + std::make_unique(kv_store), + std::make_unique(self), + std::make_shared(), + state, + nullptr); + aft::Configuration::Nodes config; + config[self] = {}; + config[survivor] = {}; + config[retiring_peer] = {}; + cft.add_configuration(0, config); + cft.force_become_primary(); + state->membership_state = ccf::kv::MembershipState::Retired; + state->retirement_phase = ccf::kv::RetirementPhase::Completed; + auto channels = channel_stub_proxy(cft); + channels->messages.clear(); + + std::vector confirmed = {self, retiring_peer}; + std::sort(confirmed.begin(), confirmed.end()); + cft.set_retired_committed(5, confirmed); + + DOCTEST_REQUIRE(channels->messages.size() == 1); + DOCTEST_CHECK(channels->messages.front().first == survivor); + DOCTEST_CHECK( + channels->count_messages_with_type(aft::propose_request_vote) == 1); + DOCTEST_CHECK(state->retired_committed_idx == 5); + DOCTEST_CHECK(cft.is_retired_committed()); + DOCTEST_CHECK_FALSE(cft.is_primary()); + } +} + +DOCTEST_TEST_CASE( + "Retired primary sends a single entry but not a heartbeat" * + doctest::test_suite("retirement")) +{ + const auto self = ccf::kv::test::PrimaryNodeId; + const auto peer = ccf::kv::test::FirstBackupNodeId; + auto kv_store = std::make_shared(self); + auto state = std::make_shared(self); + TCft cft( + cft_settings, + std::make_unique(kv_store), + std::make_unique(self), + std::make_shared(), + state, + nullptr); + aft::Configuration::Nodes config; + config[self] = {}; + config[peer] = {}; + cft.add_configuration(0, config); + cft.force_become_primary(); + auto channels = channel_stub_proxy(cft); + channels->messages.clear(); + auto entry = std::make_shared>(3, 1); + DOCTEST_REQUIRE(cft.replicate( + ccf::kv::BatchVector{{1, entry, true, hooks}}, cft.get_view())); + + // Synthetic state: committing retirement normally clears the primary role. + state->membership_state = ccf::kv::MembershipState::Retired; + state->retirement_phase = ccf::kv::RetirementPhase::RetiredCommitted; + cft.periodic(request_timeout); + auto message = channels->pop_first(aft::append_entries, peer); + DOCTEST_REQUIRE(message.has_value()); + const uint8_t* data = message->data(); + auto size = message->size(); + const auto ae = serialized::read(data, size); + DOCTEST_CHECK(ae.idx == 1); + DOCTEST_CHECK(ae.prev_idx == 0); + cft.periodic(request_timeout); + DOCTEST_CHECK(channels->messages.empty()); +} + DOCTEST_TEST_CASE("cft owns its periodic timer" * doctest::test_suite("single")) { const auto self = ccf::kv::test::PrimaryNodeId; @@ -1870,6 +1958,71 @@ DOCTEST_TEST_CASE( DOCTEST_REQUIRE(r0.is_primary()); } +DOCTEST_TEST_CASE( + "Nodes added by a rolled back configuration are forgotten" * + doctest::test_suite("multiple")) +{ + ccf::NodeId node_id0 = ccf::kv::test::PrimaryNodeId; + ccf::NodeId node_id1 = ccf::kv::test::FirstBackupNodeId; + ccf::NodeId node_id2 = ccf::kv::test::SecondBackupNodeId; + ccf::NodeId node_id3 = ccf::kv::test::ThirdBackupNodeId; + + TestNode node0(node_id0); + auto& r0 = node0.cft; + auto r0c = channel_stub_proxy(r0); + + aft::Configuration::Nodes config; + config[node_id0] = {}; + config[node_id1] = {}; + config[node_id2] = {}; + r0.add_configuration(0, config); + r0.force_become_primary(); + + DOCTEST_INFO( + "Node 2 retires: its retirement is committed, and not confirmed"); + config.erase(node_id2); + auto retire_hooks = std::make_shared(); + retire_hooks->push_back( + std::make_unique(config, 1)); + auto data = std::make_shared>(3, 1); + DOCTEST_REQUIRE(r0.replicate( + ccf::kv::BatchVector{{1, data, true, retire_hooks}}, r0.get_view())); + const auto ack = as_bytes(aft::AppendEntriesResponse{ + .term = r0.get_view(), + .last_log_idx = 1, + .success = aft::AppendEntriesResponseType::OK}); + r0.recv_message(node_id1, ack); + DOCTEST_REQUIRE(r0.get_committed_seqno() == 1); + DOCTEST_REQUIRE(r0.get_details().configs.size() == 1); + + DOCTEST_INFO("A configuration which is not committed adds node 3"); + config[node_id3] = {}; + auto trust_hooks = std::make_shared(); + trust_hooks->push_back( + std::make_unique(config, 2)); + DOCTEST_REQUIRE(r0.replicate( + ccf::kv::BatchVector{{2, data, true, trust_hooks}}, r0.get_view())); + DOCTEST_REQUIRE(r0.get_details().configs.size() == 2); + DOCTEST_REQUIRE(r0.get_details().acks.contains(node_id3)); + + DOCTEST_INFO("Once it is rolled back, no configuration names node 3"); + r0.rollback(1); + DOCTEST_REQUIRE(r0.get_details().configs.size() == 1); + DOCTEST_REQUIRE_FALSE(r0.get_details().acks.contains(node_id3)); + + DOCTEST_INFO( + "Node 1 is in the configuration which remains, and the retirement of " + "node 2 is still to confirm"); + DOCTEST_REQUIRE(r0.get_details().acks.contains(node_id1)); + DOCTEST_REQUIRE(r0.get_details().acks.contains(node_id2)); + r0c->messages.clear(); + r0.periodic(request_timeout); + DOCTEST_REQUIRE_FALSE( + r0c->pop_first(aft::append_entries, node_id3).has_value()); + DOCTEST_REQUIRE(r0c->pop_first(aft::append_entries, node_id1).has_value()); + DOCTEST_REQUIRE(r0c->pop_first(aft::append_entries, node_id2).has_value()); +} + DOCTEST_TEST_CASE( "cft messages that cannot be parsed are ignored" * doctest::test_suite("multiple")) @@ -3170,6 +3323,527 @@ DOCTEST_TEST_CASE( DOCTEST_REQUIRE(r0.ledger->ledger.size() == 1); } +DOCTEST_TEST_CASE( + "Nodes refuse a configuration with no nodes" * doctest::test_suite("single")) +{ + ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; + TestNode node(node_id); + auto& r0 = node.cft; + + aft::Configuration::Nodes config; + config[node_id] = {}; + r0.add_configuration(0, config); + + r0.start_ticking(); + r0.periodic(election_timeout * 2); + DOCTEST_REQUIRE(r0.is_primary()); + + auto entry = + std::make_shared>(std::vector{1, 2, 3}); + DOCTEST_REQUIRE( + r0.replicate(ccf::kv::BatchVector{{1, entry, true, hooks}}, 1)); + DOCTEST_REQUIRE(r0.get_committed_seqno() == 1); + + DOCTEST_INFO("The transaction which removes the only node is refused"); + auto removal_hooks = std::make_shared(); + removal_hooks->push_back(std::make_unique( + aft::Configuration::Nodes{}, 2)); + DOCTEST_REQUIRE_THROWS_WITH_AS( + r0.replicate(ccf::kv::BatchVector{{2, entry, false, removal_hooks}}, 1), + "Configuration at 2 has no nodes", + std::logic_error); + + DOCTEST_INFO("Nothing is appended, and the configuration is as it was"); + DOCTEST_REQUIRE(r0.get_last_idx() == 1); + DOCTEST_REQUIRE(r0.ledger->ledger.size() == 1); + const auto details = r0.get_details(); + DOCTEST_REQUIRE(details.configs.size() == 1); + DOCTEST_REQUIRE(details.configs.back().nodes == config); + DOCTEST_REQUIRE(details.membership_state == ccf::kv::MembershipState::Active); + DOCTEST_REQUIRE(r0.is_primary()); + + DOCTEST_INFO("A backup also refuses add_configuration with no nodes"); + TestNode backup(ccf::kv::test::FirstBackupNodeId); + backup.cft.add_configuration(0, config); + DOCTEST_REQUIRE_THROWS_WITH_AS( + backup.cft.add_configuration(2, {}), + "Configuration at 2 has no nodes", + std::logic_error); + DOCTEST_REQUIRE(backup.cft.get_details().configs.size() == 1); + DOCTEST_REQUIRE(backup.cft.get_details().configs.back().nodes == config); + + DOCTEST_INFO( + "A follower receiving an AppendEntries with an empty configuration " + "rolls back its KV, ledger, and configurations and NACKs"); + + using ValueMap = ccf::kv::Map; + using ConfigMap = ccf::kv::Map; + + class TermPreservingEncryptor : public ccf::kv::AbstractTxEncryptor + { + public: + bool encrypt( + const std::vector& plain, + const std::vector&, + std::vector& serialised_header, + std::vector& cipher, + const ccf::TxID& tx_id, + ccf::kv::EntryType = ccf::kv::EntryType::WriteSet, + bool = false) override + { + serialised_header.resize(sizeof(ccf::kv::Term)); + uint8_t* p = serialised_header.data(); + size_t s = serialised_header.size(); + serialized::write(p, s, tx_id.view); + cipher = plain; + return true; + } + + bool decrypt( + const std::vector& cipher, + const std::vector&, + const std::vector& serialised_header, + std::vector& plain, + ccf::kv::Version, + ccf::kv::Term& term, + bool = false) override + { + plain = cipher; + term = get_term(serialised_header.data(), serialised_header.size()); + return true; + } + + ccf::crypto::HashBytes get_commit_nonce( + const ccf::TxID&, bool = false) override + { + return {}; + } + + size_t get_header_length() override + { + return sizeof(ccf::kv::Term); + } + + uint64_t get_term(const uint8_t* data, size_t size) override + { + return serialized::read(data, size); + } + + void rollback(ccf::kv::Version) override {} + }; + + struct FollowerFixture + { + const ccf::NodeId primary_id = ccf::kv::test::PrimaryNodeId; + const ccf::NodeId follower_id = ccf::kv::test::FirstBackupNodeId; + const ccf::NodeId third_id = ccf::kv::test::SecondBackupNodeId; + + ValueMap values{"public:table"}; + ConfigMap configs{"public:test_config"}; + ccf::Signatures signatures{ccf::Tables::SIGNATURES}; + ccf::SerialisedMerkleTree serialised_tree{ + ccf::Tables::SERIALISED_MERKLE_TREE}; + + ccf::kv::Store sender_store; + std::shared_ptr sender_consensus = + std::make_shared(); + std::shared_ptr follower_store = + std::make_shared(); + std::shared_ptr follower_channels = + std::make_shared(); + aft::Aft follower; + std::vector> raw_entries; + + aft::Configuration::Nodes two_node_config; + aft::Configuration::Nodes three_node_config; + + FollowerFixture() : + follower( + cft_settings, + std::make_unique>(follower_store), + std::make_unique(follower_id), + follower_channels, + std::make_shared(follower_id), + nullptr) + { + auto encryptor = std::make_shared(); + sender_store.set_encryptor(encryptor); + sender_store.set_consensus(sender_consensus); + sender_store.initialise_term(1); + + follower_store->set_encryptor(encryptor); + follower_store->set_map_hook( + configs.get_name(), + configs.wrap_map_hook( + [](ccf::kv::Version v, const ConfigMap::Write& w) + -> ccf::kv::ConsensusHookPtr { + if (const auto it = w.find(0); + it != w.end() && it->second.has_value()) + { + return std::make_unique( + *it->second, v); + } + return nullptr; + })); + + two_node_config[primary_id] = {}; + two_node_config[follower_id] = {}; + three_node_config = two_node_config; + three_node_config[third_id] = {}; + + follower.add_configuration(0, two_node_config); + } + + ccf::kv::Version append_signature() + { + const auto txid = sender_store.next_txid(); + auto tx = sender_store.create_reserved_tx(txid); + tx.wo(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); + tx.wo(serialised_tree)->put({}); + auto [rc, data, claims_digest, commit_evidence_digest, tx_hooks] = + tx.commit_reserved(); + DOCTEST_REQUIRE(rc == ccf::kv::CommitResult::SUCCESS); + DOCTEST_REQUIRE( + sender_store.commit( + txid, + std::make_unique( + std::move(data), + std::move(claims_digest), + std::move(commit_evidence_digest), + std::move(tx_hooks)), + true) == ccf::kv::CommitResult::SUCCESS); + const auto replicated = sender_consensus->get_latest_data(); + DOCTEST_REQUIRE(replicated.has_value()); + raw_entries.push_back(*replicated); + return txid.seqno; + } + + ccf::kv::Version append_entry( + size_t key, + size_t value, + const std::optional& new_config = std::nullopt) + { + auto tx = sender_store.create_tx(); + tx.rw(values)->put(key, value); + if (new_config.has_value()) + { + tx.rw(configs)->put(0, *new_config); + } + DOCTEST_REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto replicated = sender_consensus->get_latest_data(); + DOCTEST_REQUIRE(replicated.has_value()); + raw_entries.push_back(*replicated); + return tx.commit_version(); + } + + void deliver( + aft::Index prev_idx, + aft::Index idx, + aft::Term prev_term, + aft::Index leader_commit_idx) + { + std::vector payload; + for (aft::Index i = prev_idx + 1; i <= idx; ++i) + { + const auto& entry = raw_entries.at(i - 1); + const size_t entry_size = entry.size(); + const size_t offset = payload.size(); + payload.resize(offset + sizeof(size_t) + entry_size); + uint8_t* ptr = payload.data() + offset; + size_t remaining = sizeof(size_t); + serialized::write(ptr, remaining, entry_size); + std::copy( + entry.begin(), + entry.end(), + payload.begin() + offset + sizeof(size_t)); + } + + aft::AppendEntries ae{}; + ae.idx = idx; + ae.prev_idx = prev_idx; + ae.term = 1; + ae.prev_term = prev_term; + ae.leader_commit_idx = leader_commit_idx; + ae.term_of_idx = 1; + follower.recv_message( + primary_id, + {reinterpret_cast(&ae), sizeof(ae)}, + payload); + } + + std::optional read_value(size_t key) + { + auto tx = follower_store->create_read_only_tx(); + return tx.ro(values)->get(key); + } + + aft::AppendEntriesResponse pop_response() + { + auto resp_msg = + follower_channels->pop_first(aft::append_entries_response, primary_id); + DOCTEST_REQUIRE(resp_msg.has_value()); + return read_msg(*resp_msg); + } + }; + + DOCTEST_SUBCASE("Preserves existing unsigned suffix on rollback") + { + FollowerFixture fx; + DOCTEST_REQUIRE(fx.append_signature() == 1); + DOCTEST_REQUIRE(fx.append_entry(2, 200, fx.three_node_config) == 2); + DOCTEST_REQUIRE(fx.append_entry(3, 300, fx.two_node_config) == 3); + DOCTEST_REQUIRE(fx.append_entry(4, 400, aft::Configuration::Nodes{}) == 4); + + fx.deliver(0, 1, 0, 1); + fx.deliver(1, 2, 1, 1); + DOCTEST_REQUIRE(fx.follower.get_last_idx() == 2); + DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 1); + DOCTEST_REQUIRE(fx.follower_store->current_version() == 2); + DOCTEST_REQUIRE(fx.read_value(2) == 200); + DOCTEST_REQUIRE(fx.follower.ledger->ledger.size() == 2); + fx.follower_channels->messages.clear(); + + fx.deliver(2, 4, 1, 1); + + DOCTEST_REQUIRE(fx.follower.get_last_idx() == 2); + DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 1); + DOCTEST_REQUIRE(fx.follower_store->current_version() == 2); + DOCTEST_REQUIRE(fx.read_value(2) == 200); + DOCTEST_REQUIRE_FALSE(fx.read_value(3).has_value()); + DOCTEST_REQUIRE_FALSE(fx.read_value(4).has_value()); + DOCTEST_REQUIRE(fx.follower.ledger->ledger.size() == 2); + const auto follower_details = fx.follower.get_details(); + DOCTEST_REQUIRE(follower_details.configs.size() == 2); + DOCTEST_REQUIRE(follower_details.configs[0].idx == 0); + DOCTEST_REQUIRE(follower_details.configs[0].nodes == fx.two_node_config); + DOCTEST_REQUIRE(follower_details.configs[1].idx == 2); + DOCTEST_REQUIRE(follower_details.configs[1].nodes == fx.three_node_config); + DOCTEST_REQUIRE( + follower_details.membership_state == ccf::kv::MembershipState::Active); + + const auto resp = fx.pop_response(); + DOCTEST_REQUIRE(resp.success == aft::AppendEntriesResponseType::FAIL); + DOCTEST_REQUIRE(resp.last_log_idx == 2); + } + + DOCTEST_SUBCASE( + "Preserves signature accepted earlier in the same AppendEntries batch") + { + FollowerFixture fx; + DOCTEST_REQUIRE(fx.append_signature() == 1); + DOCTEST_REQUIRE(fx.append_entry(2, 200, fx.three_node_config) == 2); + DOCTEST_REQUIRE(fx.append_signature() == 3); + DOCTEST_REQUIRE(fx.append_entry(4, 400, fx.two_node_config) == 4); + DOCTEST_REQUIRE(fx.append_entry(5, 500, aft::Configuration::Nodes{}) == 5); + + fx.deliver(0, 1, 0, 1); + DOCTEST_REQUIRE(fx.follower.get_last_idx() == 1); + DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 1); + DOCTEST_REQUIRE(fx.follower_store->current_version() == 1); + fx.follower_channels->messages.clear(); + + fx.deliver(1, 5, 1, 3); + + DOCTEST_REQUIRE(fx.follower.get_last_idx() == 3); + DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 3); + DOCTEST_REQUIRE(fx.follower_store->current_version() == 3); + DOCTEST_REQUIRE(fx.read_value(2) == 200); + DOCTEST_REQUIRE_FALSE(fx.read_value(4).has_value()); + DOCTEST_REQUIRE_FALSE(fx.read_value(5).has_value()); + DOCTEST_REQUIRE(fx.follower.ledger->ledger.size() == 3); + const auto follower_details = fx.follower.get_details(); + DOCTEST_REQUIRE(follower_details.configs.size() == 1); + DOCTEST_REQUIRE(follower_details.configs[0].idx == 2); + DOCTEST_REQUIRE(follower_details.configs[0].nodes == fx.three_node_config); + DOCTEST_REQUIRE( + follower_details.membership_state == ccf::kv::MembershipState::Active); + + const auto resp = fx.pop_response(); + DOCTEST_REQUIRE(resp.success == aft::AppendEntriesResponseType::FAIL); + DOCTEST_REQUIRE(resp.last_log_idx == 3); + } +} + +DOCTEST_TEST_CASE( + "Retired-committed node refuses forced leadership" * + doctest::test_suite("retirement")) +{ + PrimaryAndBackup n; + + aft::Configuration::Nodes peer_only; + peer_only[n.id1] = {}; + auto retire_hooks = std::make_shared(); + retire_hooks->push_back( + std::make_unique(peer_only, 1)); + auto entry = std::make_shared>(3, 1); + DOCTEST_REQUIRE(n.r0.replicate( + ccf::kv::BatchVector{{1, entry, false, retire_hooks}}, n.r0.get_view())); + n.replicate(2, 2, true); + + // Peer acknowledges the retirement and following signature so retirement + // commits on node 0 (RetirementPhase::Completed). + n.r0.periodic(request_timeout); + require_ack( + n.backup_receives(n.with_payload(n.take_append_entries_header())), 2); + n.primary_receives(aft::AppendEntriesResponse{ + .term = n.r0.get_view(), + .last_log_idx = 2, + .success = aft::AppendEntriesResponseType::OK}); + DOCTEST_REQUIRE(n.r0.get_committed_seqno() == 2); + DOCTEST_REQUIRE( + n.r0.get_details().retirement_phase == ccf::kv::RetirementPhase::Completed); + + n.r0.set_retired_committed(3, {n.id0}); + DOCTEST_REQUIRE(n.r0.is_retired_committed()); + DOCTEST_REQUIRE_FALSE(n.r0.is_primary()); + DOCTEST_REQUIRE_FALSE(n.r0.primary().has_value()); + + // Forcing leadership on a retired-committed node must not re-elect it. + n.r0.force_become_primary(); + DOCTEST_REQUIRE_FALSE(n.r0.is_primary()); + DOCTEST_REQUIRE_FALSE(n.r0.primary().has_value()); + DOCTEST_REQUIRE( + n.r0.get_details().leadership_state == ccf::kv::LeadershipState::None); +} + +DOCTEST_TEST_CASE( + "Backup rolls back and NACKs when a consensus hook throws a " + "non-std::exception" * + doctest::test_suite("multiple")) +{ + struct UnknownHookError + {}; + + class ThrowingHook : public ccf::kv::ConsensusHook + { + public: + void call(ccf::kv::ConfigurableConsensus*) override + { + throw UnknownHookError{}; + } + }; + + class ThrowingHookStore : public Store + { + public: + using Store::Store; + + aft::Index throw_at_idx = 0; + + std::unique_ptr deserialize( + const std::vector& data, + bool public_only = false, + const std::optional& expected_txid = std::nullopt) override + { + ccf::kv::ConsensusHookPtrs entry_hooks; + if (expected_txid.has_value() && expected_txid->seqno == throw_at_idx) + { + entry_hooks.push_back(std::make_unique()); + } + return std::make_unique( + data, expected_txid, std::move(entry_hooks)); + } + }; + + auto kv1 = + std::make_shared(ccf::kv::test::FirstBackupNodeId); + PrimaryAndBackup n({}, {.kv = kv1}); + + n.replicate(1, 1, true); + n.r0.periodic(request_timeout); + const auto ack = + n.backup_receives(n.with_payload(n.take_append_entries_header())); + require_ack(ack, 1); + n.primary_receives(ack.value()); + DOCTEST_REQUIRE(n.r1.get_last_idx() == 1); + + kv1->throw_at_idx = 3; + n.replicate(2, 3, false); + n.r0.periodic(request_timeout); + const auto nack = + n.backup_receives(n.with_payload(n.take_append_entries_header())); + require_nack(nack, 1); + DOCTEST_REQUIRE(n.r1.get_last_idx() == 1); + DOCTEST_REQUIRE(n.r1.ledger->ledger.size() == 1); +} + +DOCTEST_TEST_CASE( + "Follower retains conflicting suffix on a second conflict in the same term" * + doctest::test_suite("multiple")) +{ + PrimaryAndBackup n; + + // Commit entry 1.1 and replicate uncommitted entry 1.2 to the backup. + n.replicate(1, 1, true); + n.r0.periodic(request_timeout); + const auto ack1 = + n.backup_receives(n.with_payload(n.take_append_entries_header())); + require_ack(ack1, 1); + n.primary_receives(ack1.value()); + + n.replicate(2, 2, false); + n.r0.periodic(request_timeout); + const auto ack2 = + n.backup_receives(n.with_payload(n.take_append_entries_header())); + require_ack(ack2, 2); + DOCTEST_REQUIRE(n.r1.get_view(2) == 1); + DOCTEST_REQUIRE(n.r1.get_committed_seqno() == 1); + + // Helper to build a single-entry AppendEntries payload matching + // LoggingStubStore's wire format. + const auto make_ae_payload = + [](bool committable, aft::Term term, aft::Index idx) { + const std::vector body = {1, 2, 3}; + std::vector buf(sizeof(size_t) + aft::ADDITIONAL_METADATA_SIZE); + uint8_t* ptr = buf.data(); + size_t rem = buf.size(); + serialized::write(ptr, rem, aft::ADDITIONAL_METADATA_SIZE + body.size()); + serialized::write(ptr, rem, committable); + serialized::write(ptr, rem, term); + serialized::write(ptr, rem, idx); + buf.insert(buf.end(), body.begin(), body.end()); + return buf; + }; + + // First conflict in view 2: as a new follower in view 2, node 1 rolls back + // entry 1.2 and accepts 2.2 (clearing is_new_follower). + aft::AppendEntries term2_ae{}; + term2_ae.idx = 2; + term2_ae.prev_idx = 1; + term2_ae.term = 2; + term2_ae.prev_term = 1; + term2_ae.leader_commit_idx = 1; + term2_ae.term_of_idx = 2; + const auto term2_header = as_bytes(term2_ae); + const auto term2_payload = make_ae_payload(false, 2, 2); + n.r1.recv_message(n.id0, term2_header, term2_payload); + auto resp = n.c1->pop_first(aft::append_entries_response, n.id0); + DOCTEST_REQUIRE(resp.has_value()); + require_ack(read_msg(*resp), 2); + DOCTEST_REQUIRE(n.r1.get_view() == 2); + DOCTEST_REQUIRE(n.r1.get_view(2) == 2); + DOCTEST_REQUIRE(n.r1.primary() == n.id0); + + // Second conflicting AppendEntries in the same term (simulating an + // equivocating sender in view 2 claiming term_of_idx = 1 at index 2): + // is_new_follower is now false, so node 1 retains 2.2 without rolling back + // or sending a response. + const auto equivocator = ccf::kv::test::SecondBackupNodeId; + aft::AppendEntries conflicting_ae{}; + conflicting_ae.idx = 2; + conflicting_ae.prev_idx = 1; + conflicting_ae.term = 2; + conflicting_ae.prev_term = 1; + conflicting_ae.leader_commit_idx = 1; + conflicting_ae.term_of_idx = 1; + const auto conflicting_header = as_bytes(conflicting_ae); + const auto conflicting_payload = make_ae_payload(false, 1, 2); + n.r1.recv_message(equivocator, conflicting_header, conflicting_payload); + DOCTEST_REQUIRE(n.c1->messages.empty()); + DOCTEST_REQUIRE(n.r1.get_last_idx() == 2); + DOCTEST_REQUIRE(n.r1.get_view(2) == 2); +} + int main(int argc, char** argv) { doctest::Context context; diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index d424495e34cb..8b4e647a4ddd 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -8,6 +8,7 @@ #include "kv/null_encryptor.h" #include "kv/store.h" +#include "service/tables/signatures.h" #include "test_common.h" #include @@ -23,24 +24,29 @@ namespace straddling using TestMap = ccf::kv::Map; using Cft = aft::Aft; - class BaselinePendingTx : public ccf::kv::PendingTx + class SignaturePendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - TestMap& table; + uint8_t marker; public: - BaselinePendingTx( - ccf::TxID txid_, ccf::kv::Store& store_, TestMap& table_) : + SignaturePendingTx( + ccf::TxID txid_, ccf::kv::Store& store_, uint8_t marker_) : txid(txid_), store(store_), - table(table_) + marker(marker_) {} ccf::kv::PendingTxInfo call() override { auto tx = store.create_reserved_tx(txid); - tx.rw(table)->put(0, 1); + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {marker}); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({marker}); return tx.commit_reserved(); } }; @@ -159,6 +165,18 @@ namespace straddling return tx.ro(table)->get(key); } + static std::optional read_signature_seqno(ccf::kv::Store& store) + { + auto tx = store.create_read_only_tx_at_replicated_state(); + const auto signature = + tx.ro(ccf::Tables::SIGNATURES)->get(); + if (!signature.has_value()) + { + return std::nullopt; + } + return signature->seqno; + } + struct Fixture { const ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; @@ -191,19 +209,24 @@ namespace straddling cft->force_become_primary(); initial_view = cft->get_view(); + { + auto tx = store->create_tx(); + tx.rw(table)->put(0, 1); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } const auto baseline_txid = store->next_txid(); REQUIRE( store->commit( baseline_txid, - std::make_unique(baseline_txid, *store, table), + std::make_unique(baseline_txid, *store, 1), true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(store->current_txid() == ccf::TxID(initial_view, 1)); - REQUIRE(cft->get_committed_seqno() == 1); - REQUIRE(cft->ledger->ledger.size() == 1); + REQUIRE(store->current_txid() == ccf::TxID(initial_view, 2)); + REQUIRE(cft->get_committed_seqno() == 2); + REQUIRE(cft->ledger->ledger.size() == 2); } // Lose leadership, then win a later election. become_leader() rolls the - // Store back to the last committable index (1) under the new view. + // Store back to the last committable index (2) under the new view. ccf::View reelect() { cft->become_aware_of_new_term(cft->get_view() + 1); diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index c6913724ff93..60c35474bb9e 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -16,7 +16,7 @@ // // - Tx A passes Store::commit()'s view check under version_lock, which is // then released. -// - An election rolls the Store and the ledger history back to seqno 1. +// - An election rolls the Store and the ledger history back to seqno 2. // - A appends its digest to the history, then CFT rejects it. #include "node/history.h" @@ -82,16 +82,14 @@ TEST_CASE( const auto [baseline_txid, baseline_root, _] = fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(baseline_txid.seqno == 1); + REQUIRE(baseline_txid.seqno == 2); + REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); + REQUIRE(read_signature_seqno(*fixture.store) == baseline_txid.seqno); - INFO("Apply and serialise A at seqno 2 in the initial view"); + INFO("Apply and serialise A at seqno 3 in the initial view"); const auto stale_txid = fixture.store->next_txid(); - REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); - auto stale_info = [&]() { - auto tx = fixture.store->create_reserved_tx(stale_txid); - tx.rw(fixture.table)->put(1, 2); - return tx.commit_reserved(); - }(); + REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); + auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); INFO("A enters Store::commit, passes its view check, then is descheduled"); @@ -106,12 +104,12 @@ TEST_CASE( }); REQUIRE(commit_pause.wait_until_paused()); - INFO("Lose leadership and win a later election, rolling back to seqno 1"); + INFO("Lose leadership and win a later election, rolling back to seqno 2"); fixture.reelect(); { const auto [rolled_back_txid, rolled_back_root, rolled_back_term] = fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(rolled_back_txid.seqno == 1); + REQUIRE(rolled_back_txid.seqno == 2); REQUIRE(rolled_back_root == baseline_root); } @@ -122,7 +120,7 @@ TEST_CASE( { const auto [observed_txid, observed_root, observed_term] = fixture.history->get_replicated_state_txid_and_root(); - CHECK(observed_txid.seqno == 1); + CHECK(observed_txid.seqno == 2); CHECK(observed_root == baseline_root); } fixture.history->pause.release(); @@ -134,10 +132,12 @@ TEST_CASE( { const auto [final_txid, final_root, final_term] = fixture.history->get_replicated_state_txid_and_root(); - CHECK(final_txid.seqno == 1); + CHECK(final_txid.seqno == 2); CHECK(final_root == baseline_root); } - CHECK(fixture.store->current_txid().seqno == 1); - CHECK(fixture.cft->get_last_idx() == 1); - CHECK(fixture.cft->ledger->ledger.size() == 1); + CHECK(fixture.store->current_txid().seqno == 2); + CHECK(read_value(*fixture.store, fixture.table, 0) == 1); + CHECK(read_signature_seqno(*fixture.store) == baseline_txid.seqno); + CHECK(fixture.cft->get_last_idx() == 2); + CHECK(fixture.cft->ledger->ledger.size() == 2); } diff --git a/src/consensus/aft/test/view_straddling_rollback.cpp b/src/consensus/aft/test/view_straddling_rollback.cpp index 77ca65e9914d..85a1c0fd30bb 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -15,21 +15,23 @@ // Interleaving, from review of PR #8209 (cjen1-msft, // src/consensus/aft/cft.h): // -// - Tx A is applied locally in view V and given TxID V.2. It enters +// - Tx A is applied locally in view V and given TxID V.3. It enters // Store::commit(), passes the view check, and is descheduled before it // reaches CFT. // - An election happens. The node wins in view W > V, and become_leader() -// rolls the Store back past A, to seqno 1. -// - Tx B is applied locally in view W and given TxID W.2. It has not yet +// rolls the Store back past A, to seqno 2. +// - Tx B is applied locally in view W and given TxID W.3. It has not yet // entered Store::commit(). // - A continues. CFT rejects it. If that rejection rolls the Store -// back to CFT's last log index (1), it discards B's local application as +// back to CFT's last log index (2), it discards B's local application as // well. // - B enters Store::commit(), passes the view check (W == W), and is // replicated. It is in the ledger, but no longer in the KV. #include "view_straddling_common.h" +#include + using namespace straddling; namespace @@ -37,7 +39,7 @@ namespace std::string describe(Fixture& fixture) { const auto value = read_value(*fixture.store, fixture.table, 2); - return fmt::format( + return std::format( "store txid {}, key 2 -> {}, cft last_idx {}, ledger entries " "{}", fixture.store->current_txid().to_str(), @@ -55,16 +57,12 @@ TEST_CASE( Fixture fixture; fixture.start(); - INFO("Apply and serialise A at seqno 2 in the initial view"); + INFO("Apply and serialise A at seqno 3 in the initial view"); const auto stale_txid = fixture.store->next_txid(); - REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); - auto stale_info = [&]() { - auto tx = fixture.store->create_reserved_tx(stale_txid); - tx.rw(fixture.table)->put(1, 2); - return tx.commit_reserved(); - }(); + REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); + auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE(read_value(*fixture.store, fixture.table, 1) == 2); + REQUIRE(read_signature_seqno(*fixture.store) == 2); INFO("A enters Store::commit, passes its view check, then is descheduled"); CommitPause stale_pause; @@ -78,14 +76,15 @@ TEST_CASE( }); REQUIRE(stale_pause.wait_until_paused()); - INFO("Lose leadership and win a later election, rolling back to seqno 1"); + INFO("Lose leadership and win a later election, rolling back to seqno 2"); const auto reelection_view = fixture.reelect(); - REQUIRE(fixture.store->current_txid() == ccf::TxID(fixture.initial_view, 1)); - REQUIRE_FALSE(read_value(*fixture.store, fixture.table, 1).has_value()); - REQUIRE(fixture.cft->get_last_idx() == 1); + REQUIRE(fixture.store->current_txid() == ccf::TxID(fixture.initial_view, 2)); + REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); + REQUIRE(read_signature_seqno(*fixture.store) == 2); + REQUIRE(fixture.cft->get_last_idx() == 2); INFO( - "B is applied at seqno 2 in the new view, then pauses before " + "B is applied at seqno 3 in the new view, then pauses before " "Store::commit"); auto current_tx = fixture.store->create_tx(); current_tx.rw(fixture.table)->put(2, 3); @@ -97,8 +96,8 @@ TEST_CASE( [¤t_pause](const auto&, const auto&) { current_pause.pause(); }); }); REQUIRE(current_pause.wait_until_paused()); - REQUIRE(current_tx.get_txid() == ccf::TxID(reelection_view, 2)); - REQUIRE(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + REQUIRE(current_tx.get_txid() == ccf::TxID(reelection_view, 3)); + REQUIRE(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); REQUIRE(read_value(*fixture.store, fixture.table, 2) == 3); INFO( @@ -109,9 +108,9 @@ TEST_CASE( REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); MESSAGE("After A is rejected: " << describe(fixture)); - CHECK(fixture.cft->get_last_idx() == 1); - CHECK(fixture.cft->ledger->ledger.size() == 1); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + CHECK(fixture.cft->get_last_idx() == 2); + CHECK(fixture.cft->ledger->ledger.size() == 2); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); INFO("Resume B: whatever consensus decides, KV and ledger must agree"); @@ -120,10 +119,11 @@ TEST_CASE( REQUIRE(current_result.has_value()); CHECK(current_result.value() == ccf::kv::CommitResult::SUCCESS); MESSAGE("After B is replicated: " << describe(fixture)); - CHECK(fixture.cft->get_last_idx() == 2); - CHECK(fixture.cft->ledger->ledger.size() == 2); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); + CHECK(fixture.cft->get_last_idx() == 3); + CHECK(fixture.cft->ledger->ledger.size() == 3); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); + CHECK(read_signature_seqno(*fixture.store) == 2); INFO("The next transaction gets a fresh seqno and replicates normally"); auto next_tx = fixture.store->create_tx(); @@ -134,9 +134,9 @@ TEST_CASE( "After next tx " << (next_txid.has_value() ? next_txid->to_str() : std::string("none")) << ": " << describe(fixture)); - CHECK(next_txid == ccf::TxID(reelection_view, 3)); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); + CHECK(next_txid == ccf::TxID(reelection_view, 4)); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 4)); CHECK(read_value(*fixture.store, fixture.table, 3) == 4); - CHECK(fixture.cft->get_last_idx() == 3); - CHECK(fixture.cft->ledger->ledger.size() == 3); + CHECK(fixture.cft->get_last_idx() == 4); + CHECK(fixture.cft->ledger->ledger.size() == 4); } diff --git a/src/js/test/js.cpp b/src/js/test/js.cpp index 0b1c4d4b43e0..84fec46b340d 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -2,6 +2,7 @@ // Licensed under the Apache 2.0 License. #include "ccf/crypto/ec_key_pair.h" #include "ccf/ds/x509_time_fmt.h" +#include "ccf/endpoints/common_auth_policies.h" #include "ccf/js/common_context.h" #include "ccf/js/core/wrapped_value.h" #include "ccf/js/extensions/ccf/consensus.h" @@ -26,6 +27,9 @@ #include "node/rpc/http_rpc_context.h" #include "node/rpc/test/node_stub.h" #include "node/tx_receipt_impl.h" +#include "service/tables/signatures.h" + +#include #define DOCTEST_CONFIG_IMPLEMENT #include @@ -35,6 +39,26 @@ #include #include #include +#include + +namespace registry_compatibility +{ + class BaseRegistry : public ccf::js::BaseDynamicJSEndpointRegistry + { + public: + BaseRegistry(ccf::AbstractNodeContext& context) : + BaseDynamicJSEndpointRegistry(context) + {} + }; + + class AuditedRegistry : public ccf::js::DynamicJSEndpointRegistry + { + public: + AuditedRegistry(ccf::AbstractNodeContext& context) : + DynamicJSEndpointRegistry(context) + {} + }; +} using namespace ccf::js; @@ -510,6 +534,44 @@ TEST_CASE("Check KV Map access") } } + for (const auto access : + {TxAccess::APP_RO, TxAccess::APP_RW, TxAccess::GOV_RO, TxAccess::GOV_RW}) + { + CAPTURE(access); + for (const auto* table : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + CAPTURE(table); + CHECK(check_kv_map_access(access, table) == KVAccessPermissions::ILLEGAL); + CHECK( + check_kv_map_access( + access, table, extensions::kvhelpers::KVSource::CurrentTx) == + KVAccessPermissions::ILLEGAL); + CHECK( + check_kv_map_access( + access, table, extensions::kvhelpers::KVSource::Historical) == + KVAccessPermissions::READ_ONLY); + } + + for (const auto* table : + {"public:ccf.internal.table", + "public:ccf.internal.signatures_other", + "public:ccf.internal.signatures.nested", + "public:ccf.internal.cose_signatures_other", + "public:ccf.internal.tree_other"}) + { + CAPTURE(table); + CHECK( + check_kv_map_access(access, table) == KVAccessPermissions::READ_ONLY); + CHECK( + check_kv_map_access( + access, table, extensions::kvhelpers::KVSource::Historical) == + KVAccessPermissions::READ_ONLY); + } + } + { INFO("Every permission is described accurately"); REQUIRE( @@ -539,7 +601,7 @@ TEST_CASE("Check KV Map access") REQUIRE_THROWS_WITH_AS( explain_kv_map_access( static_cast(permission_value), TxAccess::APP_RW), - fmt::format("Unexpected KV access permission: {}", permission_value), + std::format("Unexpected KV access permission: {}", permission_value), std::logic_error); } } @@ -550,7 +612,7 @@ bool str_contains(const std::string& s, std::string_view sv) const auto b = s.contains(sv); if (!b) { - fmt::print("Didn't find\n {}\nin\n {}\n", sv, s); + std::cout << std::format("Didn't find\n {}\nin\n {}\n", sv, s); } return b; } @@ -576,12 +638,16 @@ using KVMap = ccf::kv::untyped::Map; // Returns an error message if the JS script throws. std::optional run_kv_script( - ccf::kv::Tx& tx, TxAccess access, const std::string& body) + ccf::kv::Tx& tx, + TxAccess access, + const std::string& body, + ccf::js::NamespaceRestriction namespace_restriction = {}) { ccf::js::core::Context ctx(access); - ctx.add_extension(std::make_shared(&tx)); + ctx.add_extension(std::make_shared( + &tx, std::move(namespace_restriction))); - const auto module = fmt::format("export function run() {{\n{}\n}}", body); + const auto module = std::format("export function run() {{\n{}\n}}", body); auto func = ctx.get_exported_function(module, "run", "/test/kv_script"); const auto result = ctx.call_with_rt_options( @@ -634,6 +700,110 @@ TEST_CASE("Interpreter cache without a clearing override") std::logic_error); } +TEST_CASE_TEMPLATE( + "JS registry instantiations and legacy subclass constructors link", + Registry, + registry_compatibility::BaseRegistry, + registry_compatibility::AuditedRegistry, + BaseDynamicJSEndpointRegistryT, + DynamicJSEndpointRegistryT, + BaseDynamicJSEndpointRegistryT, + DynamicJSEndpointRegistryT) +{ + ccf::AbstractNodeContext context; + context.install_subsystem(std::make_shared()); + context.install_subsystem(std::make_shared(1)); + if constexpr (std::is_base_of_v) + { + [[maybe_unused]] Registry registry(context); + } + else + { + [[maybe_unused]] Registry registry( + context, default_js_registry_kv_prefix, "app"); + } +} + +TEST_CASE("JS registry without built-ins dispatches JS and native endpoints") +{ + ccf::AbstractNodeContext context; + context.install_subsystem(std::make_shared()); + context.install_subsystem(std::make_shared(1)); + const std::string prefix = "custom"; + DynamicJSEndpointRegistryT registry( + context, "public:test", prefix); + registry.init_handlers(); + registry + .make_endpoint( + "/native", + HTTP_GET, + [](auto& ctx) { ctx.rpc_ctx->set_response_status(HTTP_STATUS_ACCEPTED); }, + ccf::no_auth_required) + .install(); + + ccf::kv::Store store; + Bundle bundle; + auto& properties = bundle.metadata.endpoints["/js/{id}"]["GET"]; + properties.js_module = "/handler.js"; + properties.js_function = "handler"; + properties.mode = ccf::endpoints::Mode::ReadOnly; + properties.authn_policies = {"no_auth"}; + bundle.modules.push_back( + {"/handler.js", + "export function handler(request) { return {body: request.params.id}; }"}); + auto tx = store.create_tx(); + REQUIRE( + registry.install_custom_endpoints_v1(tx, bundle) == ccf::ApiResult::OK); + + auto make_rpc_context = [](const std::string& path) { + return std::make_shared( + std::make_shared(0, std::vector{}), + HTTP_GET, + path, + ccf::http::HeaderMap{}, + std::vector{}); + }; + for (const auto* path : {"/tx", "/commit", "/receipt", "/api"}) + { + INFO(path); + auto rpc_ctx = make_rpc_context(path); + CHECK(registry.find_endpoint(tx, *rpc_ctx) == nullptr); + CHECK(registry.get_allowed_verbs(tx, *rpc_ctx).empty()); + } + + for (const auto* path : {"/native", "/js/42"}) + { + auto rpc_ctx = make_rpc_context(path); + auto endpoint = registry.find_endpoint(tx, *rpc_ctx); + REQUIRE(endpoint != nullptr); + CHECK( + endpoint->full_uri_path == + (std::string_view(path) == "/native" ? "/custom/native" : + "/custom/js/{id}")); + CHECK(registry.get_allowed_verbs(tx, *rpc_ctx).contains(HTTP_GET)); + ccf::endpoints::EndpointContext endpoint_ctx(rpc_ctx, tx); + registry.execute_endpoint(endpoint, endpoint_ctx); + if (std::string_view(path) == "/native") + { + CHECK(rpc_ctx->get_response_status() == HTTP_STATUS_ACCEPTED); + } + else + { + CHECK(rpc_ctx->get_response_status() == HTTP_STATUS_OK); + CHECK(rpc_ctx->get_response_body() == std::vector{'4', '2'}); + } + } + + nlohmann::json document; + REQUIRE( + registry.generate_openapi_document_v1( + tx, "Test", "Registry base selection", "1.0", document) == + ccf::ApiResult::OK); + CHECK(document["paths"].contains("/custom/native")); + CHECK(document["paths"].contains("/custom/js/{id}")); + CHECK_FALSE(document["paths"].contains("/custom/tx")); +} + TEST_CASE("JS registry namespace restrictions") { class ReassignedRegistry : public DynamicJSEndpointRegistry @@ -781,7 +951,6 @@ export function write(request) { INFO(table); auto rpc_ctx = std::make_shared( std::make_shared(0, std::vector{}), - ccf::HttpVersion::HTTP1, HTTP_POST, "/write", ccf::http::HeaderMap{}, @@ -822,7 +991,7 @@ export function write(request) { "my_table"}) { check_write( - fmt::format("public:custom_endpoints.{}", suffix), + std::format("public:custom_endpoints.{}", suffix), can_write_default_namespace); } check_write( @@ -860,7 +1029,7 @@ TEST_CASE("KV handle permissions") // Every script below operates on a single key, and refers to tables by these // names rather than repeating the string literals - const auto js_prelude = fmt::format( + const auto js_prelude = std::format( R"JS( const key = new Uint8Array([107]).buffer; const value = new Uint8Array([118]).buffer; @@ -1133,7 +1302,7 @@ std::optional call_validate_constitution( const auto path = "/path/to/constitution"; - auto module = fmt::format( + auto module = std::format( "export function call_validate () {{\n" " {}\n" " let constitution = {};\n" @@ -1542,7 +1711,7 @@ export function call_validate_catching () { ccf::js::core::Context ctx(TxAccess::GOV_RO); ctx.add_extension(std::make_shared()); const auto module = - fmt::format( + std::format( "export function call_validate () {{\n" " let constitution = {};\n" " return ccf.gov.validateConstitution(constitution);\n" @@ -1806,7 +1975,7 @@ TEST_CASE("QuickJS commits the maximum length of growable SharedArrayBuffers") JSMemoryUsage before; JS_ComputeMemoryUsage(rt, &before); - const auto script = fmt::format( + const auto script = std::format( R"( globalThis.shared = new SharedArrayBuffer(8, {{maxByteLength: {0}}}); shared.grow({0}); @@ -1829,7 +1998,7 @@ view[{0} - 1] + view[{0} >> 1]; JS_SetMemoryLimit(rt, after.malloc_size + max_length / 2); const auto over_limit = - fmt::format("new SharedArrayBuffer(8, {{maxByteLength: {}}});", max_length); + std::format("new SharedArrayBuffer(8, {{maxByteLength: {}}});", max_length); result = JS_Eval( ctx, over_limit.c_str(), @@ -2073,7 +2242,7 @@ TEST_CASE("QuickJS does not resume compiling after exceeding the heap limit") // miss the default value of 'b', compile 'f' without a separate parameter // scope, and so make f() return "inner". constexpr size_t key_size = 64 * 1024; - const std::string script = fmt::format( + const std::string script = std::format( "var x = 'outer';" "function f({{\"{}\": a}}, b = () => x) {{ var x = 'inner'; return b(); }}" "f({{}});", @@ -2225,7 +2394,7 @@ TEST_CASE("QuickJS frees a module which could not be read from bytecode") std::string source; for (size_t i = 0; i < entries; ++i) { - source += fmt::format( + source += std::format( "import {{a as a{0}}} from 'dep{0}.js'; export const b{0} = a{0};\n", i); } const auto bytecode = compile_module_to_bytecode(source, "tables.js"); @@ -2936,6 +3105,8 @@ namespace public: size_t tx_creations = 0; + CountingStore() : ccf::kv::Store(true) {} + std::unique_ptr create_read_only_tx_ptr() override { ++tx_creations; @@ -2953,6 +3124,245 @@ namespace ccf::NodeId("test-node"), std::nullopt); } + + std::vector make_test_signature_transaction(ccf::kv::Store& store) + { + const auto txid = store.next_txid(); + auto tx = store.create_reserved_tx(txid); + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::NodeId("test-node"), txid.seqno)); + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {1, 2, 3}); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({4, 5, 6}); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + return std::move(info.data); + } + + constexpr auto signature_table_test_prelude = R"JS( +const signatureTables = [ + "public:ccf.internal.signatures", + "public:ccf.internal.cose_signatures", + "public:ccf.internal.tree" +]; +const key = new ArrayBuffer(8); +const value = new Uint8Array([118]).buffer; +function expectTypeError(operation, ...fragments) { + try { + operation(); + } catch (e) { + if (!(e instanceof TypeError) || + fragments.some(fragment => !e.message.includes(fragment))) { + throw new Error(`Unexpected error: ${e}`); + } + return; + } + throw new Error(`Operation was permitted: ${fragments.join(", ")}`); +} +function readOperations(donor) { + return [ + ["get", target => donor.get.call(target, key)], + ["has", target => donor.has.call(target, key)], + ["getVersionOfPreviousWrite", + target => donor.getVersionOfPreviousWrite.call(target, key)], + ["forEach", target => donor.forEach.call(target, () => {})], + ["size", target => + Object.getOwnPropertyDescriptor(donor, "size").get.call(target)] + ]; +} +function writeOperations(donor) { + return [ + ["set", target => donor.set.call(target, key, value)], + ["delete", target => donor.delete.call(target, key)], + ["clear", target => donor.clear.call(target)] + ]; +} +)JS"; +} + +TEST_CASE("Current JS signature table handles deny every operation") +{ + NamespaceRestriction namespace_restriction; + SUBCASE("Default namespace policy") {} + SUBCASE("A namespace callback cannot grant signature table access") + { + namespace_restriction = [](const std::string&, std::string&) { + return KVAccessPermissions::READ_WRITE; + }; + } + + for (const bool populated : {false, true}) + { + CAPTURE(populated); + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + if (populated) + { + make_test_signature_transaction(store); + } + + for (const auto access : + {TxAccess::APP_RO, + TxAccess::APP_RW, + TxAccess::GOV_RO, + TxAccess::GOV_RW}) + { + CAPTURE(access); + auto tx = store.create_tx(); + const auto body = std::string(signature_table_test_prelude) + R"JS( +for (const table of signatureTables) { + const handle = ccf.kv[table]; + for (const [, operation] of [ + ...readOperations(handle), ...writeOperations(handle) + ]) { + expectTypeError(() => operation(handle), table, "inaccessible"); + } +} +for (const table of [ + "public:ccf.internal.table", + "public:ccf.internal.signatures_other", + "public:ccf.internal.cose_signatures.nested", + "public:ccf.internal.tree_other" +]) { + const handle = ccf.kv[table]; + for (const [, operation] of readOperations(handle)) { + operation(handle); + } + for (const [, operation] of writeOperations(handle)) { + expectTypeError(() => operation(handle), table, "read-only"); + } +} +)JS"; + const auto error = run_kv_script(tx, access, body, namespace_restriction); + CHECK_MESSAGE(!error.has_value(), error.value_or("")); + for (const auto* table : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + CHECK( + (store.get_map(store.current_version(), table) != nullptr) == + populated); + } + } + } +} + +TEST_CASE("Historical JS signature table handles retain read-only access") +{ + bool restricted = false; + SUBCASE("Permitted historical reads") {} + SUBCASE("Namespace restrictions can deny historical signature reads") + { + restricted = true; + } + + for (const bool populated : {false, true}) + { + CAPTURE(populated); + ccf::kv::Store source; + source.set_encryptor(std::make_shared()); + auto historical_store = std::make_shared(true); + historical_store->set_encryptor( + std::make_shared()); + if (populated) + { + const auto data = make_test_signature_transaction(source); + REQUIRE( + historical_store->deserialize(data)->apply() == + ccf::kv::ApplyResult::PASS_SIGNATURE); + } + + auto state = std::make_shared( + historical_store, make_test_receipt(), ccf::TxID{1, 1}); + for (const auto access : + {TxAccess::APP_RO, + TxAccess::APP_RW, + TxAccess::GOV_RO, + TxAccess::GOV_RW}) + { + CAPTURE(access); + ccf::js::core::Context ctx(access); + auto tx = source.create_tx(); + ctx.add_extension(std::make_shared( + &tx, [restricted](const std::string& name, std::string& explanation) { + if (restricted && ccf::kv::is_signature_table(name)) + { + explanation = "Restricted test signature table"; + return KVAccessPermissions::ILLEGAL; + } + return KVAccessPermissions::READ_WRITE; + })); + auto historical = + std::make_shared(nullptr); + ctx.add_extension(historical); + auto js_state = historical->create_historical_state_object(ctx, state); + REQUIRE_FALSE(js_state.is_exception()); + REQUIRE(ctx.get_global_obj().set("testState", std::move(js_state)) == 1); + + const auto script = std::format( + "const populated = {};\nconst restricted = {};\n", + populated, + restricted) + + signature_table_test_prelude + R"JS( +export function run() { + for (const table of signatureTables) { + const handle = testState.kv[table]; + if (restricted) { + for (const [name, operation] of [ + ...readOperations(handle), ...writeOperations(handle) + ]) { + expectTypeError( + () => operation(handle), table, "Restricted test signature table"); + } + continue; + } + if (handle.size !== (populated ? 1 : 0)) { + throw new Error(`Unexpected size for ${table}`); + } + if (handle.has(key) !== populated || + (handle.get(key) !== undefined) !== populated || + (handle.getVersionOfPreviousWrite(key) !== undefined) !== populated) { + throw new Error(`Unexpected singleton lookup for ${table}`); + } + let seen = 0; + handle.forEach((value, entryKey) => { + const storedValue = handle.get(entryKey); + if (!handle.has(entryKey) || value.byteLength === 0 || + storedValue === undefined || + handle.getVersionOfPreviousWrite(entryKey) !== 1) { + throw new Error(`Unreadable historical entry for ${table}`); + } + const bytes = new Uint8Array(value); + const storedBytes = new Uint8Array(storedValue); + if (bytes.length !== storedBytes.length || + !bytes.every((byte, i) => byte === storedBytes[i])) { + throw new Error(`Mismatched historical value for ${table}`); + } + seen++; + }); + if (seen !== handle.size) { + throw new Error(`Unexpected iteration count for ${table}`); + } + for (const [, operation] of writeOperations(handle)) { + expectTypeError(() => operation(handle), table, "read-only"); + } + } +} +)JS"; + auto func = ctx.get_exported_function( + script, "run", "/test/historical-signature-tables.js"); + const auto result = ctx.call_with_rt_options( + func, {}, std::nullopt, ccf::js::core::RuntimeLimitsPolicy::NONE); + if (result.is_exception()) + { + const auto [reason, trace] = ctx.error_message(); + FAIL_CHECK(reason); + } + CHECK(JS_HasException(ctx) == 0); + } + } } TEST_CASE("Historical state") @@ -3175,7 +3585,6 @@ export function run(request) { auto rpc_ctx = std::make_shared( std::make_shared( ccf::InvalidSessionId, std::vector{}), - ccf::HttpVersion::HTTP1, HTTP_GET, "/response?" + query, ccf::http::HeaderMap{}, @@ -3382,7 +3791,7 @@ namespace ccf::js::CommonContext ctx(TxAccess::APP_RW); JS_UpdateStackTop(ctx.runtime()); const auto module = - fmt::format("export function handler() {{\n{}\n}}", body); + std::format("export function handler() {{\n{}\n}}", body); auto handler = ctx.get_exported_function(module, "handler", "/test/crypto.js"); const auto result = ctx.call_with_rt_options( @@ -3968,7 +4377,7 @@ TEST_CASE("ccf.crypto.verifySignature against an X.509 certificate") ccf::ds::to_x509_time_string(ccf::nonstd::SystemClock::now() + 24h * 3650); auto cert_pem = kp->self_sign("CN=verify test", valid_from, valid_to); - run_crypto_handler(fmt::format( + run_crypto_handler(std::format( R"JS( const cert = {}; const privateKey = {}; @@ -4102,12 +4511,12 @@ TEST_CASE("ccf.tcbHexToPolicy") auto js_field = [](const char* field, auto opt) { if (!opt.has_value()) { - return fmt::format( + return std::format( "if (\"{}\" in policy) throw new Error(\"unexpected {}\");\n", field, field); } - return fmt::format( + return std::format( "if (policy.{} !== {}) throw new Error(\"bad {}: \" + policy.{});\n", field, opt.value(), @@ -4116,7 +4525,7 @@ TEST_CASE("ccf.tcbHexToPolicy") }; std::string checks; - checks += fmt::format( + checks += std::format( "if (policy.hexstring !== {}) throw new Error(\"bad hexstring: \" + " "policy.hexstring);\n", js_string_literal(expected.hexstring.value())); @@ -4126,7 +4535,7 @@ TEST_CASE("ccf.tcbHexToPolicy") checks += js_field("boot_loader", expected.boot_loader); checks += js_field("fmc", expected.fmc); - run_crypto_handler(fmt::format( + run_crypto_handler(std::format( R"JS( const policy = ccf.tcbHexToPolicy("{}", "{}"); {} diff --git a/src/kv/test/kv_serialisation.cpp b/src/kv/test/kv_serialisation.cpp index a60ee94b9197..bfe0b9f61940 100644 --- a/src/kv/test/kv_serialisation.cpp +++ b/src/kv/test/kv_serialisation.cpp @@ -1,5 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. +#include "ccf/kv/value.h" #include "ds/internal_logger.h" #include "kv/kv_serialiser.h" #include "kv/null_encryptor.h" @@ -9,6 +10,7 @@ #include "node/encryptor.h" #include +#include #undef FAIL #include #include @@ -718,9 +720,10 @@ TEST_CASE( kv_store.set_encryptor(encryptor); kv_store.set_max_transaction_size(1); - MapTypes::StringString map("public:signature"); + ccf::kv::RawCopySerialisedValue> tree( + ccf::Tables::SERIALISED_MERKLE_TREE); auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); - tx.rw(map)->put("signature", std::string(512, 'A')); + tx.wo(tree)->put(std::vector(512, 'A')); const auto [result, data, claims, commit_evidence, hooks] = tx.commit_reserved(); @@ -1181,7 +1184,7 @@ struct CustomVerboseDumbSerialiser static Bytes to_serialised(const CustomClass& c) { - const auto verbose = fmt::format("{}\ns={}\nn={}", T::prefix, c.s, c.n); + const auto verbose = std::format("{}\ns={}\nn={}", T::prefix, c.s, c.n); return Bytes(verbose.begin(), verbose.end()); } @@ -1247,6 +1250,8 @@ TEST_CASE_TEMPLATE( ccf::kv::Store kv_store; auto encryptor = std::make_shared(); kv_store.set_encryptor(encryptor); + auto consensus = std::make_shared(); + kv_store.set_consensus(consensus); MapType map("public:map"); @@ -1263,19 +1268,19 @@ TEST_CASE_TEMPLATE( MapType map2("public:map"); - auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); + auto tx = kv_store.create_tx(); auto handle = tx.rw(map); handle->put(k1, v1); handle->put(k2, v2); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx.commit_reserved(); - auto& success = success_; - auto& data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto data = consensus->get_latest_data(); + REQUIRE(data.has_value()); kv_store.compact(kv_store.current_version()); - REQUIRE(kv_store2.deserialize(data)->apply() == ccf::kv::ApplyResult::PASS); + REQUIRE( + kv_store2.deserialize(data.value())->apply() == + ccf::kv::ApplyResult::PASS); auto tx2 = kv_store2.create_tx(); auto handle2 = tx2.rw(map2); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index db875da33b16..2e5ed52e9ec1 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -13,16 +13,20 @@ #include "kv/compacted_version_conflict.h" #include "kv/kv_serialiser.h" #include "kv/ledger_chunker.h" +#include "kv/map_access_denied.h" #include "kv/null_encryptor.h" #include "kv/store.h" #include "kv/test/null_tx_history.h" #include "kv/test/stub_consensus.h" +#include + #define DOCTEST_CONFIG_IMPLEMENT #include #undef FAIL #include #include +#include #include #include #include @@ -40,6 +44,37 @@ struct MapTypes using UntypedMap = ccf::kv::untyped::Map; }; +static ccf::kv::PendingTxInfo make_signature_entry( + ccf::kv::Store& store, const ccf::TxID& txid, uint8_t marker) +{ + auto signature = store.create_reserved_tx(txid); + signature.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); + signature.wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, {marker}); + signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({marker}); + return signature.commit_reserved(); +} + +static ccf::kv::CommitResult publish_signature_entry( + ccf::kv::Store& store, const ccf::TxID& txid, uint8_t marker) +{ + auto info = make_signature_entry(store, txid, marker); + if (info.success != ccf::kv::CommitResult::SUCCESS) + { + return info.success; + } + return store.commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true); +} + TEST_CASE("Map name parsing") { using SD = ccf::kv::SecurityDomain; @@ -66,6 +101,448 @@ TEST_CASE("Map name parsing") REQUIRE(parse("public:ccf_foo") == mp(SD::PUBLIC, AC::APPLICATION)); } +TEST_CASE("Live transactions cannot acquire signature table handles") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + + auto check_denied = [&store]() { + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Restricted table: ", std::string_view(name)); + MapTypes::StringString typed_map(name); + + auto tx = store.create_tx(); + CHECK_THROWS_AS(tx.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.rw(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS(tx.wo(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.rw(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + tx.wo(name), ccf::kv::MapAccessDenied); + + auto ro = store.create_read_only_tx(); + CHECK_THROWS_AS(ro.ro(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ro.ro(name), ccf::kv::MapAccessDenied); + + auto diff = store.create_tx_diff(); + CHECK_THROWS_AS(diff.diff(typed_map), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + diff.diff(name), ccf::kv::MapAccessDenied); + } + }; + + INFO("Denied before any signature exists, without creating maps or snapshot"); + auto deferred_tx = store.create_tx(); + auto deferred_ro = store.create_read_only_tx(); + CHECK_THROWS_AS( + deferred_tx.ro(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + deferred_ro.ro(ccf::Tables::SIGNATURES), + ccf::kv::MapAccessDenied); + check_denied(); + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + CHECK(store.get_map(store.current_version(), name) == nullptr); + } + CHECK(store.current_version() == 0); + + INFO("Denied while a signature reservation is pending and after it commits"); + const auto signature_txid = store.next_txid(); + check_denied(); + MapTypes::StringString ordinary("public:ordinary"); + { + auto writer = store.create_tx(); + writer.rw(ordinary)->put("key", "value"); + REQUIRE(writer.commit() == ccf::kv::CommitResult::SUCCESS); + } + REQUIRE(deferred_tx.ro(ordinary)->get("key") == "value"); + REQUIRE(deferred_ro.ro(ordinary)->get("key") == "value"); + REQUIRE( + publish_signature_entry(store, signature_txid, 42) == + ccf::kv::CommitResult::SUCCESS); + check_denied(); + + INFO("Restrictions apply only to the exact three public signature tables"); + for (const auto* name : + {"public:ccf.internal.signatures_extra", + "public:ccf.internal.cose_signatures.extra", + "public:ccf.internal.tree_extra", + "ccf.internal.signatures", + ccf::Tables::ENCRYPTED_PAST_LEDGER_SECRET}) + { + INFO("Allowed table: ", std::string_view(name)); + MapTypes::StringString map(name); + auto tx = store.create_tx(); + tx.wo(map)->put("key", "value"); + REQUIRE(tx.ro(map)->get("key") == "value"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + auto read = store.create_read_only_tx(); + REQUIRE(read.ro(map)->get("key") == "value"); + auto diff = store.create_tx_diff(); + REQUIRE(diff.diff(map)->size() == 1); + } +} + +TEST_CASE("Historical signature entries remain readable") +{ + ccf::kv::Store source; + source.set_encryptor(std::make_shared()); + const auto txid = source.next_txid(); + auto info = make_signature_entry(source, txid, 42); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + + ccf::kv::Store historical(true); + historical.set_encryptor(std::make_shared()); + REQUIRE( + historical.deserialize(info.data)->apply() == + ccf::kv::ApplyResult::PASS_SIGNATURE); + + auto tx = historical.create_read_only_tx(); + REQUIRE( + tx.ro(ccf::Tables::SIGNATURES)->get()->seqno == + txid.seqno); + REQUIRE( + tx.ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{42}); + REQUIRE( + tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{42}); + + auto ptr = historical.create_read_only_tx_ptr(); + auto diff = historical.create_tx_diff(); + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Historical table: ", std::string_view(name)); + REQUIRE(ptr->ro(name)->size() == 1); + REQUIRE(diff.diff(name)->size() == 1); + + auto ordinary = historical.create_tx(); + CHECK_THROWS_AS( + ordinary.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + ordinary.wo(name), ccf::kv::MapAccessDenied); + } +} + +TEST_CASE("Reserved transactions are write-only on signature tables") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + store.set_consensus(std::make_shared()); + + INFO("Cannot access non-signature maps or upgrade signature handles"); + { + auto reserved = store.create_reserved_tx(store.next_txid()); + CHECK_THROWS_AS( + reserved.wo("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.ro("public:ordinary"), + ccf::kv::MapAccessDenied); + CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); + + for (const auto* name : + {ccf::Tables::SIGNATURES, + ccf::Tables::COSE_SIGNATURES, + ccf::Tables::SERIALISED_MERKLE_TREE}) + { + INFO("Reserved table: ", std::string_view(name)); + auto* handle = reserved.wo(name); + CHECK(reserved.wo(name) == handle); + CHECK_THROWS_AS( + reserved.ro(name), ccf::kv::MapAccessDenied); + CHECK_THROWS_AS( + reserved.rw(name), ccf::kv::MapAccessDenied); + } + } + + INFO("Clear on an empty signature table records a read and is rejected"); + { + auto reserved = store.create_reserved_tx(store.next_txid()); + auto* tree = reserved.wo( + ccf::Tables::SERIALISED_MERKLE_TREE); + tree->clear(); + tree->put({1}); + CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); + } + + INFO("Recorded read dependencies on populated signature tables are rejected"); + const auto baseline = store.next_txid(); + REQUIRE( + publish_signature_entry(store, baseline, 1) == + ccf::kv::CommitResult::SUCCESS); + store.compact(baseline.seqno); + for (const std::string_view observation : + {"get", + "foreach", + "clear", + "get_globally_committed", + "has_globally_committed"}) + { + INFO("Reserved observation: ", observation); + auto reserved = store.create_reserved_tx(store.next_txid()); + auto* handle = + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + const auto key = ccf::SerialisedMerkleTree::create_unit(); + if (observation == "get") + { + REQUIRE(handle->get(key).has_value()); + } + else if (observation == "foreach") + { + handle->foreach([](const auto&, const auto&) { return true; }); + } + else if (observation == "clear") + { + reserved + .wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->clear(); + } + else if (observation == "get_globally_committed") + { + REQUIRE(handle->get_globally_committed(key).has_value()); + } + else + { + REQUIRE(handle->has_globally_committed(key)); + } + handle->put(key, {2}); + CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); + } +} + +TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + MapTypes::StringString raw("public:raw"); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "old"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto old_signature = store.next_txid(); + REQUIRE( + publish_signature_entry(store, old_signature, 1) == + ccf::kv::CommitResult::SUCCESS); + const auto pending_signature = store.next_txid(); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "new"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + REQUIRE(store.current_version() == pending_signature.seqno + 1); + REQUIRE(consensus->number_of_replicas() == old_signature.seqno); + + auto cold = store.create_read_only_tx_at_replicated_state(); + auto warm = store.create_read_only_tx_at_replicated_state(); + REQUIRE( + warm.ro(ccf::Tables::SIGNATURES)->get()->seqno == + old_signature.seqno); + REQUIRE(warm.ro(raw)->get("key") == "old"); + REQUIRE( + publish_signature_entry(store, pending_signature, 2) == + ccf::kv::CommitResult::SUCCESS); + + for (auto* read : {&cold, &warm}) + { + REQUIRE(read->ro(raw)->get("key") == "old"); + REQUIRE( + read->ro(ccf::Tables::SIGNATURES)->get()->seqno == + old_signature.seqno); + REQUIRE( + read->ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{1}); + REQUIRE( + read->ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{1}); + } + + auto current = store.create_read_only_tx_at_replicated_state(); + REQUIRE(current.ro(raw)->get("key") == "new"); + REQUIRE( + current.ro(ccf::Tables::SIGNATURES)->get()->seqno == + pending_signature.seqno); + REQUIRE( + current.ro(ccf::Tables::COSE_SIGNATURES) + ->get(ccf::IdentityType::CLASSICAL) == std::vector{2}); + REQUIRE( + current.ro(ccf::Tables::SERIALISED_MERKLE_TREE) + ->get() == std::vector{2}); +} + +TEST_CASE("Materialised reads reject rollback and see replication compaction") +{ + SUBCASE("Rollback before lookup invalidates live and historical views") + { + for (const bool is_historical : {false, true}) + { + INFO("Historical store: ", is_historical); + ccf::kv::Store store(is_historical); + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + constexpr ccf::View initial_view = 2; + constexpr ccf::View replacement_view = 3; + store.initialise_term(initial_view); + MapTypes::StringString raw("public:raw"); + ccf::Signatures signatures(ccf::Tables::SIGNATURES); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "old"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto initial_signature = store.next_txid(); + REQUIRE( + publish_signature_entry(store, initial_signature, 1) == + ccf::kv::CommitResult::SUCCESS); + + auto old = store.create_read_only_tx_at_replicated_state(); + REQUIRE(old.ro(signatures)->get()->seqno == initial_signature.seqno); + auto diff = store.create_tx_diff(); + if (is_historical) + { + REQUIRE(diff.diff(cose_signatures)->size() == 1); + } + + store.rollback({initial_view, 0}, replacement_view); + consensus->view_history.rollback(0); + consensus->flush(); + { + auto tx = store.create_tx(); + tx.rw(raw)->put("key", "replacement"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + const auto replacement_signature = store.next_txid(); + REQUIRE(replacement_signature.seqno == initial_signature.seqno); + REQUIRE( + publish_signature_entry(store, replacement_signature, 2) == + ccf::kv::CommitResult::SUCCESS); + + CHECK_THROWS_AS(old.ro(raw), ccf::kv::CompactedVersionConflict); + CHECK_THROWS_AS(old.ro(signatures), ccf::kv::CompactedVersionConflict); + if (is_historical) + { + CHECK_THROWS_AS( + diff.diff(cose_signatures), ccf::kv::CompactedVersionConflict); + } + + auto fresh = store.create_read_only_tx_at_replicated_state(); + REQUIRE(fresh.ro(raw)->get("key") == "replacement"); + REQUIRE( + fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == + std::vector{2}); + } + } + + SUBCASE("Rollback during snapshot acquisition is detected") + { + class ReplacingStore : public ccf::kv::Store + { + public: + std::function replace_during_lookup = nullptr; + bool replacement_triggered = false; + + std::shared_ptr get_map( + ccf::kv::Version version, const std::string& name) override + { + if ( + name == ccf::Tables::COSE_SIGNATURES && + replace_during_lookup != nullptr) + { + auto replace = std::exchange(replace_during_lookup, nullptr); + replacement_triggered = true; + replace(); + } + return ccf::kv::Store::get_map(version, name); + } + }; + + ReplacingStore store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + store.initialise_term(2); + ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); + const auto initial_signature = store.next_txid(); + REQUIRE( + publish_signature_entry(store, initial_signature, 1) == + ccf::kv::CommitResult::SUCCESS); + auto old = store.create_read_only_tx_at_replicated_state(); + + store.replace_during_lookup = [&]() { + store.rollback({2, 0}, 3); + consensus->view_history.rollback(0); + consensus->flush(); + REQUIRE( + publish_signature_entry(store, store.next_txid(), 2) == + ccf::kv::CommitResult::SUCCESS); + }; + + CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); + REQUIRE(store.replacement_triggered); + } + + SUBCASE("Prefix compacted synchronously inside replication is visible") + { + class CompactingConsensus : public ccf::kv::test::PrimaryStubConsensus + { + ccf::kv::Store& store; + + public: + std::optional observed_signature; + + explicit CompactingConsensus(ccf::kv::Store& store_) : store(store_) {} + + bool replicate( + const ccf::kv::BatchVector& entries, ccf::View view) override + { + const auto result = PrimaryStubConsensus::replicate(entries, view); + store.compact(std::get<0>(entries.back())); + auto read = store.create_read_only_tx_at_replicated_state(); + if (auto sig = read.ro(ccf::Tables::SIGNATURES)->get()) + { + observed_signature = sig->seqno; + } + return result; + } + }; + + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(store); + store.set_consensus(consensus); + const auto txid = store.next_txid(); + REQUIRE( + publish_signature_entry(store, txid, 1) == + ccf::kv::CommitResult::SUCCESS); + REQUIRE(consensus->observed_signature == txid.seqno); + } +} + TEST_CASE("Zero-revision whole-map dependencies") { using Result = ccf::kv::CommitResult; @@ -2589,24 +3066,25 @@ TEST_CASE("Deserialising from other Store") auto encryptor = std::make_shared(); ccf::kv::Store store; store.set_encryptor(encryptor); + auto consensus = std::make_shared(); + store.set_consensus(consensus); MapTypes::NumString public_map("public:public"); MapTypes::NumString private_map("private"); - auto tx1 = store.create_reserved_tx(store.next_txid()); + auto tx1 = store.create_tx(); auto handle1 = tx1.rw(public_map); auto handle2 = tx1.rw(private_map); handle1->put(42, "aardvark"); handle2->put(14, "alligator"); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx1.commit_reserved(); - auto& success = success_; - auto& data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx1.commit() == ccf::kv::CommitResult::SUCCESS); + const auto data = consensus->get_latest_data(); + REQUIRE(data.has_value()); ccf::kv::Store clone; clone.set_encryptor(encryptor); - REQUIRE(clone.deserialize(data)->apply() == ccf::kv::ApplyResult::PASS); + REQUIRE( + clone.deserialize(data.value())->apply() == ccf::kv::ApplyResult::PASS); } TEST_CASE("Transaction diffs") @@ -2780,6 +3258,8 @@ TEST_CASE("Deserialise return status") ccf::kv::Store store; auto encryptor = std::make_shared(); store.set_encryptor(encryptor); + auto consensus = std::make_shared(); + store.set_consensus(consensus); ccf::Signatures signatures(ccf::Tables::SIGNATURES); ccf::SerialisedMerkleTree serialised_tree( @@ -2796,24 +3276,22 @@ TEST_CASE("Deserialise return status") store.set_history(history); { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_tx(); auto data_handle = tx.rw(data); data_handle->put(42, 42); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx.commit_reserved(); - auto& success = success_; - auto& serialised_data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto serialised_data = consensus->get_latest_data(); + REQUIRE(serialised_data.has_value()); REQUIRE( - store.deserialize(serialised_data)->apply() == + store.deserialize(serialised_data.value())->apply() == ccf::kv::ApplyResult::PASS); } { auto tx = store.create_reserved_tx(store.next_txid()); - auto sig_handle = tx.rw(signatures); - auto tree_handle = tx.rw(serialised_tree); + auto sig_handle = tx.wo(signatures); + auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); sig_handle->put(sigv); tree_handle->put({}); @@ -2830,17 +3308,35 @@ TEST_CASE("Deserialise return status") INFO("Signature transactions with additional contents should fail"); { - auto tx = store.create_reserved_tx(store.next_txid()); - auto sig_handle = tx.rw(signatures); - auto data_handle = tx.rw(data); + // The transaction API rejects this mixture, so exercise ledger admission + // with an explicitly malformed serialised entry. + ccf::kv::RawKvStoreSerialiser serialiser( + encryptor, + ccf::TxID{store.commit_view(), store.current_version() + 1}, + ccf::kv::EntryType::WriteSet, + 0); + const auto serialise_single_write = + [&serialiser]( + const std::string& name, + const ccf::kv::serialisers::SerialisedEntry& key, + const ccf::kv::serialisers::SerialisedEntry& value) { + serialiser.start_map(name, ccf::kv::SecurityDomain::PUBLIC); + serialiser.serialise_entry_version(ccf::kv::NoVersion); + serialiser.serialise_count_header(0); + serialiser.serialise_count_header(1); + serialiser.serialise_write(key, value); + serialiser.serialise_count_header(0); + }; ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); - sig_handle->put(sigv); - data_handle->put(43, 43); - auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = - tx.commit_reserved(); - auto& success = success_; - auto& serialised_data = data_; - REQUIRE(success == ccf::kv::CommitResult::SUCCESS); + serialise_single_write( + signatures.get_name(), + ccf::Signatures::create_unit(), + ccf::Signatures::ValueSerialiser::to_serialised(sigv)); + serialise_single_write( + data.get_name(), + MapTypes::NumNum::KeySerialiser::to_serialised(43), + MapTypes::NumNum::ValueSerialiser::to_serialised(43)); + const auto serialised_data = serialiser.get_raw_data(); REQUIRE( store.deserialize(serialised_data)->apply() == @@ -3626,7 +4122,7 @@ TEST_CASE("Cross-map conflicts") std::string rand_string(size_t i) { - return fmt::format("{}: {}", i, rand()); + return std::format("{}: {}", i, rand()); } TEST_CASE("Mid-tx compaction") @@ -3880,7 +4376,8 @@ TEST_CASE("CommittableTx guards") const auto baseline_txid = kv_store.current_txid(); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); - reserved.rw(map)->put("k", "from_reserved"); + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); // Roll the store back, invalidating the rollback_count that `reserved` // captured when it was created. @@ -3909,13 +4406,44 @@ TEST_CASE("CommittableTx guards") std::logic_error); } + SUBCASE("commit rejects a reserved transaction directly and via base ref") + { + ccf::kv::Store kv_store; + kv_store.set_encryptor(std::make_shared()); + + const auto reserved_txid = kv_store.next_txid(); + auto reserved = kv_store.create_reserved_tx(reserved_txid); + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); + + REQUIRE_THROWS_WITH_AS( + reserved.commit(), + "Reserved transaction must be committed with commit_reserved()", + std::logic_error); + + ccf::kv::CommittableTx& base = reserved; + REQUIRE_THROWS_WITH_AS( + base.commit(), + "Reserved transaction must be committed with commit_reserved()", + std::logic_error); + + REQUIRE(kv_store.current_version() == reserved_txid.seqno); + REQUIRE_THROWS_WITH_AS( + auto _ = reserved.commit_version(), + "Transaction not yet committed", + std::logic_error); + REQUIRE( + reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + } + SUBCASE("commit_reserved rejects being called twice") { ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); - reserved.rw(map)->put("k", "v"); + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({42}); REQUIRE( reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); @@ -3954,22 +4482,31 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - { - // Establish the map, so the reserved tx below can read from it without - // creating it - auto tx = kv_store.create_tx(); - tx.rw(map)->put("k", "v"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } + const auto baseline = kv_store.next_txid(); + REQUIRE( + make_signature_entry(kv_store, baseline, 42).success == + ccf::kv::CommitResult::SUCCESS); // Such a transaction would otherwise succeed with an empty ledger entry, // leaving nothing at its reserved version auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); - REQUIRE(reserved.rw(map)->get("k") == "v"); - REQUIRE_THROWS_WITH_AS( - reserved.commit_reserved(), - "Reserved transaction cannot be empty", - std::logic_error); + auto* handle = + reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); + bool denied = false; + try + { + reserved.commit_reserved(); + } + catch (const ccf::kv::MapAccessDenied& e) + { + denied = true; + CHECK( + std::string_view(e.what()) == + "Reserved transaction cannot depend on reads from map " + "'public:ccf.internal.tree'"); + } + REQUIRE(denied); REQUIRE_THROWS_WITH_AS( auto _ = reserved.commit_version(), "Transaction not yet committed", @@ -4619,11 +5156,11 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") size_t n = 0; while (!stop_token.stop_requested()) { - // Takes maps_lock and searches the map set. Looks up names in the - // range being inserted, so the search path traverses the nodes - // add_dynamic_map is writing. Deliberately avoids current_version(), - // so this contends only on maps_lock. - (void)store.get_map(1, fmt::format("public:reserved_{}", n % 2000)); + // These names are repeatedly created and removed. The lookup holds + // maps_lock, and avoids any additional ordering with the writer. + const auto* name = (n % 2 == 0) ? ccf::Tables::SIGNATURES : + ccf::Tables::SERIALISED_MERKLE_TREE; + (void)store.get_map(2, name); n++; } }); @@ -4632,16 +5169,16 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") constexpr size_t reserved_txs = 2000; for (size_t i = 0; i < reserved_txs; ++i) { - // Each reserved transaction writes to a map that does not exist yet, so - // committing it adds to the Store's map set. Nothing else here may take - // maps_lock, or it would order the write against the readers and hide the - // race being reproduced. - auto tx = store.create_reserved_tx(store.next_txid()); - tx.rw(fmt::format("public:reserved_{}", i)) - ->put("k", "v"); - const auto [result, data, claims, commit_evidence, hooks] = - tx.commit_reserved(); - REQUIRE(result == ccf::kv::CommitResult::SUCCESS); + // Rollback removes the signature tables so the next reservation creates + // them again, exercising add_dynamic_map on every iteration. + const auto txid = store.next_txid(); + REQUIRE( + make_signature_entry(store, txid, 42).success == + ccf::kv::CommitResult::SUCCESS); + if (i + 1 < reserved_txs) + { + store.rollback({txid.view, 1}, txid.view); + } } for (auto& reader : readers) @@ -4650,14 +5187,12 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") } readers.clear(); - // Confirm the writes really did extend the map set, so this exercises - // Store::add_dynamic_map rather than silently doing nothing. + // Confirm the final reservation really recreated the signature tables. REQUIRE( - store.get_map(store.current_version(), "public:reserved_0") != nullptr); + store.get_map(store.current_version(), ccf::Tables::SIGNATURES) != nullptr); REQUIRE( store.get_map( - store.current_version(), - fmt::format("public:reserved_{}", reserved_txs - 1)) != nullptr); + store.current_version(), ccf::Tables::SERIALISED_MERKLE_TREE) != nullptr); } // Exposes the version the chunker has recorded entries up to, which is the @@ -4686,7 +5221,6 @@ class RollingBackPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - MapTypes::StringString& table; ccf::TxID rollback_to; ccf::kv::Term rollback_term; @@ -4694,21 +5228,17 @@ class RollingBackPendingTx : public ccf::kv::PendingTx RollingBackPendingTx( ccf::TxID txid_, ccf::kv::Store& store_, - MapTypes::StringString& table_, ccf::TxID rollback_to_, ccf::kv::Term rollback_term_) : txid(txid_), store(store_), - table(table_), rollback_to(rollback_to_), rollback_term(rollback_term_) {} ccf::kv::PendingTxInfo call() override { - auto tx = store.create_reserved_tx(txid); - tx.rw(table)->put("key", "value"); - auto info = tx.commit_reserved(); + auto info = make_signature_entry(store, txid, 42); store.rollback(rollback_to, rollback_term); return info; } @@ -4749,7 +5279,7 @@ TEST_CASE("Chunk metadata is not restored by a batch a rollback discarded") store.commit( reserved, std::make_unique( - reserved, store, map, baseline_txid, initial_term + 1), + reserved, store, baseline_txid, initial_term + 1), false); } @@ -5036,7 +5566,7 @@ TEST_CASE("committable_gap after replaying a ledger ending in a signature") for (size_t i = 1; i <= tx_count; ++i) { auto tx = primary.create_tx(); - tx.rw(map)->put(fmt::format("key{}", i), "value"); + tx.rw(map)->put(std::format("key{}", i), "value"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(primary.committable_gap() == i); } @@ -5077,7 +5607,7 @@ TEST_CASE("committable_gap after replaying a ledger ending in a signature") for (size_t i = 1; i <= tx_count; ++i) { auto tx = store.create_tx(); - tx.rw(map)->put("key", fmt::format("value{}", i)); + tx.rw(map)->put("key", std::format("value{}", i)); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(store.committable_gap() == i); } @@ -5107,7 +5637,7 @@ TEST_CASE("committable_gap after rolling back replayed entries") for (size_t i = 0; i < count; ++i) { auto tx = primary.create_tx(); - tx.rw(map)->put("key", fmt::format("value{}", primary.current_version())); + tx.rw(map)->put("key", std::format("value{}", primary.current_version())); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } }; @@ -5245,8 +5775,8 @@ TEST_CASE("Ledger entry chunk request") { auto txid = store.next_txid(); auto tx = store.create_reserved_tx(txid); - auto sig_handle = tx.rw(signatures); - auto tree_handle = tx.rw(serialised_tree); + auto sig_handle = tx.wo(signatures); + auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, txid.seqno); sig_handle->put(sigv); tree_handle->put({}); @@ -5321,8 +5851,8 @@ TEST_CASE("Ledger entry chunk request") REQUIRE(store.should_create_ledger_chunk(txid.seqno)); // Add the signature - auto sig_handle = tx.rw(signatures); - auto tree_handle = tx.rw(serialised_tree); + auto sig_handle = tx.wo(signatures); + auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, txid.seqno); sig_handle->put(sigv); tree_handle->put({}); @@ -5347,6 +5877,243 @@ TEST_CASE("Ledger entry chunk request") } } +TEST_CASE("Store version wraps to 0 past INT64_MAX") +{ + ccf::kv::Store kv_store; + auto encryptor = std::make_shared(); + kv_store.set_encryptor(encryptor); + kv_store.initialise_term(2); + + constexpr auto max_signed_version = + static_cast(std::numeric_limits::max()); + ccf::kv::StoreSnapshot snapshot(max_signed_version); + auto serialised = snapshot.serialise(encryptor); + ccf::kv::ConsensusHookPtrs hooks; + REQUIRE( + kv_store.deserialise_snapshot( + serialised.data(), serialised.size(), hooks) == + ccf::kv::ApplyResult::PASS); + REQUIRE(kv_store.current_version() == max_signed_version); + + const auto wrapped_txid = kv_store.next_txid(); + REQUIRE(wrapped_txid.view == 2); + REQUIRE(wrapped_txid.seqno == 0); + REQUIRE(kv_store.current_version() == 0); + + const auto next_txid = kv_store.next_txid(); + REQUIRE(next_txid.view == 2); + REQUIRE(next_txid.seqno == 1); + REQUIRE(kv_store.current_version() == 1); +} + +TEST_CASE("Store::commit edge cases") +{ + class FixedResultPendingTx : public ccf::kv::PendingTx + { + ccf::kv::CommitResult result; + + public: + explicit FixedResultPendingTx(ccf::kv::CommitResult result_) : + result(result_) + {} + + ccf::kv::PendingTxInfo call() override + { + return {result, {}, ccf::empty_claims(), {}, {}}; + } + }; + + SUBCASE("Out-of-order committable commits do not regress last_committable") + { + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + store.initialise_term(1); + + const auto txid1 = store.next_txid(); + const auto txid2 = store.next_txid(); + REQUIRE(txid1.seqno == 1); + REQUIRE(txid2.seqno == 2); + + // Commit seqno 2 first so last_committable advances to 2 while seqno 2 + // waits in pending_txs for seqno 1. + REQUIRE( + store.commit( + txid2, + std::make_unique(ccf::kv::CommitResult::SUCCESS), + true) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(consensus->number_of_replicas() == 0); + REQUIRE(store.committable_gap() == 0); + + // Committing an earlier committable seqno must not lower last_committable, + // and should drain both queued entries in order. + REQUIRE( + store.commit( + txid1, + std::make_unique(ccf::kv::CommitResult::SUCCESS), + true) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(consensus->number_of_replicas() == 2); + REQUIRE(store.committable_gap() == 0); + } + + SUBCASE("Unexpected non-SUCCESS PendingTx result is handled without aborting") + { + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + store.set_consensus(consensus); + store.initialise_term(1); + + const auto txid = store.next_txid(); + REQUIRE( + store.commit( + txid, + std::make_unique( + ccf::kv::CommitResult::FAIL_CONFLICT), + false) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(consensus->number_of_replicas() == 1); + } +} + +TEST_CASE("untyped::Map::create_committer rejects unexpected AbstractChangeSet") +{ + class DummyChangeSet : public ccf::kv::AbstractChangeSet + { + public: + [[nodiscard]] bool has_writes() const override + { + return false; + } + }; + + ccf::kv::Store store; + ccf::kv::untyped::Map map(&store, "public:map"); + DummyChangeSet dummy; + + REQUIRE_THROWS_WITH_AS( + map.create_committer(&dummy), "Type confusion error", std::logic_error); +} + +TEST_CASE("apply_changes ignores new_maps entries absent from changes") +{ + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + + auto written_map = + std::make_shared(&store, "public:written"); + auto untracked_map = + std::make_shared(&store, "public:untracked"); + + auto changeset = written_map->create_change_set(0, false); + REQUIRE(changeset != nullptr); + const auto key = + ccf::kv::serialisers::JsonSerialiser::to_serialised("k"); + const auto val = + ccf::kv::serialisers::JsonSerialiser::to_serialised("v"); + changeset->writes[key] = val; + + ccf::kv::OrderedChanges changes; + changes.emplace( + std::piecewise_construct, + std::forward_as_tuple("public:written"), + std::forward_as_tuple(written_map, std::move(changeset))); + + ccf::kv::MapCollection new_maps; + new_maps["public:written"] = written_map; + new_maps["public:untracked"] = untracked_map; + + ccf::kv::ConsensusHookPtrs hooks; + store.lock_map_set(); + const auto committed_v = ccf::kv::apply_changes( + changes, + []() -> std::optional { return 1; }, + hooks, + new_maps, + std::nullopt, + false); + store.unlock_map_set(); + + REQUIRE(committed_v.has_value()); + REQUIRE(*committed_v == 1); + REQUIRE(store.get_map(1, "public:written") == written_map); + REQUIRE(store.get_map(1, "public:untracked") == nullptr); +} + +TEST_CASE("BaseTx internal invariant guards") +{ + class TestBaseTx : public ccf::kv::BaseTx + { + public: + using BaseTx::BaseTx; + using BaseTx::compacted_version_conflict; + using BaseTx::get_map_and_change_set_by_name; + using BaseTx::retain_change_set; + }; + + ccf::kv::Store store; + store.set_encryptor(std::make_shared()); + + SUBCASE("retain_change_set rejects duplicate map name") + { + TestBaseTx tx(&store); + auto mc = tx.get_map_and_change_set_by_name("public:dup", false); + auto untyped_map = std::dynamic_pointer_cast(mc.map); + REQUIRE(untyped_map != nullptr); + + tx.retain_change_set("public:dup", std::move(mc.changeset), mc.map); + + auto duplicate_cs = untyped_map->create_change_set(0, false); + REQUIRE_THROWS_WITH_AS( + tx.retain_change_set("public:dup", std::move(duplicate_cs), mc.map), + "Re-creating change set for map public:dup", + std::logic_error); + } + + SUBCASE( + "get_map_and_change_set_by_name rejects duplicate created map without " + "handle") + { + TestBaseTx tx(&store); + auto mc = tx.get_map_and_change_set_by_name("public:unretained", false); + REQUIRE(mc.map != nullptr); + + REQUIRE_THROWS_WITH_AS( + tx.get_map_and_change_set_by_name("public:unretained", false), + "Created map without creating handle over it", + std::logic_error); + } + + SUBCASE("get_map_and_change_set_by_name rejects non-untyped AbstractMap") + { + class WrongMapStore : public ccf::kv::Store + { + public: + std::shared_ptr get_map( + ccf::kv::Version, const std::string& map_name) override + { + return std::make_shared(map_name); + } + }; + + WrongMapStore wrong_store; + ccf::kv::ReadOnlyTx tx(&wrong_store); + REQUIRE_THROWS_WITH_AS( + tx.ro("public:wrong_type"), + "Map public:wrong_type has unexpected type", + std::logic_error); + } + + SUBCASE("compacted_version_conflict requires read_txid to be set") + { + TestBaseTx tx(&store); + REQUIRE_THROWS_WITH_AS( + tx.compacted_version_conflict("public:map"), + "read_txid should have already been set", + std::logic_error); + } +} + int main(int argc, char** argv) { ccf::logger::config::default_init(); diff --git a/src/node/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index 442da3085183..6d9ded974d4e 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -1,17 +1,18 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. +#include "ccf/crypto/eddsa_key_pair.h" #include "ccf/crypto/pem.h" #include "ccf/crypto/verifier.h" -#include "ccf/node/node_configuration_interface.h" +#include "crypto/certs.h" #include "crypto/openssl/hash.h" -#include "crypto/openssl/mldsa_support.h" #include "ds/internal_logger.h" #include "frontend_test_infra.h" #include "kv/null_encryptor.h" #include "nlohmann/json.hpp" #include "node/http_node_client.h" #include "node/internal_tables_access.h" +#include "node/node_configuration_state.h" #include "node/rpc/node_frontend.h" #include "node/rpc/self_cert_auth.h" #include "node/startup_inputs.h" @@ -19,6 +20,7 @@ #include #include +#include #include #include #include @@ -80,7 +82,7 @@ class TestNodeRpcFrontend : public NodeRpcFrontend } }; -class StubNodeConfiguration : public NodeConfigurationInterface +class StubNodeConfiguration : public NodeConfigurationStateInterface { public: CCFConfig config = {}; @@ -108,6 +110,7 @@ TEST_CASE("Node configuration retains operator file paths") { const json input = { {"network", CCFConfig{}.network}, + {"node_certificate", {{"id_format", "did:key"}}}, {"node_data_json_file", "not-loaded/node.json"}, {"service_data_json_file", "not-loaded/service.json"}, {"tick_interval", "25ms"}, @@ -141,6 +144,7 @@ TEST_CASE("Node configuration retains operator file paths") {"service_mldsa_parameter_set", "ML-DSA-44"}}}}}}; auto config = input.get(); + CHECK(config.node_certificate.id_format == IdentityIdFormat::DIDKey); CHECK(config.command.type == StartType::Start); CHECK( config.command.start.members.front().certificate_file == @@ -205,6 +209,7 @@ TEST_CASE("Node configuration retains operator file paths") {{"type", "Join"}}}}.get(); CHECK(defaults.command.join.retry_timeout.count_ms() == 1000); CHECK(defaults.command.join.follow_redirect); + CHECK(defaults.node_certificate.id_format == IdentityIdFormat::SHA256); CHECK(defaults.command.join.fetch_recent_snapshot); CHECK( defaults.command.recover.initial_service_certificate_validity_days == 1); @@ -383,13 +388,17 @@ TEST_CASE("Startup inputs are read from files") MemberRecoveryRole::Owner}); start.members.push_back( {write_test_file(dir, "member1_cert.pem", member_cert.str())}); + ParsedMemberInfo did_member; + did_member.did_key = ccf::crypto::did_key_from_public_key_der( + ccf::crypto::make_verifier(member_cert)->public_key_der()); + start.members.push_back(did_member); start.constitution_files = { write_test_file(dir, "first.js", "first"), write_test_file(dir, "second.js", "second")}; start.service_configuration.recovery_threshold = 1; const auto genesis = resolve_genesis_info(start); - REQUIRE(genesis.members.size() == 2); + REQUIRE(genesis.members.size() == 3); CHECK(genesis.members[0].cert == member_cert); CHECK(genesis.members[0].encryption_pub_key == encryption_key); CHECK(genesis.members[0].member_data == json{{"is_operator", true}}); @@ -398,6 +407,11 @@ TEST_CASE("Startup inputs are read from files") CHECK_FALSE(genesis.members[1].encryption_pub_key.has_value()); CHECK(genesis.members[1].member_data.is_null()); CHECK_FALSE(genesis.members[1].recovery_role.has_value()); + CHECK(genesis.members[2].cert.empty()); + CHECK(genesis.members[2].did_key == did_member.did_key); + auto conflicting = start; + conflicting.members[2].certificate_file = "must-not-be-read.pem"; + CHECK_THROWS_AS(resolve_genesis_info(conflicting), std::logic_error); CHECK(genesis.constitution == "first\nsecond"); CHECK(genesis.service_configuration == start.service_configuration); @@ -410,7 +424,7 @@ TEST_CASE("Startup inputs are read from files") CHECK( logic_error_message([&]() { resolve_genesis_info(empty_member_data); }) .starts_with( - fmt::format("Could not parse member data from {}:", empty_file))); + std::format("Could not parse member data from {}:", empty_file))); } { @@ -418,7 +432,7 @@ TEST_CASE("Startup inputs are read from files") const auto malformed_file = write_test_file(dir, "malformed.json", "{"); CHECK(logic_error_message( [&]() { read_startup_json(malformed_file, "node data", true); }) - .starts_with(fmt::format( + .starts_with(std::format( "Could not parse node data from {}:", malformed_file))); } @@ -428,17 +442,17 @@ TEST_CASE("Startup inputs are read from files") CHECK( logic_error_message( [&]() { read_startup_file(missing_file, "service certificate"); }) == - fmt::format("Could not read service certificate from {}", missing_file)); + std::format("Could not read service certificate from {}", missing_file)); CHECK( logic_error_message( [&]() { read_startup_file(dir.path.string(), "constitution"); }) == - fmt::format("Could not read constitution from {}", dir.path.string())); + std::format("Could not read constitution from {}", dir.path.string())); auto missing_constitution = start; missing_constitution.constitution_files.push_back(missing_file); CHECK( logic_error_message([&]() { resolve_genesis_info(missing_constitution); - }) == fmt::format("Could not read constitution from {}", missing_file)); + }) == std::format("Could not read constitution from {}", missing_file)); } } @@ -521,7 +535,7 @@ TEST_CASE("Startup inputs are resolved by start type") CHECK( logic_error_message( [&]() { resolve_startup_inputs(no_service_cert, StartType::Join); }) == - fmt::format("Could not read service certificate from {}", missing_file)); + std::format("Could not read service certificate from {}", missing_file)); auto no_service_data = config; no_service_data.service_data_json_file = missing_file; @@ -530,7 +544,7 @@ TEST_CASE("Startup inputs are resolved by start type") CHECK( logic_error_message([&]() { resolve_startup_inputs(no_service_data, type); - }) == fmt::format("Could not read service data from {}", missing_file)); + }) == std::format("Could not read service data from {}", missing_file)); } auto no_node_data = config; @@ -541,7 +555,7 @@ TEST_CASE("Startup inputs are resolved by start type") CHECK( logic_error_message([&]() { resolve_startup_inputs(no_node_data, type); - }) == fmt::format("Could not read node data from {}", missing_file)); + }) == std::format("Could not read node data from {}", missing_file)); } } } @@ -620,6 +634,323 @@ TEST_CASE("Self certificate authentication") CHECK(error_reason.contains("before certificate's Not Before")); } +TEST_CASE("Node state is explicitly nontransactional metadata") +{ + class MinimalNodeState : public ccf::AbstractNodeState + { + ccf::CCFConfig config = {}; + nlohmann::json node_data = nullptr; + + public: + void transition_service_to_open( + ccf::kv::Tx&, AbstractGovernanceEffects::ServiceIdentities) override + { + throw std::logic_error("Unimplemented"); + } + + bool rekey_ledger(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + void trigger_recovery_shares_refresh(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + void trigger_ledger_chunk(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + void trigger_snapshot(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + [[nodiscard]] bool is_in_initialised_state() const override + { + return false; + } + + [[nodiscard]] bool is_part_of_public_network() const override + { + return false; + } + + [[nodiscard]] bool is_primary() const override + { + return false; + } + + bool can_replicate() override + { + return false; + } + + std::optional get_primary() override + { + return std::nullopt; + } + + [[nodiscard]] bool is_reading_public_ledger() const override + { + return false; + } + + [[nodiscard]] bool is_reading_private_ledger() const override + { + return false; + } + + [[nodiscard]] bool is_part_of_network() const override + { + return false; + } + + ccf::kv::Version get_last_recovered_signed_idx() override + { + return 0; + } + + void initiate_private_recovery(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + ExtendedState state() override + { + return {NodeStartupState::uninitialized, std::nullopt, std::nullopt}; + } + + QuoteVerificationResult verify_quote( + ccf::kv::ReadOnlyTx&, + const QuoteInfo&, + const std::vector&, + pal::PlatformAttestationMeasurement&, + const std::optional>&, + std::shared_ptr) override + { + throw std::logic_error("Unimplemented"); + } + + ccf::kv::Version get_startup_snapshot_seqno() override + { + return 0; + } + + SessionMetrics get_session_metrics() override + { + return {}; + } + + ccf::crypto::Pem get_self_signed_certificate() override + { + return {}; + } + + const ccf::COSESignaturesConfig& get_cose_signatures_config() override + { + throw std::logic_error("Unimplemented"); + } + + RecoveryDecisionProtocolSubsystem& get_recovery_decision_protocol() override + { + throw std::logic_error("Unimplemented"); + } + + void shuffle_sealed_shares(ccf::kv::Tx&) override + { + throw std::logic_error("Unimplemented"); + } + + [[nodiscard]] const ccf::CCFConfig& get_node_config() const override + { + return config; + } + + [[nodiscard]] const nlohmann::json& get_node_data() const override + { + return node_data; + } + + ccf::crypto::Pem get_network_cert() override + { + return {}; + } + + void stop_notice() override {} + + bool has_received_stop_notice() override + { + return false; + } + + bool is_member_frontend_open() override + { + return false; + } + + bool is_user_frontend_open() override + { + return false; + } + + [[nodiscard]] bool is_accessible_to_members() const override + { + return false; + } + + std::shared_ptr get_store() override + { + return nullptr; + } + }; + + class RollbackingStore : public ccf::kv::Store + { + public: + std::function on_signature_lookup = nullptr; + + std::shared_ptr get_map( + ccf::kv::Version version, const std::string& name) override + { + if (name == Tables::SIGNATURES && on_signature_lookup != nullptr) + { + auto callback = std::exchange(on_signature_lookup, nullptr); + callback(); + } + return ccf::kv::Store::get_map(version, name); + } + }; + + NetworkState network; + auto store = std::make_shared(); + network.tables = store; + network.tables->set_encryptor(std::make_shared()); + auto consensus = std::make_shared(); + network.tables->set_consensus(consensus); + network.tables->initialise_term(2); + + auto publish_signature = [&](ccf::kv::Version reported_seqno) { + const auto txid = network.tables->next_txid(); + auto tx = network.tables->create_reserved_tx(txid); + tx.wo(Tables::SIGNATURES) + ->put( + ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, reported_seqno)); + tx.wo(Tables::SERIALISED_MERKLE_TREE)->put({}); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + network.tables->commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::SUCCESS); + }; + + // Record a higher signed seqno in the KV so pre-readiness checks fail if + // they accidentally read from the store instead of node progress metadata. + constexpr ccf::kv::Version kv_signed_seqno = 99; + publish_signature(kv_signed_seqno); + + MinimalNodeState node_state; + StubNodeContext context; + context.install_subsystem(std::make_shared( + node_state, NodeConfigurationSubsystem::InterfaceRegexes{})); + TestNodeRpcFrontend frontend(network, context); + frontend.open(); + + ::http::Request request("state", HTTP_GET); + auto session = std::make_shared( + ccf::InvalidSessionId, std::vector{}); + auto rpc_ctx = ccf::make_rpc_context(session, request.build_request()); + const auto endpoint = + frontend.get_node_endpoints().find_endpoint_without_kv(*rpc_ctx); + REQUIRE(endpoint != nullptr); + CHECK( + endpoint->execution_mode == ccf::endpoints::EndpointExecutionMode::Command); + CHECK( + endpoint->properties.forwarding_required == + ccf::endpoints::ForwardingRequired::Never); + CHECK(endpoint->authn_policies.empty()); + + for (const auto readiness : + {ccf::kv::StoreReadiness::Unavailable, + ccf::kv::StoreReadiness::InstallingSnapshot}) + { + network.tables->set_readiness(readiness); + context.node_operation->extended_state = { + NodeStartupState::readingPublicLedger, std::nullopt, std::nullopt}; + + for (const auto& [recovered, startup, expected] : std::vector< + std::tuple>{ + {25, 10, 25}, {10, 40, 40}}) + { + context.node_operation->last_recovered_signed_idx = recovered; + context.node_operation->startup_snapshot_seqno = startup; + + const auto response = + frontend_process(frontend, nullptr, "state", {}, HTTP_GET); + REQUIRE(response.status == HTTP_STATUS_OK); + CHECK_FALSE(response.headers.contains(ccf::http::headers::CCF_TX_ID)); + + const auto out = parse_response_body(response); + CHECK(out.state == NodeStartupState::readingPublicLedger); + CHECK(out.startup_seqno == startup); + CHECK(out.last_signed_seqno == expected); + } + } + + network.tables->set_readiness(ccf::kv::StoreReadiness::Ready); + context.node_operation->extended_state = { + NodeStartupState::partOfNetwork, std::nullopt, std::nullopt}; + context.node_operation->last_recovered_signed_idx = 0; + context.node_operation->startup_snapshot_seqno = 10; + + const auto response = + frontend_process(frontend, nullptr, "state", {}, HTTP_GET); + REQUIRE(response.status == HTTP_STATUS_OK); + CHECK_FALSE(response.headers.contains(ccf::http::headers::CCF_TX_ID)); + const auto out = parse_response_body(response); + CHECK(out.state == NodeStartupState::partOfNetwork); + CHECK(out.startup_seqno == 10); + CHECK(out.last_signed_seqno == kv_signed_seqno); + + // Regression: if readiness flips to Ready after RpcFrontend enters + // process_command_without_kv(), a concurrent rollback during get_state()'s + // signature lookup throws CompactedVersionConflict (not a std::exception). + // The frontend must catch and retry it rather than terminating the node. + constexpr ccf::kv::Version post_rollback_seqno = 105; + bool transitioned_to_ready = false; + bool rollback_triggered = false; + network.tables->set_readiness(ccf::kv::StoreReadiness::Unavailable); + context.node_operation->on_state = [&]() { + transitioned_to_ready = true; + network.tables->set_readiness(ccf::kv::StoreReadiness::Ready); + context.node_operation->on_state = nullptr; + }; + store->on_signature_lookup = [&]() { + rollback_triggered = true; + network.tables->rollback({2, 0}, 3); + consensus->view_history.rollback(0); + consensus->flush(); + publish_signature(post_rollback_seqno); + }; + + const auto raced_response = + frontend_process(frontend, nullptr, "state", {}, HTTP_GET); + CHECK(transitioned_to_ready); + CHECK(rollback_triggered); + REQUIRE(raced_response.status == HTTP_STATUS_OK); + CHECK_FALSE(raced_response.headers.contains(ccf::http::headers::CCF_TX_ID)); + const auto raced_out = parse_response_body(raced_response); + CHECK(raced_out.last_signed_seqno == post_rollback_seqno); +} + TEST_CASE("Pending-node cleanup uses renewed client certificates") { NetworkState network; @@ -675,6 +1006,13 @@ TEST_CASE("Pending-node cleanup uses renewed client certificates") TEST_CASE("Add a node to an opening service") { + auto id_format = IdentityIdFormat::SHA256; + SUBCASE("Legacy node ID") {} + SUBCASE("DID node ID") + { + id_format = IdentityIdFormat::DIDKey; + } + NetworkState network; auto tx_encryptor = std::make_shared(); network.tables->set_encryptor(tx_encryptor); @@ -704,8 +1042,9 @@ TEST_CASE("Add a node to an opening service") INFO("Add first node before a service exists"); { JoinNetworkNodeToNode::In join_input; + join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + join_input.mldsa_supported = true; const auto response = frontend_process(frontend, join_input, "join", caller); @@ -719,15 +1058,11 @@ TEST_CASE("Add a node to an opening service") auto tx = network.tables->create_tx(); INFO("A service with an ML-DSA identity only admits ML-DSA capable nodes"); - REQUIRE( - network.identity->pq_cert.has_value() == ccf::crypto::mldsa_supported()); - // Without ML-DSA the service has no such identity, and the main flow below - // shows that a joiner declaring no support is then accepted - if (ccf::crypto::mldsa_supported()) + REQUIRE(network.identity->pq_cert.has_value()); { auto pk_der = node_kp->public_key_der(); const NodeId joiner_node_id = ccf::crypto::Sha256Hash(pk_der).hex_str(); - // Nodes of this build without ML-DSA, and nodes that predate the field + // Nodes that declare no ML-DSA support, and nodes that predate the field const std::vector> incapable = {false, std::nullopt}; for (const auto& declared : incapable) { @@ -744,11 +1079,48 @@ TEST_CASE("Add a node to an opening service") } } + const NodeId tls_peer{std::string(64, '1')}; + const std::map expected_tls_addresses{ + {tls_peer, "tls-peer.example:8082"}}; + { + auto peers_tx = network.tables->create_tx(); + auto* peers = peers_tx.rw(network.nodes); + const auto add_peer = [peers, &node_public_encryption_key]( + const NodeId& id, + NodeStatus status, + const std::optional& tls_address) { + NodeInfo info; + info.encryption_pub_key = node_public_encryption_key; + info.status = status; + info.node_to_node_interface.published_address = + std::format("{}.example:8081", id.value()); + if (tls_address.has_value()) + { + info.node_to_node_tls_interface = NodeInfoNetwork::NodeToNodeInterface{ + "localhost:8082", tls_address.value()}; + } + peers->put(id, info); + }; + add_peer( + tls_peer, NodeStatus::TRUSTED, expected_tls_addresses.at(tls_peer)); + add_peer(NodeId{std::string(64, '2')}, NodeStatus::TRUSTED, std::nullopt); + add_peer( + NodeId{std::string(64, '3')}, + NodeStatus::PENDING, + "pending-peer.example:8082"); + add_peer( + NodeId{std::string(64, '4')}, + NodeStatus::RETIRED, + "retired-peer.example:8082"); + REQUIRE(peers_tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + INFO("Add first node which should be trusted straight away"); { JoinNetworkNodeToNode::In join_input; + join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + join_input.mldsa_supported = true; // Join input does not include CSR (1.x) join_input.certificate_signing_request = std::nullopt; @@ -762,11 +1134,14 @@ TEST_CASE("Add a node to an opening service") CHECK(response.network_info.has_value()); CHECK(response.network_info->identity == *network.identity.get()); CHECK(response.network_info->public_only == false); + CHECK( + response.network_info->node_to_node_tls_addresses == + expected_tls_addresses); // No endorsed certificate since no CSR was passed in CHECK(response.network_info->endorsed_certificate == std::nullopt); - auto pk_der = node_kp->public_key_der(); - const NodeId joiner_node_id = ccf::crypto::Sha256Hash(pk_der).hex_str(); + const auto joiner_node_id = compute_node_id_from_kp(node_kp, id_format); + CHECK(response.node_id == joiner_node_id); auto nodes = tx.rw(network.nodes); auto node_info = nodes->get(joiner_node_id); @@ -775,6 +1150,30 @@ TEST_CASE("Add a node to an opening service") CHECK(node_kp->public_key_pem() == node_info->public_key); } + INFO("A key outside the did:key profile cannot request a DID node ID"); + { + const auto eddsa_kp = + ccf::crypto::make_eddsa_key_pair(ccf::crypto::CurveID::CURVE25519); + const auto unsupported_caller = ccf::crypto::create_endorsed_cert( + eddsa_kp->public_key_pem(), + "CN=Unsupported Joiner", + {}, + valid_from, + valid_to, + node_kp->private_key_pem(), + caller); + JoinNetworkNodeToNode::In join_input; + join_input.id_format = IdentityIdFormat::DIDKey; + join_input.public_encryption_key = node_public_encryption_key; + const auto response = + frontend_process(frontend, join_input, "join", unsupported_caller); + check_error(response, HTTP_STATUS_BAD_REQUEST); + check_error_message( + response, "cannot be identified in the requested format"); + auto verify_tx = network.tables->create_tx(); + CHECK(verify_tx.ro(network.nodes)->size() == 5); + } + INFO("Adding the same node should return the same result"); { // Even if rekey occurs in between, the same ledger secrets should be @@ -783,10 +1182,14 @@ TEST_CASE("Add a node to an opening service") up_to_ledger_secret_seqno + 1, make_ledger_secret()); JoinNetworkNodeToNode::In join_input; + join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + join_input.mldsa_supported = true; - auto http_response = frontend_process(frontend, join_input, "join", caller); + const auto replacement = + node_kp->self_sign("CN=Replacement", valid_from, valid_to); + auto http_response = + frontend_process(frontend, join_input, "join", replacement); CHECK(http_response.status == HTTP_STATUS_OK); const auto response = @@ -798,6 +1201,9 @@ TEST_CASE("Add a node to an opening service") response.network_info->ledger_secrets, network.ledger_secrets->get(tx, up_to_ledger_secret_seqno)); CHECK(response.network_info->identity == *network.identity.get()); + CHECK( + response.network_info->node_to_node_tls_addresses == + expected_tls_addresses); } INFO( @@ -811,7 +1217,7 @@ TEST_CASE("Add a node to an opening service") // Network node info is empty (same as before) JoinNetworkNodeToNode::In join_input; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + join_input.mldsa_supported = true; auto http_response = frontend_process(frontend, join_input, "join", new_caller); @@ -870,6 +1276,13 @@ TEST_CASE("JWT refresh metrics are thread-safe") TEST_CASE("Add a node to an open service") { + auto id_format = IdentityIdFormat::SHA256; + SUBCASE("Legacy node ID") {} + SUBCASE("DID node ID") + { + id_format = IdentityIdFormat::DIDKey; + } + NetworkState network; auto gen_tx = network.tables->create_tx(); auto tx_encryptor = std::make_shared(); @@ -914,8 +1327,9 @@ TEST_CASE("Add a node to an open service") ccf::crypto::make_ec_key_pair()->public_key_pem(); JoinNetworkNodeToNode::In join_input; + join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + join_input.mldsa_supported = true; join_input.certificate_signing_request = node_kp->create_csr("CN=Joiner"); INFO("Add node once service is open"); @@ -929,8 +1343,8 @@ TEST_CASE("Add a node to an open service") CHECK(!response.network_info.has_value()); - auto pk_der = node_kp->public_key_der(); - const NodeId joiner_node_id = ccf::crypto::Sha256Hash(pk_der).hex_str(); + const auto joiner_node_id = compute_node_id_from_kp(node_kp, id_format); + CHECK(response.node_id == joiner_node_id); auto nodes = tx.rw(network.nodes); auto node_info = nodes->get(joiner_node_id); CHECK(node_info.has_value()); @@ -949,7 +1363,7 @@ TEST_CASE("Add a node to an open service") // Network node info is empty (same as before) JoinNetworkNodeToNode::In other_join_input; other_join_input.public_encryption_key = node_public_encryption_key; - other_join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + other_join_input.mldsa_supported = true; auto http_response = frontend_process(frontend, other_join_input, "join", new_caller); @@ -975,7 +1389,7 @@ TEST_CASE("Add a node to an open service") { auto tx = network.tables->create_tx(); // In a real scenario, nodes are trusted via member governance. - auto joining_node_id = ccf::compute_node_id_from_kp(node_kp); + auto joining_node_id = ccf::compute_node_id_from_kp(node_kp, id_format); InternalTablesAccess::trust_node( tx, joining_node_id, network.ledger_secrets->get_latest(tx).first); const auto dummy_endorsed_certificate = @@ -1030,7 +1444,7 @@ TEST_CASE("Add a node to an open service") JoinNetworkNodeToNode::In expired_join_input; expired_join_input.public_encryption_key = ccf::crypto::make_ec_key_pair()->public_key_pem(); - expired_join_input.mldsa_supported = ccf::crypto::mldsa_supported(); + expired_join_input.mldsa_supported = true; expired_join_input.certificate_signing_request = expired_node_kp->create_csr("CN=Expired Joiner"); expired_join_input.node_info_network.node_to_node_interface @@ -1144,7 +1558,8 @@ TEST_CASE("Add a node to an open service") std::chrono::duration_cast( std::chrono::hours(2)) .count(); - const auto trusted_node_id = ccf::compute_node_id_from_kp(node_kp); + const auto trusted_node_id = + ccf::compute_node_id_from_kp(node_kp, id_format); set_last_seen(expired_node_id, expired); set_last_seen(trusted_node_id, expired); @@ -1200,7 +1615,7 @@ TEST_CASE("File range parsing preserves half-open bounds") {"bytes=99-99", 100, 99, 100}, {"bytes=0-100", 100, 0, 100}, {"bytes=10-100", 100, 10, 100}, - {fmt::format("bytes=0-{}", max), 100, 0, 100}, + {std::format("bytes=0-{}", max), 100, 0, 100}, {"bytes=0-", 100, 0, 100}, {"bytes=10-", 100, 10, 100}, {"bytes=99-", 100, 99, 100}, @@ -1208,7 +1623,7 @@ TEST_CASE("File range parsing preserves half-open bounds") {"bytes=-20", 100, 80, 100}, {"bytes=-100", 100, 0, 100}, {"bytes=-101", 100, 0, 100}, - {fmt::format("bytes=-{}", max), 100, 0, 100}, + {std::format("bytes=-{}", max), 100, 0, 100}, {"bytes=010-019", 100, 10, 20}, {"bytes=10x-19y", 100, 10, 20}, {"bytes=10 -19 ", 100, 10, 20}, @@ -1222,12 +1637,12 @@ TEST_CASE("File range parsing preserves half-open bounds") {"bytes=100-100", 100, 100, 100}, {"bytes=0-0", 1, 0, 1}, {"bytes=-1", 1, 0, 1}, - {fmt::format("bytes=0-{}", max), max, 0, max}, - {fmt::format("bytes={}-{}", max - 1, max), max, max - 1, max}, - {fmt::format("bytes={}-", max - 1), max, max - 1, max}, - {fmt::format("bytes=-{}", max), max, 0, max}, - {fmt::format("bytes={}-", max), max, max, max}, - {fmt::format("bytes={}-{}", max, max), max, max, max}}; + {std::format("bytes=0-{}", max), max, 0, max}, + {std::format("bytes={}-{}", max - 1, max), max, max - 1, max}, + {std::format("bytes={}-", max - 1), max, max - 1, max}, + {std::format("bytes=-{}", max), max, 0, max}, + {std::format("bytes={}-", max), max, max, max}, + {std::format("bytes={}-{}", max, max), max, max, max}}; for (const auto& test : cases) { @@ -1282,18 +1697,18 @@ TEST_CASE("File range parsing preserves exact errors") {"bytes=101-foo", "Start of range 101 is larger than total file size 100"}, {"bytes=50-48", "Invalid range: Start (50) and end (49) out of order"}, {"bytes=99-0", "Invalid range: Start (99) and end (1) out of order"}, - {fmt::format("bytes={}-", overflow), - fmt::format( + {std::format("bytes={}-", overflow), + std::format( "Unable to parse start of range value {} in bytes={}-", overflow, overflow)}, - {fmt::format("bytes=0-{}", overflow), - fmt::format( + {std::format("bytes=0-{}", overflow), + std::format( "Unable to parse end of range value {} in bytes=0-{}", overflow, overflow)}, - {fmt::format("bytes=-{}", overflow), - fmt::format( + {std::format("bytes=-{}", overflow), + std::format( "Unable to parse end of range offset value {} in bytes=-{}", overflow, overflow)}}; @@ -1333,7 +1748,7 @@ TEST_CASE("File range responses preserve GET and HEAD metadata") {"bytes=10-", 10, 100}, {"bytes=-20", 80, 100}, {"bytes=-101", 0, 100}, - {fmt::format("bytes=0-{}", std::numeric_limits::max()), 0, 100}, + {std::format("bytes=0-{}", std::numeric_limits::max()), 0, 100}, {"bytes=10junk-19junk", 10, 20}}; for (const auto& test : cases) @@ -1372,7 +1787,7 @@ TEST_CASE("File range responses preserve GET and HEAD metadata") { CHECK( headers.at(ccf::http::headers::CONTENT_RANGE) == - fmt::format("bytes {}-{}/100", test.start, test.end - 1)); + std::format("bytes {}-{}/100", test.start, test.end - 1)); } else { @@ -1382,7 +1797,7 @@ TEST_CASE("File range responses preserve GET and HEAD metadata") bytes.begin() + test.start, bytes.begin() + test.end); CHECK( headers.at(ccf::http::headers::ETAG) == - fmt::format( + std::format( "\"{}\"", ccf::node::format_repr_digest( "sha-256", @@ -1527,11 +1942,11 @@ TEST_CASE( const std::vector matches = { "*", etag, - fmt::format( + std::format( "\"{}\"", ccf::node::format_repr_digest( "sha-384", ccf::crypto::MDType::SHA384, body.data(), body.size())), - fmt::format( + std::format( "\"{}\"", ccf::node::format_repr_digest( "sha-512", ccf::crypto::MDType::SHA512, body.data(), body.size()))}; @@ -1583,7 +1998,7 @@ TEST_CASE( etag); for (const auto& invalid_match : - std::vector{"not etags", fmt::format("W/{}", etag)}) + std::vector{"not etags", std::format("W/{}", etag)}) { headers[ccf::http::headers::IF_NONE_MATCH] = invalid_match; const auto invalid_response = diff --git a/src/node/test/historical_queries.cpp b/src/node/test/historical_queries.cpp index 586d42255f1b..3ba0384ca70c 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -8,6 +8,7 @@ #include "node/historical_queries.h" #include "ccf/crypto/rsa_key_pair.h" +#include "ccf/ds/join.h" #include "ccf/ds/locking.h" #include "ccf/receipt.h" #include "consensus/test/ledger_stub.h" @@ -22,7 +23,9 @@ #include "node/signature_cache_subsystem.h" #include +#include #include +#include #include #include #include @@ -47,7 +50,9 @@ struct TestState std::shared_ptr service_kp = nullptr; }; -TestState create_and_init_state(bool initialise_ledger_rekey = true) +TestState create_and_init_state( + bool initialise_ledger_rekey = true, + ccf::crypto::MLDSAKeyPairPtr pq_service_kp = nullptr) { TestState ts; @@ -66,7 +71,7 @@ TestState create_and_init_state(bool initialise_ledger_rekey = true) std::make_shared(*ts.kv_store, node_id, *ts.node_kp); h->set_endorsed_certificate({}); h->set_service_signing_identity( - ts.service_kp, nullptr, ccf::COSESignaturesConfig{}); + ts.service_kp, std::move(pq_service_kp), ccf::COSESignaturesConfig{}); ts.kv_store->set_history(h); ts.kv_store->initialise_term(2); @@ -1802,6 +1807,7 @@ TEST_CASE("Historical receipts preserve the transaction view across signatures") ccf::NodeId{"node_id"}, *state.node_kp, *state.service_kp, + nullptr, cert, history->get_cose_signatures_config(), signing_mode), @@ -1959,39 +1965,94 @@ TEST_CASE("Historical cache rejects signatures which misreport their TxID") // Write a signature transaction by hand, which declares a TxID in a later // view than the one it is actually committed in - const auto signature_seqno = store.current_version() + 1; - const ccf::TxID declared_id{store.current_txid().view + 1, signature_seqno}; + const auto signature_txid = store.next_txid(); + const auto signature_seqno = signature_txid.seqno; + const ccf::TxID declared_id{signature_txid.view + 1, signature_seqno}; { - auto tx = store.create_tx(); - const auto root = history->get_replicated_state_root(); - const std::vector root_hash(root.h.begin(), root.h.end()); - if (signing_mode == ccf::LedgerSignMode::Dual) + class MisreportedSignatureTx : public ccf::kv::PendingTx { - tx.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature( - ccf::NodeId{"node_id"}, - declared_id.seqno, - declared_id.view, - root, - {}, - state.node_kp->sign_hash(root_hash.data(), root_hash.size()), - node_cert)); - } - const auto& cose_config = history->get_cose_signatures_config(); - tx.wo(ccf::Tables::COSE_SIGNATURES) - ->put( - ccf::IdentityType::CLASSICAL, - ccf::cose::sign_ledger( - *state.service_kp, - ccf::crypto::kid_from_key(state.service_kp->public_key_der()), - 0, - cose_config.issuer, - cose_config.subject, - declared_id.to_str(), - root_hash)); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put(history->serialise_tree(signature_seqno - 1)); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + ccf::kv::Store& store; + ccf::TxID txid; + ccf::TxID declared_id; + ccf::LedgerSignMode signing_mode; + ccf::crypto::Sha256Hash root; + std::vector serialised_tree; + ccf::crypto::ECKeyPairPtr node_kp; + ccf::crypto::Pem node_cert; + ccf::crypto::ECKeyPairPtr service_kp; + ccf::COSESignaturesConfig cose_config; + + public: + MisreportedSignatureTx( + ccf::kv::Store& store_, + ccf::TxID txid_, + ccf::TxID declared_id_, + ccf::LedgerSignMode signing_mode_, + ccf::crypto::Sha256Hash root_, + std::vector serialised_tree_, + ccf::crypto::ECKeyPairPtr node_kp_, + ccf::crypto::Pem node_cert_, + ccf::crypto::ECKeyPairPtr service_kp_, + ccf::COSESignaturesConfig cose_config_) : + store(store_), + txid(txid_), + declared_id(declared_id_), + signing_mode(signing_mode_), + root(root_), + serialised_tree(std::move(serialised_tree_)), + node_kp(std::move(node_kp_)), + node_cert(std::move(node_cert_)), + service_kp(std::move(service_kp_)), + cose_config(std::move(cose_config_)) + {} + + ccf::kv::PendingTxInfo call() override + { + auto tx = store.create_reserved_tx(txid); + const std::vector root_hash(root.h.begin(), root.h.end()); + if (signing_mode == ccf::LedgerSignMode::Dual) + { + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature( + ccf::NodeId{"node_id"}, + declared_id.seqno, + declared_id.view, + root, + {}, + node_kp->sign_hash(root_hash.data(), root_hash.size()), + node_cert)); + } + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put( + ccf::IdentityType::CLASSICAL, + ccf::cose::sign_ledger( + *service_kp, + ccf::crypto::kid_from_key(service_kp->public_key_der()), + 0, + cose_config.issuer, + cose_config.subject, + declared_id.to_str(), + root_hash)); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put(serialised_tree); + return tx.commit_reserved(); + } + }; + + auto pending = std::make_unique( + store, + signature_txid, + declared_id, + signing_mode, + history->get_replicated_state_root(), + history->serialise_tree(signature_seqno - 1), + state.node_kp, + node_cert, + state.service_kp, + history->get_cose_signatures_config()); + REQUIRE( + store.commit(signature_txid, std::move(pending), true) == + ccf::kv::CommitResult::SUCCESS); } const auto signature_id = store.current_txid(); REQUIRE(signature_id.seqno == signature_seqno); @@ -2167,13 +2228,13 @@ TEST_CASE("StateCache point queries") cache.drop_cached_states(low_handle); cache.drop_cached_states(high_handle); - INFO(fmt::format( + INFO(std::format( "Signature transactions can be requested between {} and {}", low_signature_transaction, high_signature_transaction)); for (const auto i : {low_signature_transaction, high_signature_transaction}) { - INFO(fmt::format("Requesting signature at {}", i)); + INFO(std::format("Requesting signature at {}", i)); auto state_at_seqno = cache.get_state_at(default_handle, i); REQUIRE(state_at_seqno == nullptr); @@ -2182,7 +2243,7 @@ TEST_CASE("StateCache point queries") state_at_seqno = cache.get_state_at(default_handle, i); REQUIRE(state_at_seqno != nullptr); - INFO(fmt::format("Receipt for transaction at {}", i)); + INFO(std::format("Receipt for transaction at {}", i)); REQUIRE(state_at_seqno->receipt.get() != nullptr); } @@ -3187,13 +3248,13 @@ namespace size_t i, const std::vector& previously_requested) { - std::cout << fmt::format( + std::cout << std::format( "Thread <{}>, i [{}]: {} - still no answer!", handle, i, previously_requested.back()) << std::endl; - std::cout << fmt::format( + std::cout << std::format( "I've previously used handle {} to request:", handle) << std::endl; for (const auto& s : previously_requested) @@ -3344,7 +3405,7 @@ namespace // Fetch a single point const auto target_seqno = random_seqno(); previously_requested.push_back( - fmt::format("Point {} [{}]", target_seqno, ss)); + std::format("Point {} [{}]", target_seqno, ss)); if (store_or_state) { query_random_point_store(target_seqno, handle, error_printer); @@ -3365,7 +3426,7 @@ namespace std::swap(range_start, range_end); } previously_requested.push_back( - fmt::format("Range {}->{} [{}]", range_start, range_end, ss)); + std::format("Range {}->{} [{}]", range_start, range_end, ss)); if (store_or_state) { query_random_range_stores( @@ -3402,11 +3463,11 @@ namespace for (const auto& [from, additional] : seqnos.get_ranges()) { range_descriptions.push_back( - fmt::format("{}->{}", from, from + additional)); + std::format("{}->{}", from, from + additional)); } - previously_requested.push_back(fmt::format( - "Ranges {} [{}]", fmt::join(range_descriptions, ", "), ss)); + previously_requested.push_back(std::format( + "Ranges {} [{}]", ccf::ds::join(range_descriptions, ", "), ss)); if (store_or_state) { @@ -3581,17 +3642,17 @@ TEST_CASE("StateCache concurrent access") } }; { - messages.push_back(fmt::format( + messages.push_back(std::format( "Handle {} requested stores (no sigs) from 3 to 8", handle_a)); queries.query_random_range_stores(3, 8, handle_a, error_printer); } { - messages.push_back(fmt::format( + messages.push_back(std::format( "Handle {} requested states (with sigs) from 5 to 8", handle_b)); queries.query_random_range_states(5, 8, handle_b, error_printer); } { - messages.push_back(fmt::format( + messages.push_back(std::format( "Handle {} requested states (with sigs) from 3 to 8", handle_b)); queries.query_random_range_states(3, 8, handle_b, error_printer); } @@ -4065,7 +4126,8 @@ TEST_CASE( for (const auto& written_signatures : signature_transactions) { - auto tx = store.create_tx(); + const auto txid = store.next_txid(); + auto tx = store.create_reserved_tx(txid); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); for (const auto& [identity_type, signature] : written_signatures) { @@ -4073,12 +4135,22 @@ TEST_CASE( } tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({}); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + store.commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::SUCCESS); - const auto txid = store.current_txid(); + REQUIRE(store.current_txid() == txid); INFO("Signature transaction: ", txid.to_str()); { - auto read_tx = store.create_read_only_tx(); + auto read_tx = store.create_read_only_tx_at_replicated_state(); REQUIRE( read_tx.ro(ccf::Tables::COSE_SIGNATURES)->size() == 2); @@ -4110,7 +4182,7 @@ TEST_CASE( } } -TEST_CASE("Legacy COSE receipt descriptions select CLASSICAL, not PQ") +TEST_CASE("COSE receipt descriptions: _v1 are CLASSICAL, _v2 take the type") { const ccf::CoseSignature classical_signature{1, 2, 3}; const ccf::CoseSignature pq_signature{4, 5, 6}; @@ -4124,15 +4196,115 @@ TEST_CASE("Legacy COSE receipt descriptions select CLASSICAL, not PQ") std::nullopt); REQUIRE(ccf::describe_cose_signature_v1(receipt) == classical_signature); + REQUIRE( + ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::CLASSICAL) == + classical_signature); + REQUIRE( + ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::PQ) == + pq_signature); REQUIRE( ccf::historical::select_described_cose_signature(receipt.cose_signatures) == classical_signature); + INFO("Endorsements are described for the identity types which have them"); + const ccf::CoseEndorsementsChain classical_endorsements{{7}, {8}}; + const ccf::CoseEndorsementsChain pq_endorsements{{9}}; + REQUIRE_FALSE(ccf::describe_cose_endorsements_v1(receipt).has_value()); + receipt.cose_endorsements[ccf::IdentityType::CLASSICAL] = + classical_endorsements; + REQUIRE( + ccf::describe_cose_endorsements_v1(receipt) == classical_endorsements); + REQUIRE_FALSE( + ccf::describe_cose_endorsements_v2(receipt, ccf::IdentityType::PQ) + .has_value()); + receipt.cose_endorsements[ccf::IdentityType::PQ] = pq_endorsements; + REQUIRE( + ccf::describe_cose_endorsements_v2(receipt, ccf::IdentityType::PQ) == + pq_endorsements); + REQUIRE( + ccf::describe_cose_endorsements_v1(receipt) == classical_endorsements); + receipt.cose_signatures.erase(ccf::IdentityType::CLASSICAL); REQUIRE_FALSE(ccf::describe_cose_signature_v1(receipt).has_value()); + REQUIRE( + ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::PQ) == + pq_signature); REQUIRE_FALSE( ccf::historical::select_described_cose_signature(receipt.cose_signatures) .has_value()); + + receipt.cose_signatures.erase(ccf::IdentityType::PQ); + REQUIRE_FALSE(ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::PQ) + .has_value()); +} + +TEST_CASE("Historical receipts carry a COSE receipt of each identity type") +{ + const auto pq_service_kp = + ccf::crypto::make_mldsa_key_pair(ccf::crypto::MLDSAParameterSet::ML_DSA_65); + auto state = create_and_init_state(true, pq_service_kp); + auto& store = *state.kv_store; + + const auto seqno = write_transactions(store, 1); + const auto signature_seqno = write_transactions_and_signature(store, 0); + REQUIRE(signature_seqno == seqno + 1); + + auto ledger = construct_host_ledger(store.get_consensus()); + ccf::historical::StateCache cache( + store, + state.ledger_secrets, + std::make_shared()); + REQUIRE(cache.get_state_range(0, seqno, signature_seqno).empty()); + cache.tick(std::chrono::milliseconds(0)); + REQUIRE(cache.handle_ledger_entry(seqno, ledger.at(seqno))); + REQUIRE( + cache.handle_ledger_entry(signature_seqno, ledger.at(signature_seqno))); + const auto states = cache.get_state_range(0, seqno, signature_seqno); + REQUIRE(states.size() == 2); + REQUIRE(states[0]->receipt != nullptr); + const auto& receipt = *states[0]->receipt; + + const auto classical_receipt = ccf::describe_cose_receipt_v1(receipt); + const auto pq_receipt = + ccf::describe_cose_receipt_v2(receipt, ccf::IdentityType::PQ); + REQUIRE(classical_receipt.has_value()); + REQUIRE(pq_receipt.has_value()); + REQUIRE( + ccf::describe_cose_receipt_v2(receipt, ccf::IdentityType::CLASSICAL) == + classical_receipt); + + INFO("Both receipts prove the transaction against the same signed root"); + const auto decoded_classical = + ccf::cose::decode_ccf_receipt(classical_receipt.value(), true); + const auto decoded_pq = + ccf::cose::decode_ccf_receipt(pq_receipt.value(), true); + REQUIRE(decoded_pq.merkle_root == decoded_classical.merkle_root); + REQUIRE(decoded_pq.phdr.ccf.txid == decoded_classical.phdr.ccf.txid); + REQUIRE(decoded_pq.phdr.alg == ccf::cose::alg::ML_DSA_65); + REQUIRE( + std::string(decoded_pq.phdr.kid.begin(), decoded_pq.phdr.kid.end()) == + ccf::crypto::kid_from_key(pq_service_kp->public_key_der())); + + INFO("Each receipt is signed by the service key of its identity type"); + const auto classical_verifier = ccf::crypto::make_cose_verifier_from_key( + state.service_kp->public_key_pem()); + const auto pq_public_key = pq_service_kp->public_key_der(); + const auto pq_verifier = ccf::crypto::make_cose_verifier_from_key( + std::span(pq_public_key.data(), pq_public_key.size())); + REQUIRE(classical_verifier->verify_detached( + classical_receipt.value(), decoded_classical.merkle_root)); + REQUIRE( + pq_verifier->verify_detached(pq_receipt.value(), decoded_pq.merkle_root)); + REQUIRE_FALSE(pq_verifier->verify_detached( + classical_receipt.value(), decoded_classical.merkle_root)); + REQUIRE_FALSE(classical_verifier->verify_detached( + pq_receipt.value(), decoded_pq.merkle_root)); + + INFO("The signature transaction has a COSE signature of each type"); + REQUIRE(states[1]->receipt != nullptr); + REQUIRE( + ccf::describe_cose_signature_v2(*states[1]->receipt, ccf::IdentityType::PQ) + .has_value()); } // Opt-in: run with --test-case="StateCache tick scaling benchmark" --no-skip @@ -4171,7 +4343,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) constexpr size_t pending = 8; constexpr size_t ticks_per_sample = 200; constexpr size_t sample_count = 7; - fmt::print( + std::cout << std::format( "retained_requests,retained_stores,pending_fetches,tick_ns," "tick_and_mutations_ns,pending_visited,released_checked\n"); for (size_t retained : {0, 7300, 14600, 29200}) @@ -4231,7 +4403,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) REQUIRE(cache.store_slot_count() == 3 * retained + pending + 6); const auto work = cache.tick_work(); - fmt::print( + std::cout << std::format( "{},{},{},{:.0f},{:.0f},{},{}\n", retained, 3 * retained, @@ -4248,7 +4420,8 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) constexpr size_t retained = 7300; constexpr size_t ticks_per_sample = 200; constexpr size_t sample_count = 7; - fmt::print("retained_requests,pending_fetches,tick_ns,pending_visited\n"); + std::cout << std::format( + "retained_requests,pending_fetches,tick_ns,pending_visited\n"); for (size_t pending : {1, 10, 100, 1000}) { auto reader = std::make_shared(); @@ -4273,7 +4446,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) reader->writes.clear(); REQUIRE(cache.tick_work().pending_fetches_visited == pending); } - fmt::print( + std::cout << std::format( "{},{},{:.0f},{}\n", retained, pending, @@ -4285,7 +4458,8 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) SUBCASE("Expiring many requests at once") { constexpr size_t retained = 7300; - fmt::print("retained_requests,due_requests,tick_ns,expired,released\n"); + std::cout << std::format( + "retained_requests,due_requests,tick_ns,expired,released\n"); for (size_t due : {1, 100, 1000}) { auto reader = std::make_shared(); @@ -4309,7 +4483,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) REQUIRE(cache.request_count() == retained); REQUIRE(cache.store_slot_count() == 3 * retained); cache.check_no_expired_slots(); - fmt::print( + std::cout << std::format( "{},{},{:.0f},{},{}\n", retained, due, @@ -4400,7 +4574,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) SUBCASE("Fixed receipt consumers against growing retention") { constexpr size_t consumers = 4; - fmt::print( + std::cout << std::format( "retained,consumers,reply_ns,signature_reply_ns,new_get_ns," "renew_get_ns,range_mutation_ns,index_buckets,index_handles," "index_value_bytes,rss_kb,cache_rss_delta_kb,visited\n"); @@ -4443,7 +4617,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) REQUIRE(cache.drop_cached_states(mutation_handle)); cache.tick(0ms); cache.check_invariants(); - fmt::print( + std::cout << std::format( "{},{},{:.0f},{:.0f},{:.0f},{:.0f},{:.0f},{},{},{},{},{},{}\n", retained, consumers, @@ -4464,7 +4638,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) SUBCASE("Growing real receipt fan-out") { constexpr size_t retained = 7300; - fmt::print( + std::cout << std::format( "retained,consumers,reply_ns,signature_reply_ns,new_get_ns,visited\n"); for (size_t consumers : {1, 10, 100, 1000}) { @@ -4473,7 +4647,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) add_retained(cache, retained); const auto [reply_ns, signature_ns, get_ns] = measure_replies(cache, retained, consumers); - fmt::print( + std::cout << std::format( "{},{},{:.0f},{:.0f},{:.0f},{}\n", retained, consumers, @@ -4498,7 +4672,8 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) ccf::LedgerSecretsMap secrets; secrets.emplace(state.ledger_secrets->get_latest(tx)); recovered.ledger_secrets->restore_historical(std::move(secrets)); - fmt::print("retained,secret_consumers,secret_reply_ns,visited\n"); + std::cout << std::format( + "retained,secret_consumers,secret_reply_ns,visited\n"); auto measure_secret = [&](size_t retained, size_t consumers) { auto reader = std::make_shared(); BenchmarkCache cache( @@ -4518,7 +4693,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) REQUIRE(cache.secret_waiter_count(second_rekey) == 0); REQUIRE(cache.secret_waiter_count(first_rekey) == consumers); cache.check_invariants(); - fmt::print( + std::cout << std::format( "{},{},{:.0f},{}\n", retained, consumers, diff --git a/src/node/test/history.cpp b/src/node/test/history.cpp index 269ddab72973..d2e2fc64601e 100644 --- a/src/node/test/history.cpp +++ b/src/node/test/history.cpp @@ -9,7 +9,6 @@ #include "ccf/service/tables/nodes.h" #include "crypto/certs.h" #include "crypto/openssl/hash.h" -#include "crypto/openssl/mldsa_support.h" #include "ds/internal_logger.h" #include "kv/kv_types.h" #include "kv/null_encryptor.h" @@ -18,12 +17,15 @@ #include "service/tables/signatures.h" #include "service/tables/signing_identities.h" +#include + #define DOCTEST_CONFIG_IMPLEMENT #include #undef FAIL #include #include +#include #include #include #include @@ -79,6 +81,161 @@ class DummyConsensus : public ccf::kv::test::StubConsensus } }; +class CustomSignaturePendingTx : public ccf::kv::PendingTx +{ +public: + using WriteSignatures = std::function; + +private: + ccf::TxID txid; + ccf::kv::Store& store; + ccf::kv::TxHistory& history; + WriteSignatures write_signatures; + +public: + CustomSignaturePendingTx( + ccf::TxID txid_, + ccf::kv::Store& store_, + ccf::kv::TxHistory& history_, + WriteSignatures write_signatures_) : + txid(txid_), + store(store_), + history(history_), + write_signatures(std::move(write_signatures_)) + {} + + ccf::kv::PendingTxInfo call() override + { + auto tx = store.create_reserved_tx(txid); + write_signatures(tx, txid, history.get_replicated_state_root()); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put(history.serialise_tree(txid.seqno - 1)); + return tx.commit_reserved(); + } +}; + +template +ccf::CoseSignature sign_root( + const KeyPair& key, + const ccf::TxID& txid, + const ccf::crypto::Sha256Hash& root) +{ + return ccf::cose::sign_ledger( + key, + ccf::crypto::kid_from_key(key.public_key_der()), + 0, + "", + "", + txid.to_str(), + root.h); +} + +struct SigningFixture +{ + std::shared_ptr encryptor = + std::make_shared(); + ccf::crypto::ECKeyPairPtr node_kp = ccf::crypto::make_ec_key_pair(); + ccf::crypto::Pem node_cert = + node_kp->self_sign("CN=Node", valid_from, valid_to); + std::shared_ptr service_kp = + std::dynamic_pointer_cast( + ccf::crypto::make_ec_key_pair()); + ccf::crypto::Pem service_cert = + service_kp->self_sign("CN=Service", valid_from, valid_to); + ccf::crypto::MLDSAKeyPairPtr pq_service_kp; + std::optional pq_service_cert = std::nullopt; + + ccf::kv::Store primary_store; + ccf::kv::Store backup_store; + std::shared_ptr primary_history; + std::shared_ptr consensus; + + SigningFixture(ccf::crypto::MLDSAKeyPairPtr pq_service_kp_ = nullptr) : + pq_service_kp(std::move(pq_service_kp_)) + { + if (pq_service_kp != nullptr) + { + pq_service_cert = + pq_service_kp->self_sign("CN=Service", valid_from, valid_to); + } + + constexpr auto store_term = 2; + primary_store.set_encryptor(encryptor); + primary_history = std::make_shared( + primary_store, ccf::kv::test::PrimaryNodeId, *node_kp); + primary_history->set_endorsed_certificate(node_cert); + primary_history->set_service_signing_identity( + service_kp, pq_service_kp, ccf::COSESignaturesConfig{}); + primary_store.set_history(primary_history); + primary_store.initialise_term(store_term); + + backup_store.set_encryptor(encryptor); + backup_store.set_history(std::make_shared( + backup_store, ccf::kv::test::FirstBackupNodeId, *node_kp)); + backup_store.initialise_term(store_term); + backup_store.set_consensus(std::make_shared(nullptr)); + + consensus = std::make_shared(&backup_store); + primary_store.set_consensus(consensus); + + commit([this](ccf::kv::Tx& tx) { + ccf::NodeInfo node_info; + node_info.encryption_pub_key = node_kp->public_key_pem(); + node_info.cert = node_cert; + tx.wo(ccf::Tables::NODES) + ->put(ccf::kv::test::PrimaryNodeId, node_info); + }); + } + + void commit(const std::function& write) + { + auto tx = primary_store.create_tx(); + write(tx); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } + + void publish_service_keys() + { + commit([this](ccf::kv::Tx& tx) { + tx.wo(ccf::Tables::SERVICE) + ->put( + ccf::ServiceInfo{.cert = service_cert, .pq_cert = pq_service_cert}); + auto* identities = + tx.wo(ccf::Tables::SIGNING_IDENTITIES); + identities->put( + ccf::IdentityType::CLASSICAL, + ccf::signing_identity_from_cert(service_cert)); + if (pq_service_cert.has_value()) + { + identities->put( + ccf::IdentityType::PQ, + ccf::signing_identity_from_cert(pq_service_cert.value())); + } + }); + } + + std::optional emit_signature() + { + primary_history->emit_signature(); + return consensus->last_apply_result; + } + + std::optional emit_signature( + CustomSignaturePendingTx::WriteSignatures write_signatures) + { + const auto txid = primary_store.next_txid(); + primary_store.commit( + txid, + std::make_unique( + txid, primary_store, *primary_history, std::move(write_signatures)), + true); + return consensus->last_apply_result; + } +}; + TEST_CASE("Check signature verification") { auto encryptor = std::make_shared(); @@ -159,12 +316,27 @@ TEST_CASE("Check signature verification") INFO("Issue a bogus signature, rejected by verification on the backup"); { - auto txs = primary_store.create_tx(); - auto sigs = txs.rw(signatures); - ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, 0); + const auto txid = primary_store.next_txid(); + auto txs = primary_store.create_reserved_tx(txid); + auto sigs = txs.wo(signatures); + ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, txid.seqno); + bogus.view = txid.view; + bogus.root = primary_history->get_replicated_state_root(); bogus.sig = std::vector(256, 1); sigs->put(bogus); - REQUIRE(txs.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + txs.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put(primary_history->serialise_tree(txid.seqno - 1)); + auto info = txs.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + primary_store.commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + true) == ccf::kv::CommitResult::FAIL_NO_REPLICATE); } } @@ -282,17 +454,13 @@ TEST_CASE("Check signature verification with the signing identities table") TEST_CASE("Signing identity carries an ML-DSA key next to the classical key") { - if (!ccf::crypto::mldsa_supported()) - { - return; - } - auto encryptor = std::make_shared(); auto node_kp = ccf::crypto::make_ec_key_pair(); auto service_kp = std::dynamic_pointer_cast( ccf::crypto::make_ec_key_pair()); auto pq_service_kp = ccf::crypto::make_mldsa_key_pair(ccf::crypto::MLDSAParameterSet::ML_DSA_65); + const auto pq_public_key_der = pq_service_kp->public_key_der(); const auto self_signed = node_kp->self_sign("CN=Node", valid_from, valid_to); const auto service_cert = service_kp->self_sign("CN=Service", valid_from, valid_to); @@ -347,14 +515,229 @@ TEST_CASE("Signing identity carries an ML-DSA key next to the classical key") REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - INFO("The classical signature is emitted and verified on the backup"); + INFO("Both signatures are emitted and verified on the backup"); primary_history->emit_signature(); REQUIRE(consensus->last_apply_result == ccf::kv::ApplyResult::PASS_SIGNATURE); - auto tx = backup_store.create_read_only_tx(); + auto tx = backup_store.create_read_only_tx_at_replicated_state(); auto* cose_signatures = tx.ro(ccf::Tables::COSE_SIGNATURES); - REQUIRE(cose_signatures->get(ccf::IdentityType::CLASSICAL).has_value()); + const auto classical_signature = + cose_signatures->get(ccf::IdentityType::CLASSICAL); + const auto pq_signature = cose_signatures->get(ccf::IdentityType::PQ); + REQUIRE(classical_signature.has_value()); + REQUIRE(pq_signature.has_value()); + + INFO("The signatures share their protected header except alg and kid"); + const auto classical = + ccf::cose::decode_ccf_receipt(classical_signature.value(), false).phdr; + const auto pq = + ccf::cose::decode_ccf_receipt(pq_signature.value(), false).phdr; + const auto kid_bytes = [](const std::string& kid) { + return std::vector(kid.begin(), kid.end()); + }; + REQUIRE( + classical.alg == + ccf::cose::algorithm_for_curve(service_kp->get_curve_id()).alg); + REQUIRE( + classical.kid == + kid_bytes(ccf::crypto::kid_from_key(service_kp->public_key_der()))); + REQUIRE(pq.alg == ccf::cose::alg::ML_DSA_65); + REQUIRE(pq.kid == kid_bytes(ccf::crypto::kid_from_key(pq_public_key_der))); + REQUIRE(pq.vds == classical.vds); + REQUIRE(pq.ccf.txid == classical.ccf.txid); + REQUIRE(pq.cwt.iat == classical.cwt.iat); + REQUIRE(pq.cwt.iss == classical.cwt.iss); + REQUIRE(pq.cwt.sub == classical.cwt.sub); +} + +TEST_CASE("Every COSE signature is verified with the identity of its type") +{ + SigningFixture f(ccf::crypto::make_mldsa_key_pair( + ccf::crypto::MLDSAParameterSet::ML_DSA_65)); + f.publish_service_keys(); + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::PASS_SIGNATURE); + + const auto sign_with = [&f]( + ccf::kv::Tx& tx, + const ccf::TxID& txid, + const ccf::crypto::Sha256Hash& root, + bool with_pq_signature, + bool tamper_pq_signature = false) { + auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); + signatures->put( + ccf::IdentityType::CLASSICAL, sign_root(*f.service_kp, txid, root)); + if (with_pq_signature) + { + auto pq_signature = sign_root(*f.pq_service_kp, txid, root); + if (tamper_pq_signature) + { + pq_signature.back() ^= 1; + } + signatures->put(ccf::IdentityType::PQ, pq_signature); + } + }; + + SUBCASE("Signatures by both published keys verify") + { + REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { + sign_with(tx, txid, root, true); + }) == ccf::kv::ApplyResult::PASS_SIGNATURE); + } + + SUBCASE("A tampered PQ signature fails verification") + { + REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { + sign_with(tx, txid, root, true, true); + }) == ccf::kv::ApplyResult::FAIL); + } + + SUBCASE("A PQ signature by another key fails verification") + { + const auto other_cert = ccf::crypto::make_mldsa_key_pair( + ccf::crypto::MLDSAParameterSet::ML_DSA_65) + ->self_sign("CN=Service", valid_from, valid_to); + f.commit([&](ccf::kv::Tx& tx) { + tx.wo(ccf::Tables::SERVICE) + ->put(ccf::ServiceInfo{.cert = f.service_cert, .pq_cert = other_cert}); + tx.wo(ccf::Tables::SIGNING_IDENTITIES) + ->put( + ccf::IdentityType::PQ, ccf::signing_identity_from_cert(other_cert)); + }); + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); + } + + SUBCASE("A PQ signature by a rotated key verifies") + { + // The fixture's first signature cached a verifier for the previous key + f.pq_service_kp = ccf::crypto::make_mldsa_key_pair( + ccf::crypto::MLDSAParameterSet::ML_DSA_65); + const auto rotated_cert = + f.pq_service_kp->self_sign("CN=Service", valid_from, valid_to); + f.commit([&](ccf::kv::Tx& tx) { + tx.wo(ccf::Tables::SERVICE) + ->put( + ccf::ServiceInfo{.cert = f.service_cert, .pq_cert = rotated_cert}); + tx.wo(ccf::Tables::SIGNING_IDENTITIES) + ->put( + ccf::IdentityType::PQ, ccf::signing_identity_from_cert(rotated_cert)); + }); + REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { + sign_with(tx, txid, root, true); + }) == ccf::kv::ApplyResult::PASS_SIGNATURE); + } + + SUBCASE("A published PQ identity requires a PQ signature") + { + // The table still holds the PQ signature of the previous signature + // transaction, and this transaction writes only a CLASSICAL one + REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { + sign_with(tx, txid, root, false); + }) == ccf::kv::ApplyResult::FAIL); + } + + SUBCASE("A PQ signature requires a published PQ identity") + { + f.commit([&](ccf::kv::Tx& tx) { + tx.wo(ccf::Tables::SERVICE) + ->put(ccf::ServiceInfo{.cert = f.service_cert}); + tx.wo(ccf::Tables::SIGNING_IDENTITIES) + ->remove(ccf::IdentityType::PQ); + }); + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); + } + + SUBCASE("A PQ certificate requires a published PQ identity") + { + f.commit([&](ccf::kv::Tx& tx) { + tx.wo(ccf::Tables::SIGNING_IDENTITIES) + ->remove(ccf::IdentityType::PQ); + }); + + SUBCASE("With both signatures") + { + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); + } + + SUBCASE("With a CLASSICAL signature alone") + { + REQUIRE( + f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { + sign_with(tx, txid, root, false); + }) == ccf::kv::ApplyResult::FAIL); + } + } +} + +TEST_CASE("An unknown identity type fails signature verification") +{ + SigningFixture f; + f.publish_service_keys(); + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::PASS_SIGNATURE); + + constexpr uint64_t unknown_identity_type = 2; + + SUBCASE("Among the signing identities") + { + f.commit([&](ccf::kv::Tx& tx) { + tx.wo>( + ccf::Tables::SIGNING_IDENTITIES) + ->put( + unknown_identity_type, + ccf::signing_identity_from_cert(f.service_cert)); + }); + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); + } + + SUBCASE("Among the COSE signatures") + { + REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { + const auto signature = sign_root(*f.service_kp, txid, root); + tx.template wo(ccf::Tables::COSE_SIGNATURES) + ->put(ccf::IdentityType::CLASSICAL, signature); + tx.template wo>( + ccf::Tables::COSE_SIGNATURES) + ->put(unknown_identity_type, signature); + }) == ccf::kv::ApplyResult::FAIL); + } +} + +TEST_CASE("A published CLASSICAL identity requires a CLASSICAL COSE signature") +{ + SigningFixture f; + const auto node_signature_only = [&f]( + ccf::kv::Tx& tx, + const ccf::TxID& txid, + const ccf::crypto::Sha256Hash& root) { + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature( + ccf::kv::test::PrimaryNodeId, + txid.seqno, + txid.view, + root, + {}, + f.node_kp->sign_hash(root.h.data(), root.h.size()), + f.node_cert)); + }; + + SUBCASE("Without a published identity, a node signature suffices") + { + f.commit([&f](ccf::kv::Tx& tx) { + tx.wo(ccf::Tables::SERVICE) + ->put(ccf::ServiceInfo{.cert = f.service_cert}); + }); + REQUIRE( + f.emit_signature(node_signature_only) == + ccf::kv::ApplyResult::PASS_SIGNATURE); + } + + SUBCASE("With a published identity, a node signature alone fails") + { + f.publish_service_keys(); + REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::PASS_SIGNATURE); + REQUIRE( + f.emit_signature(node_signature_only) == ccf::kv::ApplyResult::FAIL); + } } TEST_CASE("Check signing works across rollback") @@ -447,9 +830,9 @@ TEST_CASE("Check signing works across rollback") INFO("Check merkle roots are updating"); { auto primary_root = primary_history->get_replicated_state_root(); - auto pr_str = fmt::format("{}", primary_root); + auto pr_str = std::format("{}", primary_root); auto backup_root = backup_history->get_replicated_state_root(); - auto bk_str = fmt::format("{}", backup_root); + auto bk_str = std::format("{}", backup_root); REQUIRE(pr_str == bk_str); } @@ -504,20 +887,18 @@ class TestPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - MapT& other_table; public: - TestPendingTx(ccf::TxID txid_, ccf::kv::Store& store_, MapT& other_table_) : + TestPendingTx(ccf::TxID txid_, ccf::kv::Store& store_) : txid(txid_), - store(store_), - other_table(other_table_) + store(store_) {} ccf::kv::PendingTxInfo call() override { auto txr = store.create_reserved_tx(txid); - auto txrv = txr.rw(other_table); - txrv->put(0, 1); + txr.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); return txr.commit_reserved(); } }; @@ -549,7 +930,6 @@ TEST_CASE("Pending signatures retain their endorsed certificate") constexpr auto store_term = 2; store.initialise_term(store_term); - MapT table("public:table"); const auto gap_txid = store.next_txid(); history->emit_signature(); @@ -558,11 +938,10 @@ TEST_CASE("Pending signatures retain their endorsed certificate") history->set_endorsed_certificate(second_cert); REQUIRE( store.commit( - gap_txid, - std::make_unique(gap_txid, store, table), - false) == ccf::kv::CommitResult::SUCCESS); + gap_txid, std::make_unique(gap_txid, store), false) == + ccf::kv::CommitResult::SUCCESS); - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); auto signatures = tx.ro(ccf::Tables::SIGNATURES); const auto signature = signatures->get(); REQUIRE(signature.has_value()); @@ -628,7 +1007,7 @@ TEST_CASE("Signatures are not emitted on demand until signing is enabled") MapT table("public:table"); auto get_signature = [&]() { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); return tx.ro(ccf::Tables::SIGNATURES)->get(); }; @@ -685,8 +1064,8 @@ class PausedReservedSignatureTx : public ccf::kv::PendingTx ccf::kv::PendingTxInfo call() override { auto tx = store.create_reserved_tx(txid); - auto sig = tx.rw(signatures); - auto tree = tx.rw(serialised_tree); + auto sig = tx.wo(signatures); + auto tree = tx.wo(serialised_tree); sig->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); tree->put({}); @@ -717,7 +1096,6 @@ TEST_CASE( store.set_consensus(consensus); MapT table("public:table"); - MapT other_table("public:other_table"); INFO("Write first tx"); { @@ -738,8 +1116,7 @@ TEST_CASE( REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(consensus->count == 1); - store.commit( - rv, std::make_unique(rv, store, other_table), true); + store.commit(rv, std::make_unique(rv, store), true); REQUIRE(consensus->count == 3); } @@ -996,15 +1373,18 @@ TEST_CASE("COSE signature table holds one entry per identity") INFO("A table carrying two identities round-trips both"); { - auto tx = store.create_tx(); + auto tx = store.create_reserved_tx(store.next_txid()); auto* handle = tx.wo(ccf::Tables::COSE_SIGNATURES); handle->put(ccf::IdentityType::CLASSICAL, ec384_sig); handle->put(ccf::IdentityType::PQ, mldsa65_sig); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); + REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + store.compact(store.current_version()); } { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); auto* handle = tx.ro(ccf::Tables::COSE_SIGNATURES); // A reader which only understands ECDSA still finds it, unaffected by @@ -1030,22 +1410,33 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") const ccf::CoseSignature keyed_signature{4, 5, 6}; { - auto tx = store.create_tx(); + auto tx = store.create_reserved_tx(store.next_txid()); tx.wo(ccf::Tables::COSE_SIGNATURES) ->put(legacy_signature); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); + REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + store.compact(store.current_version()); } { - auto tx = store.create_tx(); - auto* signatures = tx.rw(ccf::Tables::COSE_SIGNATURES); + auto tx = store.create_read_only_tx_at_replicated_state(); + auto* signatures = tx.ro(ccf::Tables::COSE_SIGNATURES); REQUIRE(signatures->get(ccf::IdentityType::CLASSICAL) == legacy_signature); + } + + { + auto tx = store.create_reserved_tx(store.next_txid()); + auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); signatures->put(ccf::IdentityType::CLASSICAL, keyed_signature); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put({}); + REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); + store.compact(store.current_version()); } { - auto tx = store.create_read_only_tx(); + auto tx = store.create_read_only_tx_at_replicated_state(); REQUIRE( tx.ro(ccf::Tables::COSE_SIGNATURES)->get() == keyed_signature); diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index 092bb0342417..a73e341e34ee 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -18,6 +18,8 @@ #include "node/snapshot_serdes.h" #include "snapshots/filenames.h" +#include + #define DOCTEST_CONFIG_IMPLEMENT #include #include @@ -47,7 +49,7 @@ struct ScopedSnapshotDir ScopedSnapshotDir() { - const auto unique_name = fmt::format( + const auto unique_name = std::format( "ccf-snapshotter-test-{}-{}", ::getpid(), std::chrono::steady_clock::now().time_since_epoch().count()); @@ -459,7 +461,7 @@ TEST_CASE("Recovery snapshot ledger scan filters directory contents") fixture.ledger_config.directory = path.string(); REQUIRE_THROWS_WITH_AS( ccf::find_recovery_snapshot_ledger_files(fixture.ledger_config), - fmt::format( + std::format( "Unable to iterate ledger directory {}: {}", path.string(), std::make_error_code(std::errc::not_a_directory).message()) @@ -474,7 +476,7 @@ TEST_CASE("Recovery snapshot ledger scan filters directory contents") fixture.ledger_config.directory = path.string(); REQUIRE_THROWS_WITH_AS( ccf::find_recovery_snapshot_ledger_files(fixture.ledger_config), - fmt::format( + std::format( "Unable to inspect ledger directory {}: {}", path.string(), std::make_error_code(std::errc::too_many_symbolic_link_levels) @@ -499,7 +501,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") REQUIRE(fs::remove(current_path)); REQUIRE_THROWS_WITH_AS( ccf::open_recovery_snapshot_ledger_file(files.front()), - fmt::format("Unable to open ledger file {}", current_path.string()) + std::format("Unable to open ledger file {}", current_path.string()) .c_str(), std::logic_error); } @@ -512,7 +514,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") fs::resize_file(current_path, size); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format("Ledger file {} is too small", current_path.string()) + std::format("Ledger file {} is too small", current_path.string()) .c_str(), std::logic_error); } @@ -525,7 +527,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") fs::rename(current_path, committed_path); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Committed ledger file {} has no positions table", committed_path.string()) .c_str(), @@ -549,7 +551,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") } REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Ledger file {} has invalid positions table offset {}", committed_path.string(), offset) @@ -588,7 +590,7 @@ TEST_CASE("Recovery snapshot ledger reader reports truncation after opening") REQUIRE(reader.file); REQUIRE_THROWS_WITH_AS( ccf::read_recovery_snapshot_ledger_entry(reader, ledger_file), - fmt::format("Unable to read {} from ledger file {}", error, path.string()) + std::format("Unable to read {} from ledger file {}", error, path.string()) .c_str(), std::logic_error); } @@ -646,7 +648,7 @@ TEST_CASE("Recovery snapshot ledger scan distinguishes incomplete chunk tails") write_ledger_file(committed_path, {first, tail}, true); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format("Committed ledger file {} {}", committed_path.string(), error) + std::format("Committed ledger file {} {}", committed_path.string(), error) .c_str(), std::logic_error); } @@ -688,7 +690,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {first, second}); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Ledger file {} does not start at its declared seqno 2", path.string()) .c_str(), std::logic_error); @@ -700,7 +702,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {first, second}, true); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Ledger file {} does not end at its declared seqno 3", path.string()) .c_str(), std::logic_error); @@ -712,7 +714,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {}, true); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Ledger file {} does not end at its declared seqno 1", path.string()) .c_str(), std::logic_error); @@ -726,7 +728,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {first, fixture.entry(next)}); REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Ledger file {} contains non-contiguous versions 1 and {}", path.string(), next) @@ -762,7 +764,7 @@ TEST_CASE("Recovery snapshot ledger scan rejects seqno overflow") SUBCASE("The last scanned entry must have a successor") { write_ledger_file( - fixture.ledger_dir.path / fmt::format("ledger_{}", max_seqno), + fixture.ledger_dir.path / std::format("ledger_{}", max_seqno), {fixture.entry(max_seqno)}); REQUIRE_THROWS_WITH_AS( fixture.scan(max_seqno - 1), @@ -882,7 +884,7 @@ TEST_CASE("Recovery snapshot ledger scan bounds individual endorsement sizes") { REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Ledger endorsement at 1 is too large ({} bytes; maximum {} bytes)", limit + extra, limit) @@ -925,7 +927,7 @@ TEST_CASE("Recovery snapshot ledger scan bounds individual endorsement sizes") { REQUIRE_THROWS_WITH_AS( fixture.scan(), - fmt::format( + std::format( "Serialised previous service identity endorsement is too large " "({} bytes; maximum {} bytes)", limit + 4 * extra, @@ -1446,14 +1448,25 @@ TEST_CASE("Rekey ledger while snapshot is in progress") { // It is necessary to record a signature for the snapshot to be // deserialisable by the backup store - auto tx = network.tables->create_tx(); - auto sigs = tx.rw(ccf::Tables::SIGNATURES); + const auto txid = network.tables->next_txid(); + auto tx = network.tables->create_reserved_tx(txid); + auto sigs = tx.wo(ccf::Tables::SIGNATURES); auto trees = - tx.rw(ccf::Tables::SERIALISED_MERKLE_TREE); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE); sigs->put({ccf::kv::test::PrimaryNodeId, 0, 0, {}, {}, {}, {}}); auto tree = history->serialise_tree(snapshot_idx - 1); trees->put(tree); - tx.commit(); + auto info = tx.commit_reserved(); + REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); + REQUIRE( + network.tables->commit( + txid, + std::make_unique( + std::move(info.data), + std::move(info.claims_digest), + std::move(info.commit_evidence_digest), + std::move(info.hooks)), + false) == ccf::kv::CommitResult::SUCCESS); REQUIRE(record_signature(history, snapshotter, snapshot_idx)); snapshotter->commit(snapshot_idx, true); @@ -1551,7 +1564,7 @@ TEST_CASE("Snapshot receipt") } else { - tree.append(ccf::crypto::Sha256Hash(fmt::format("tx {}", seqno))); + tree.append(ccf::crypto::Sha256Hash(std::format("tx {}", seqno))); } } const auto root = tree.get_root(); From 9a4678065e5b7a4c10e4cc6a269c79f92b7f760f Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Thu, 3 Dec 2026 19:00:34 +0000 Subject: [PATCH 2/3] Fence local writes against step-down with a role lock (#8921) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> (cherry picked from commit 25eaec3255888e4d342860bad414ed5dcf668044) --- .../local-writes-fenced-on-step-down.fixed.md | 1 + src/consensus/aft/cft.h | 119 +++++- src/consensus/aft/test/main.cpp | 2 +- .../aft/test/view_straddling_common.h | 99 +++-- .../aft/test/view_straddling_history.cpp | 343 +++++++++++++----- .../aft/test/view_straddling_rollback.cpp | 16 +- src/js/test/js.cpp | 2 +- src/kv/committable_tx.h | 51 ++- src/kv/kv_types.h | 100 ++++- src/kv/store.h | 96 ++++- src/kv/test/kv_serialisation.cpp | 2 +- src/kv/test/kv_test.cpp | 62 ++-- src/kv/test/null_tx_history.h | 7 +- src/node/history.h | 10 +- src/node/rpc/test/node_frontend_test.cpp | 2 +- src/node/snapshotter.h | 44 ++- src/node/test/historical_queries.cpp | 6 +- src/node/test/history.cpp | 16 +- src/node/test/snapshotter.cpp | 124 ++++++- 19 files changed, 905 insertions(+), 197 deletions(-) create mode 100644 .changes/local-writes-fenced-on-step-down.fixed.md diff --git a/.changes/local-writes-fenced-on-step-down.fixed.md b/.changes/local-writes-fenced-on-step-down.fixed.md new file mode 100644 index 000000000000..c16c9fd4b9b3 --- /dev/null +++ b/.changes/local-writes-fenced-on-step-down.fixed.md @@ -0,0 +1 @@ +A primary that steps down no longer races local transactions, signatures or snapshot evidence against incoming replication, which could cause the node to reject valid entries or diverge from the service's ledger. diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 204a8ac4c5a1..e09306d9a695 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -20,11 +20,13 @@ #include "tasks/periodic_task_owner.h" #include +#include #include #include #include #include #include +#include #include #include @@ -169,6 +171,29 @@ namespace aft // append entries bool public_only = false; + // Whether this has set the Store's term, which can only be initialised + // once, and must later be updated by rollback. + bool store_term_initialised = false; + + // Fences local writers (CommittableTx::commit(), Store::next_txid() and + // Store::commit()) against this node's role changing. Local writers hold + // it shared, through a permit, while they apply writes to the KV, and + // again, through a separate permit, while they publish them to the history. + // update_local_writes() takes it exclusively, under state->lock. Lock + // order: commit_lock -> state->lock -> role_rwlock -> maps_lock -> + // version_lock -> history lock. It must never be held across a call that + // takes state->lock, such as replicate(), nor acquired recursively. + ccf::ds::SharedMutex role_rwlock; + // std::shared_mutex may prefer readers, so a steady stream of local + // writers could starve update_local_writes(), which waits for role_rwlock + // while holding state->lock. It sets this before it waits, and local + // writers which see it are refused without taking role_rwlock, so it only + // waits for writers which checked the flag before it was set. + std::atomic role_change_pending = false; + // Whether local writes are accepted. Only modified by + // update_local_writes(), with role_rwlock held exclusively. + std::atomic local_writes_open = false; + // Randomness std::uniform_int_distribution distrib; std::default_random_engine rand; @@ -322,6 +347,22 @@ namespace aft } } + ccf::kv::LocalWritePermit acquire_local_write_permit() override + { + if (role_change_pending.load()) + { + return {}; + } + std::shared_lock guard(role_rwlock); + const auto writable = local_writes_open.load(); + return {std::move(guard), writable}; + } + + bool local_writes_enabled() override + { + return local_writes_open.load(); + } + void set_retired_committed( ccf::SeqNo seqno, const std::vector& node_ids) override { @@ -647,9 +688,12 @@ namespace aft if (state->leadership_state.load() != ccf::kv::LeadershipState::Leader) { + // Local writes were closed, and the speculative local state these + // entries belong to discarded, when this node stopped being leader. + // Entries from before a later re-election are refused by the term + // check below, as every candidacy increments the view. CFT_DEBUG_FMT( "Failed to replicate {} items: not leader", entries.size()); - rollback(state->last_idx); return false; } @@ -668,7 +712,6 @@ namespace aft CFT_DEBUG_FMT( "Failed to replicate {} items: node retirement is complete", entries.size()); - rollback(state->last_idx); return false; } @@ -2014,6 +2057,47 @@ namespace aft } } + // Only a primary whose retirement is not complete accepts local writes. + // Brings local_writes_open in line with that, waiting for local writers + // holding a permit to release it. When local writes stop, discards the + // speculative local state they wrote beyond last_idx (the end of Aft's + // log, committed or not), which no further + // local writer can add to. Must be called with state->lock held, and not + // under any Store lock other than commit_lock. + void update_local_writes() + { + const auto writable = + state->leadership_state.load() == ccf::kv::LeadershipState::Leader && + !is_retired_committed(); + if (writable == local_writes_open.load()) + { + return; + } + + role_change_pending.store(true); + { + std::unique_lock guard(role_rwlock); + local_writes_open.store(writable); + } + role_change_pending.store(false); + + if (!writable) + { + rollback(state->last_idx); + } + } + + // Every change of leadership state goes through here, so that local + // writes follow it. The one exception is completing retirement, which + // runs under the Store's locks, and so is followed up by Aft's commit(). + // Any other transition made under the Store's locks must likewise leave + // calling update_local_writes() until those locks are released. + void set_leadership_state(ccf::kv::LeadershipState leadership_state) + { + state->leadership_state.store(leadership_state); + update_local_writes(); + } + void become_pre_vote_candidate() { if (configurations.empty()) @@ -2026,7 +2110,7 @@ namespace aft trace::tick(*state); - state->leadership_state.store(ccf::kv::LeadershipState::PreVoteCandidate); + set_leadership_state(ccf::kv::LeadershipState::PreVoteCandidate); leader_id.reset(); reset_votes_for_me(); @@ -2064,12 +2148,14 @@ namespace aft return; } - state->leadership_state.store(ccf::kv::LeadershipState::Candidate); + // The view moves on first, so that if this closes local writes, + // discarding local state moves the Store to the new view too. + state->current_view++; + set_leadership_state(ccf::kv::LeadershipState::Candidate); leader_id.reset(); voted_for = state->node_id; reset_votes_for_me(); - state->current_view++; restart_election_timeout(); reset_last_ack_timeouts(); @@ -2109,15 +2195,24 @@ namespace aft { rollback(election_index); } - else + else if (!store_term_initialised) { // but we still want the KV to know which term we're in store->initialise_term(state->current_view); + store_term_initialised = true; + } + else + { + // The KV's term was already set, by an earlier election or rollback, + // so this only updates its term; nothing is past last_idx to discard. + rollback(state->last_idx); } - state->leadership_state.store(ccf::kv::LeadershipState::Leader); leader_id = state->node_id; should_sign = true; + // The KV is now in this term, and holds no speculative state from an + // earlier one, so local writes can start. + set_leadership_state(ccf::kv::LeadershipState::Leader); using namespace std::chrono_literals; timeout_elapsed = 0ms; @@ -2159,7 +2254,7 @@ namespace aft restart_election_timeout(); reset_last_ack_timeouts(); - state->leadership_state.store(ccf::kv::LeadershipState::Follower); + set_leadership_state(ccf::kv::LeadershipState::Follower); CFT_INFO_FMT( "Becoming follower {}: {}.{}", state->node_id, @@ -2278,6 +2373,8 @@ namespace aft nominate_successor_unsafe(); leader_id.reset(); + // This runs under the Store's locks, from compaction, so it must not + // wait for local writers. commit() stops them once compaction is done. state->leadership_state.store(ccf::kv::LeadershipState::None); } @@ -2550,6 +2647,11 @@ namespace aft CFT_DEBUG_FMT("Compacting..."); store->compact(idx); + // Compaction may have run the hook that completes this node's + // retirement, which cannot itself stop local writes because it runs + // under the Store's locks. state->lock is still held, so nothing + // published since can have been replicated, and this discards it. + update_local_writes(); ledger->commit(idx); if (commit_observer != nullptr) @@ -2632,6 +2734,7 @@ namespace aft } store->rollback({get_term_internal(idx), idx}, state->current_view); + store_term_initialised = true; CFT_DEBUG_FMT("Setting term in store to: {}", state->current_view); ledger->truncate(idx); diff --git a/src/consensus/aft/test/main.cpp b/src/consensus/aft/test/main.cpp index 7ad54e2dfaae..d38be3e64379 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -3496,7 +3496,7 @@ DOCTEST_TEST_CASE( ccf::kv::Version append_signature() { - const auto txid = sender_store.next_txid(); + const auto txid = sender_store.next_txid().value(); auto tx = sender_store.create_reserved_tx(txid); tx.wo(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); tx.wo(serialised_tree)->put({}); diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index 8b4e647a4ddd..00f4ff2ab4e0 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -11,6 +11,7 @@ #include "service/tables/signatures.h" #include "test_common.h" +#include #include #include #include @@ -22,7 +23,6 @@ namespace straddling { using TestMap = ccf::kv::Map; - using Cft = aft::Aft; class SignaturePendingTx : public ccf::kv::PendingTx { @@ -135,29 +135,62 @@ namespace straddling }; // Behaves like ccf::kv::MovePendingTx, the PendingTx of every normal - // transaction: hands over an already-serialised entry and cannot fail. It - // pauses first, modelling the committing thread being descheduled after - // Store::commit() has checked the transaction's view and released - // version_lock, but before it reaches CFT. In production this is the - // thread blocking on aft::State::lock while an election holds it. - class PausingMovePendingTx : public ccf::kv::PendingTx + // transaction: hands over an already-serialised entry and cannot fail. If + // given a pause, it pauses first, while Store::commit() holds the role lock + // shared, modelling the committing thread being descheduled + // while it publishes the entry. + class ReadyPendingTx : public ccf::kv::PendingTx { ccf::kv::PendingTxInfo info; - CommitPause& pause; + CommitPause* pause; public: - PausingMovePendingTx(ccf::kv::PendingTxInfo&& info_, CommitPause& pause_) : + ReadyPendingTx( + ccf::kv::PendingTxInfo&& info_, CommitPause* pause_ = nullptr) : info(std::move(info_)), pause(pause_) {} ccf::kv::PendingTxInfo call() override { - pause.pause(); + if (pause != nullptr) + { + pause->pause(); + } return std::move(info); } }; + // Pauses the next call to replicate() once armed, before it takes CFT's + // lock. This models the committing thread being descheduled after + // Store::commit() has published the entry locally and released the role + // lock, but before it reaches CFT. In production this is the + // thread blocking on aft::State::lock while an election holds it. + class PausingCft : public aft::Aft + { + std::atomic next_pause = nullptr; + + public: + using aft::Aft::Aft; + + void pause_next_replicate(CommitPause& pause) + { + next_pause.store(&pause); + } + + bool replicate(const ccf::kv::BatchVector& entries, aft::Term term) override + { + auto* pause = next_pause.exchange(nullptr); + if (pause != nullptr) + { + pause->pause(); + } + return aft::Aft::replicate(entries, term); + } + }; + + using Cft = PausingCft; + static std::optional read_value( ccf::kv::Store& store, TestMap& table, size_t key) { @@ -182,6 +215,7 @@ namespace straddling const ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; std::shared_ptr store = std::make_shared(); TestMap table{"public:table"}; + std::shared_ptr state = std::make_shared(node_id); std::shared_ptr cft; ccf::View initial_view = 0; @@ -194,27 +228,14 @@ namespace straddling // history before CFT is created and the baseline is committed. void start() { - cft = std::make_shared( - cft_settings, - std::make_unique>(store), - std::make_unique(node_id), - std::make_shared(), - std::make_shared(node_id), - nullptr); - store->set_consensus(cft); - - ccf::kv::Configuration::Nodes configuration; - configuration.try_emplace(node_id); - cft->add_configuration(0, configuration); - cft->force_become_primary(); - initial_view = cft->get_view(); + start_consensus(); { auto tx = store->create_tx(); tx.rw(table)->put(0, 1); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto baseline_txid = store->next_txid(); + const auto baseline_txid = store->next_txid().value(); REQUIRE( store->commit( baseline_txid, @@ -225,11 +246,37 @@ namespace straddling REQUIRE(cft->ledger->ledger.size() == 2); } + // Creates CFT and makes this node primary, with nothing committed. + void start_consensus() + { + cft = std::make_shared( + cft_settings, + std::make_unique>(store), + std::make_unique(node_id), + std::make_shared(), + state, + nullptr); + store->set_consensus(cft); + + ccf::kv::Configuration::Nodes configuration; + configuration.try_emplace(node_id); + cft->add_configuration(0, configuration); + cft->force_become_primary(); + initial_view = cft->get_view(); + } + + // Lose leadership, discarding everything after CFT's last index once + // in-flight local writers have finished publishing. + void step_down() + { + cft->become_aware_of_new_term(cft->get_view() + 1); + } + // Lose leadership, then win a later election. become_leader() rolls the // Store back to the last committable index (2) under the new view. ccf::View reelect() { - cft->become_aware_of_new_term(cft->get_view() + 1); + step_down(); cft->force_become_primary(); return cft->get_view(); } diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index 60c35474bb9e..9de314bea265 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -1,23 +1,27 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. -// A transaction which CFT is going to reject must never be published -// to the ledger history. Readers of the history, for instance -// set_root_on_proposals(), take no Store lock, so a transiently appended -// digest would give them a root which is in neither the KV nor the ledger. +// A transaction which CFT is going to reject must not remain published in +// the ledger history. Readers of the history, for instance +// set_root_on_proposals(), take no Store lock, so a stale digest would give +// them a root which is in neither the KV nor the ledger. On a follower, a +// stale digest would also prevent the root signed by the primary from +// matching, and the follower would reject valid entries. // -// Store::commit() checks the transaction's view under version_lock, then -// releases that lock before appending to the history. A rollback can land in -// that window. The guard is the view captured under version_lock, which is -// passed to TxHistory::append_entry() and compared against the history's own -// view under the history lock, dropping the append if they differ. +// Store::commit() publishes a local transaction to the history while it +// holds the role lock shared, and CFT discards everything published after +// its last index once it has taken that lock exclusively, when the node +// stops being primary. A local writer which CFT has not yet accepted +// therefore either finishes publishing before CFT takes the lock, and is +// discarded and then refused by replicate(), or is refused before it +// publishes. // // Interleaving, from PR #8223: // -// - Tx A passes Store::commit()'s view check under version_lock, which is -// then released. +// - Tx A is published locally by Store::commit(), which then releases the +// role lock before calling CFT. // - An election rolls the Store and the ledger history back to seqno 2. -// - A appends its digest to the history, then CFT rejects it. +// - CFT rejects A, which must not reappear in the history. #include "node/history.h" #include "view_straddling_common.h" @@ -28,48 +32,39 @@ using namespace straddling; namespace { - // A history which pauses once, on the next append_entry() call after it is - // armed, after the base class has done its work and released its lock. What - // it has published at that point is exactly what any concurrent reader of - // the history would see. - class PausableHistory : public ccf::MerkleTxHistory + struct HistoryFixture : public Fixture { - std::atomic armed = false; - - public: - using ccf::MerkleTxHistory::MerkleTxHistory; - - CommitPause pause; + ccf::crypto::ECKeyPairPtr node_kp = ccf::crypto::make_ec_key_pair(); + std::shared_ptr history; - void arm() + HistoryFixture() { - armed.store(true); + history = + std::make_shared(*store, node_id, *node_kp); + store->set_history(history); + start(); } - void append_entry( - const ccf::crypto::Sha256Hash& digest, - std::optional expected_term_of_next_version = - std::nullopt) override + ccf::crypto::Sha256Hash root() { - ccf::MerkleTxHistory::append_entry(digest, expected_term_of_next_version); - - if (armed.exchange(false)) - { - pause.pause(); - } + const auto [txid, root, term] = + history->get_replicated_state_txid_and_root(); + return root; } - }; - struct HistoryFixture : public Fixture - { - ccf::crypto::ECKeyPairPtr node_kp = ccf::crypto::make_ec_key_pair(); - std::shared_ptr history; + ccf::SeqNo history_seqno() + { + const auto [txid, root, term] = + history->get_replicated_state_txid_and_root(); + return txid.seqno; + } - HistoryFixture() + // Applies a signature at the next TxID, without committing it to the + // Store. + std::pair prepare(uint8_t marker) { - history = std::make_shared(*store, node_id, *node_kp); - store->set_history(history); - start(); + const auto txid = store->next_txid().value(); + return {txid, SignaturePendingTx(txid, *store, marker).call()}; } }; } @@ -80,64 +75,248 @@ TEST_CASE( { HistoryFixture fixture; - const auto [baseline_txid, baseline_root, _] = - fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(baseline_txid.seqno == 2); - REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); - REQUIRE(read_signature_seqno(*fixture.store) == baseline_txid.seqno); + const auto baseline_root = fixture.root(); + REQUIRE(fixture.history_seqno() == 2); INFO("Apply and serialise A at seqno 3 in the initial view"); - const auto stale_txid = fixture.store->next_txid(); + auto [stale_txid, stale_info] = fixture.prepare(2); REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); - auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); - INFO("A enters Store::commit, passes its view check, then is descheduled"); - CommitPause commit_pause; + INFO( + "A is published locally by Store::commit, then is descheduled before " + "reaching consensus"); + CommitPause replicate_pause; + fixture.cft->pause_next_replicate(replicate_pause); std::optional stale_result; - Worker stale_worker({&commit_pause, &fixture.history->pause}, [&]() { + Worker stale_worker({&replicate_pause}, [&]() { stale_result = fixture.store->commit( stale_txid, - std::make_unique( - std::move(stale_info), commit_pause), + std::make_unique(std::move(stale_info)), false); }); - REQUIRE(commit_pause.wait_until_paused()); + REQUIRE(replicate_pause.wait_until_paused()); + REQUIRE(fixture.history_seqno() == 3); INFO("Lose leadership and win a later election, rolling back to seqno 2"); fixture.reelect(); - { - const auto [rolled_back_txid, rolled_back_root, rolled_back_term] = - fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(rolled_back_txid.seqno == 2); - REQUIRE(rolled_back_root == baseline_root); - } + REQUIRE(fixture.history_seqno() == 2); + REQUIRE(fixture.root() == baseline_root); - INFO("Resume A, and observe the history once its append has completed"); - fixture.history->arm(); - commit_pause.release(); - REQUIRE(fixture.history->pause.wait_until_paused()); - { - const auto [observed_txid, observed_root, observed_term] = - fixture.history->get_replicated_state_txid_and_root(); - CHECK(observed_txid.seqno == 2); - CHECK(observed_root == baseline_root); - } - fixture.history->pause.release(); + INFO("Resume A: cft rejects it, and history, KV and ledger agree"); + replicate_pause.release(); stale_worker.join(); - - INFO("cft rejects A, and history, KV and ledger agree"); REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.history_seqno() == 2); + CHECK(fixture.root() == baseline_root); + CHECK(fixture.store->current_txid().seqno == 2); + CHECK(fixture.cft->get_last_idx() == 2); + CHECK(fixture.cft->ledger->ledger.size() == 2); +} + +TEST_CASE( + "Stepping down waits for an in-flight local writer, then discards it" * + doctest::test_suite("view_straddling_history")) +{ + HistoryFixture fixture; + + const auto baseline_root = fixture.root(); + + INFO("A enters Store::commit and is descheduled while publishing"); + auto [txid, info] = fixture.prepare(2); + CommitPause publish_pause; + std::optional result; + Worker writer({&publish_pause}, [&]() { + result = fixture.store->commit( + txid, + std::make_unique(std::move(info), &publish_pause), + false); + }); + REQUIRE(publish_pause.wait_until_paused()); + + INFO( + "Consensus starts stepping down, under its lock, but cannot complete " + "while A is publishing"); + const auto view = fixture.cft->get_view(); + std::atomic holds_consensus_lock = false; + std::atomic stepped_down = false; + std::thread demoter([&]() { + std::lock_guard guard(fixture.state->lock); + holds_consensus_lock.store(true); + fixture.cft->become_aware_of_new_term(view + 1); + stepped_down.store(true); + }); + while (!holds_consensus_lock.load()) { - const auto [final_txid, final_root, final_term] = - fixture.history->get_replicated_state_txid_and_root(); - CHECK(final_txid.seqno == 2); - CHECK(final_root == baseline_root); + std::this_thread::yield(); } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + CHECK_FALSE(stepped_down.load()); + + INFO("Once A has published, stepping down discards it"); + publish_pause.release(); + writer.join(); + demoter.join(); + REQUIRE(stepped_down.load()); + REQUIRE(result.has_value()); + CHECK(result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.history_seqno() == 2); + CHECK(fixture.root() == baseline_root); CHECK(fixture.store->current_txid().seqno == 2); - CHECK(read_value(*fixture.store, fixture.table, 0) == 1); - CHECK(read_signature_seqno(*fixture.store) == baseline_txid.seqno); + CHECK(read_signature_seqno(*fixture.store) == 2); CHECK(fixture.cft->get_last_idx() == 2); CHECK(fixture.cft->ledger->ledger.size() == 2); } + +TEST_CASE( + "A follower refuses local writes and signatures, but not reads" * + doctest::test_suite("view_straddling_history")) +{ + HistoryFixture fixture; + fixture.history->set_endorsed_certificate(fixture.node_kp->self_sign( + "CN=Node", + ccf::ds::to_x509_time_string(std::chrono::system_clock::now()), + ccf::ds::to_x509_time_string( + std::chrono::system_clock::now() + std::chrono::hours(24)))); + + INFO("A transaction starts, and a TxID is reserved, while primary"); + auto stale_tx = fixture.store->create_tx(); + stale_tx.rw(fixture.table)->put(1, 1); + const auto reserved_txid = fixture.store->next_txid(); + REQUIRE(reserved_txid.has_value()); + + fixture.step_down(); + const auto baseline_root = fixture.root(); + const auto baseline_txid = fixture.store->current_txid(); + + INFO("A signature, which is reserved directly, is not emitted"); + CHECK_FALSE(fixture.store->next_txid().has_value()); + fixture.history->emit_signature(); + CHECK(fixture.store->current_txid() == baseline_txid); + CHECK(fixture.root() == baseline_root); + + INFO("A transaction reserved before stepping down cannot write"); + CHECK( + SignaturePendingTx(reserved_txid.value(), *fixture.store, 2) + .call() + .success == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(read_signature_seqno(*fixture.store) == 2); + + INFO("Writes are refused, whether started before or after stepping down"); + CHECK(stale_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + auto tx = fixture.store->create_tx(); + tx.rw(fixture.table)->put(2, 2); + CHECK(tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.store->current_txid() == baseline_txid); + CHECK(fixture.root() == baseline_root); + + INFO("A read-only transaction still commits"); + auto ro_tx = fixture.store->create_tx(); + CHECK(ro_tx.rw(fixture.table)->get(0) == 1); + CHECK(ro_tx.commit() == ccf::kv::CommitResult::SUCCESS); + + INFO("A snapshot cannot be requested"); + auto snapshot_tx = fixture.store->create_tx(); + CHECK(snapshot_tx.ro(fixture.table)->get(0) == 1); + snapshot_tx.set_tx_flag( + ccf::kv::CommittableTx::TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); + CHECK(snapshot_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK_FALSE(fixture.store->flag_enabled( + ccf::kv::AbstractStore::StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE)); + + INFO("Writes are accepted again once the node is re-elected"); + fixture.cft->force_become_primary(); + auto new_tx = fixture.store->create_tx(); + new_tx.rw(fixture.table)->put(3, 3); + CHECK(new_tx.commit() == ccf::kv::CommitResult::SUCCESS); + CHECK(fixture.store->next_txid().has_value()); +} + +TEST_CASE( + "Completing retirement on global commit stops local writes" * + doctest::test_suite("view_straddling_history")) +{ + HistoryFixture fixture; + + INFO( + "As in production, a global hook run by compaction completes this " + "node's retirement, under the Store's locks"); + TestMap retired{"public:retired"}; + fixture.store->set_global_hook( + retired.get_name(), + TestMap::wrap_commit_hook( + [&fixture](ccf::kv::Version version, const TestMap::Write&) { + fixture.cft->set_retired_committed(version, {fixture.node_id}); + })); + + // Retirement is otherwise driven by reconfiguration, which needs more + // nodes, so start from its last phase before RetiredCommitted. + fixture.state->membership_state = ccf::kv::MembershipState::Retired; + fixture.state->retirement_phase = ccf::kv::RetirementPhase::Completed; + fixture.state->retirement_idx = 2; + fixture.state->retirement_committable_idx = 2; + + INFO("Committing the retirement completes it, without deadlocking"); + auto tx = fixture.store->create_tx(); + tx.rw(retired)->put(0, 0); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto txid = fixture.store->next_txid().value(); + REQUIRE( + fixture.store->commit( + txid, + std::make_unique(txid, *fixture.store, 2), + true) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(fixture.cft->get_committed_seqno() == 4); + REQUIRE(fixture.cft->is_retired_committed()); + + const auto baseline_root = fixture.root(); + const auto baseline_txid = fixture.store->current_txid(); + + INFO("Local writes are refused"); + CHECK_FALSE(fixture.store->next_txid().has_value()); + auto write_tx = fixture.store->create_tx(); + write_tx.rw(fixture.table)->put(1, 1); + CHECK(write_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + + INFO("And remain refused, since a retired node cannot become primary"); + fixture.cft->force_become_primary(); + CHECK_FALSE(fixture.store->next_txid().has_value()); + auto later_tx = fixture.store->create_tx(); + later_tx.rw(fixture.table)->put(2, 2); + CHECK(later_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.store->current_txid() == baseline_txid); + CHECK(fixture.root() == baseline_root); +} + +TEST_CASE( + "A node can be re-elected before anything is committed" * + doctest::test_suite("view_straddling_history")) +{ + Fixture fixture; + fixture.start_consensus(); + REQUIRE(fixture.cft->get_committed_seqno() == 0); + + INFO( + "A transaction, such as the genesis transaction, is replicated but not " + "committed in the first term"); + auto tx = fixture.store->create_tx(); + tx.rw(fixture.table)->put(1, 1); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + REQUIRE(fixture.cft->get_last_idx() == 1); + REQUIRE(fixture.cft->get_committed_seqno() == 0); + + INFO("Re-election keeps it, and moves the Store to the new term"); + fixture.step_down(); + REQUIRE_NOTHROW(fixture.cft->force_become_primary()); + const auto view = fixture.cft->get_view(); + REQUIRE(view > fixture.initial_view); + CHECK(fixture.cft->get_last_idx() == 1); + CHECK(read_value(*fixture.store, fixture.table, 1) == 1); + + auto next_tx = fixture.store->create_tx(); + next_tx.rw(fixture.table)->put(2, 2); + CHECK(next_tx.commit() == ccf::kv::CommitResult::SUCCESS); + CHECK(next_tx.get_txid() == ccf::TxID(view, 2)); + CHECK(fixture.cft->get_last_idx() == 2); +} diff --git a/src/consensus/aft/test/view_straddling_rollback.cpp b/src/consensus/aft/test/view_straddling_rollback.cpp index 85a1c0fd30bb..b5da38874f64 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -16,10 +16,10 @@ // src/consensus/aft/cft.h): // // - Tx A is applied locally in view V and given TxID V.3. It enters -// Store::commit(), passes the view check, and is descheduled before it +// Store::commit(), is published locally, and is descheduled before it // reaches CFT. -// - An election happens. The node wins in view W > V, and become_leader() -// rolls the Store back past A, to seqno 2. +// - An election happens. Stepping down rolls the Store back past A, to seqno +// 2, and the node then wins in view W > V. // - Tx B is applied locally in view W and given TxID W.3. It has not yet // entered Store::commit(). // - A continues. CFT rejects it. If that rejection rolls the Store @@ -58,20 +58,22 @@ TEST_CASE( fixture.start(); INFO("Apply and serialise A at seqno 3 in the initial view"); - const auto stale_txid = fixture.store->next_txid(); + const auto stale_txid = fixture.store->next_txid().value(); REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); REQUIRE(read_signature_seqno(*fixture.store) == 2); - INFO("A enters Store::commit, passes its view check, then is descheduled"); + INFO( + "A enters Store::commit, is published locally, then is descheduled " + "before reaching consensus"); CommitPause stale_pause; + fixture.cft->pause_next_replicate(stale_pause); std::optional stale_result; Worker stale_worker({&stale_pause}, [&]() { stale_result = fixture.store->commit( stale_txid, - std::make_unique( - std::move(stale_info), stale_pause), + std::make_unique(std::move(stale_info)), false); }); REQUIRE(stale_pause.wait_until_paused()); diff --git a/src/js/test/js.cpp b/src/js/test/js.cpp index 84fec46b340d..28741e8d88c5 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -3127,7 +3127,7 @@ namespace std::vector make_test_signature_transaction(ccf::kv::Store& store) { - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); tx.wo(ccf::Tables::SIGNATURES) ->put(ccf::PrimarySignature(ccf::NodeId("test-node"), txid.seqno)); diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 67651147d5ff..c0a8136436cc 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -259,6 +259,33 @@ namespace ccf::kv } } #endif + const auto force_ledger_chunk = + tx_flag_enabled(TxFlag::LEDGER_CHUNK_AT_NEXT_SIGNATURE); + const auto snapshot_at_next_signature = + tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); + + // Held from before any write is applied until the Store flags have been + // applied, so that consensus cannot discard local state in between. + // Read-only transactions that do not request a snapshot do not need it, + // and can commit on any node. + LocalWritePermit permit; + if (has_writes() || snapshot_at_next_signature) + { + permit = pimpl->store->acquire_local_write_permit(); + } + + if (snapshot_at_next_signature && !permit.allows_writes()) + { + // A snapshot can only be requested on a node that will emit the next + // signature. A transaction which writes is refused anyway, when it is + // allocated a version. + LOG_TRACE_FMT( + "Could not request a snapshot because this node does not accept " + "local writes"); + KV_TRACE(trace_commit.result("no_replicate", 0)); + return CommitResult::FAIL_NO_REPLICATE; + } + { MapSetLockGuard map_set_guard(*pimpl->store, maps_created); #ifdef CCF_KV_TRACING @@ -268,7 +295,8 @@ namespace ccf::kv c = apply_changes( all_changes, [&]() { - auto resolution = pimpl->store->next_version(pimpl->commit_view); + auto resolution = + pimpl->store->next_version(pimpl->commit_view, permit); commit_term_changed = !resolution.has_value(); if (!resolution.has_value()) { @@ -307,11 +335,6 @@ namespace ccf::kv committed = true; version = c.value(); - const auto force_ledger_chunk = - tx_flag_enabled(TxFlag::LEDGER_CHUNK_AT_NEXT_SIGNATURE); - const auto snapshot_at_next_signature = - tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); - if (version == NoVersion) { // Read-only transaction. It has no version to attach a ledger chunk @@ -349,6 +372,10 @@ namespace ccf::kv } } + // Store::commit() acquires its own permit, and the write set observer + // may call into the Store, so this must not be held past here. + permit.release(); + // From here, we have received a unique commit version and made // modifications to our local kv. If we fail in any way, we cannot // recover. @@ -550,6 +577,18 @@ namespace ccf::kv throw std::logic_error("Reserved transaction cannot be empty"); } + // A reserved transaction must be committed from inside Store::commit, + // whose permit keeps this stable and whose view check rejects a TxID + // reserved in an earlier term before this is called. Its TxID may have + // been reserved before a step-down, so it must not write the follower's + // maps. + if (!pimpl->store->local_writes_enabled()) + { + committed = true; + return { + CommitResult::FAIL_NO_REPLICATE, {}, ccf::empty_claims(), {}, {}}; + } + std::vector hooks; bool track_deletes_on_missing_keys = false; diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index 66882c74e606..40c0af384cba 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -9,6 +9,7 @@ #include "ccf/crypto/pem.h" #include "ccf/ds/hex.h" #include "ccf/ds/json.h" +#include "ccf/ds/locking.h" #include "ccf/ds/net_address.h" #include "ccf/ds/nonstd.h" #include "ccf/entity_id.h" @@ -34,12 +35,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include namespace ccf @@ -444,6 +447,72 @@ namespace ccf::kv virtual const ccf::COSESignaturesConfig& get_cose_signatures_config() = 0; }; + // A shared hold on consensus's role lock. While it is held, consensus cannot + // switch between accepting and refusing local writes, so a local writer can + // apply, or publish, its writes without a concurrent demotion discarding them + // underneath it. Writers must check allows_writes(); a refused commit returns + // CommitResult::FAIL_NO_REPLICATE. A permit from + // consensus which does not fence local writes allows them without holding + // any lock. + class LocalWritePermit + { + private: + // Keeps the owner of the lock alive until the guard has released it. + std::shared_ptr owner; + std::shared_lock guard; + bool writable = false; + + public: + LocalWritePermit() = default; + + LocalWritePermit( + std::shared_lock&& guard_, bool writable_) : + guard(std::move(guard_)), + writable(writable_) + {} + + LocalWritePermit(LocalWritePermit&& other) noexcept : + owner(std::move(other.owner)), + guard(std::move(other.guard)), + writable(std::exchange(other.writable, false)) + {} + + LocalWritePermit& operator=(LocalWritePermit&& other) noexcept + { + if (this != &other) + { + release(); + guard = std::move(other.guard); + owner = std::move(other.owner); + writable = std::exchange(other.writable, false); + } + return *this; + } + + LocalWritePermit(const LocalWritePermit&) = delete; + LocalWritePermit& operator=(const LocalWritePermit&) = delete; + ~LocalWritePermit() = default; + + void set_owner(std::shared_ptr owner_) + { + owner = std::move(owner_); + } + + [[nodiscard]] bool allows_writes() const + { + return writable; + } + + void release() + { + writable = false; + if (guard.owns_lock()) + { + guard.unlock(); + } + } + }; + class Consensus : public ConfigurableConsensus { public: @@ -511,6 +580,24 @@ namespace ccf::kv virtual void nominate_successor() {} + // Acquires the role lock shared, if this fences local writes against + // changes of role. A local writer holds a permit while it applies its + // writes, and Store::commit() holds another while it publishes them to the + // history, so the writer must release its own first. A holder must neither + // acquire another permit, including through next_txid() or + // Store::commit(), nor call into consensus in a way that takes its + // lock, such as replicate(), or it may deadlock with a role change. + virtual LocalWritePermit acquire_local_write_permit() + { + return {std::shared_lock{}, true}; + } + + // Only stable while the caller holds a permit. + virtual bool local_writes_enabled() + { + return true; + } + ccf::TxStatus evaluate_tx_status( ccf::View target_view, ccf::SeqNo target_seqno) { @@ -830,9 +917,18 @@ namespace ccf::kv virtual void lock_map_set() = 0; virtual void unlock_map_set() = 0; + // Acquires a permit from consensus, see Consensus. A Store without + // consensus returns one which allows local writes without holding a lock. + virtual LocalWritePermit acquire_local_write_permit() = 0; + // Returns nullopt if the permit does not allow local writes, or if the + // commit term has moved on from expected_commit_term. virtual std::optional> next_version( - Term expected_commit_term) = 0; - virtual ccf::TxID next_txid() = 0; + Term expected_commit_term, const LocalWritePermit& permit) = 0; + // Reserves the next TxID, or returns nullopt if this Store does not + // currently accept local writes. + virtual std::optional next_txid() = 0; + // Only stable while the caller holds a permit. + [[nodiscard]] virtual bool local_writes_enabled() = 0; virtual Version current_version() = 0; virtual ccf::TxID current_txid() = 0; diff --git a/src/kv/store.h b/src/kv/store.h index 209955c9fcf3..2cadfa755a8f 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1016,6 +1016,24 @@ namespace ccf::kv } } + LocalWritePermit acquire_local_write_permit() override + { + auto c = get_consensus(); + if (c == nullptr) + { + return {std::shared_lock{}, true}; + } + auto permit = c->acquire_local_write_permit(); + permit.set_owner(c); + return permit; + } + + [[nodiscard]] bool local_writes_enabled() override + { + auto c = get_consensus(); + return c == nullptr || c->local_writes_enabled(); + } + void initialise_term(Term t) override { // Note: This should only be called once, when the store is first @@ -1185,6 +1203,19 @@ namespace ccf::kv txid.seqno, (globally_committable ? " globally_committable" : "")); + // Held from admission until the batch is published to the history and + // chunker, so that consensus cannot discard local state between this + // check and publication. It is released before calling consensus. + auto permit = c->acquire_local_write_permit(); + if (!permit.allows_writes()) + { + LOG_DEBUG_FMT( + "Refusing to commit {} because this node does not accept local " + "writes", + txid.seqno); + return CommitResult::FAIL_NO_REPLICATE; + } + BatchVector batch; Version previous_last_replicated = 0; Version next_last_replicated = 0; @@ -1284,25 +1315,40 @@ namespace ccf::kv txid.seqno); } - if (h) - { - h->append_entry( - ccf::entry_leaf( - *data_shared, commit_evidence_digest_, claims_digest_), - replication_view); - } + auto leaf = h ? + std::optional(ccf::entry_leaf( + *data_shared, commit_evidence_digest_, claims_digest_)) : + std::nullopt; - if (chunker) { std::lock_guard vguard(version_lock); // A rollback can only discard this batch's writes by truncating, // which requires its target to be below `version` and therefore // increments rollback_count. A rollback that does not truncate // leaves the writes intact, but may still move the term on, which - // consensus will reject - so both are checked here. + // consensus will reject - so both are checked here. Consensus does + // not roll back while local writes are accepted, so this only + // happens when the Store is rolled back directly. if ( - previous_rollback_count == rollback_count && - replication_view == term_of_next_version) + previous_rollback_count != rollback_count || + replication_view != term_of_next_version) + { + LOG_DEBUG_FMT( + "Batch for commit of {}.{} was rolled back at {}", + txid.view, + txid.seqno, + previous_last_replicated + offset); + return CommitResult::FAIL_NO_REPLICATE; + } + + // Published under version_lock, so that a rollback either discards + // these or prevents them from being published. + if (leaf.has_value()) + { + h->append_entry(leaf.value(), replication_view); + } + + if (chunker) { chunker->append_entry_size(data_shared->size()); } @@ -1324,6 +1370,13 @@ namespace ccf::kv offset++; } + // Consensus takes the role lock exclusively under its own lock, so this + // must not be held across a call which takes that lock. If this node + // stops being primary before replicate() runs, consensus discards the + // batch as it does so, and refuses it here, or by its old term if it has + // since been re-elected. + permit.release(); + if (c->replicate(batch, replication_view)) { std::lock_guard vguard(version_lock); @@ -1421,8 +1474,17 @@ namespace ccf::kv } std::optional> next_version( - Term expected_commit_term) override + Term expected_commit_term, const LocalWritePermit& permit) override { + if (!permit.allows_writes()) + { + KV_TRACE(trace::local_result("no_replicate", 0)); + LOG_DEBUG_FMT( + "Refusing to assign a version to a transaction because this node " + "does not accept local writes"); + return std::nullopt; + } + std::lock_guard vguard(version_lock); // If rollback updates the term before this lock is acquired, reject the // transaction before map writes are applied. If version allocation wins @@ -1444,13 +1506,19 @@ namespace ccf::kv return std::make_tuple(v, rollback_count); } - TxID next_txid() override + std::optional next_txid() override { KV_TRACE(trace::unsupported(this, "reserved transaction ID")); + auto permit = acquire_local_write_permit(); + if (!permit.allows_writes()) + { + return std::nullopt; + } + std::lock_guard vguard(version_lock); next_version_unsafe(); - return {term_of_next_version, version}; + return TxID{term_of_next_version, version}; } size_t committable_gap() override diff --git a/src/kv/test/kv_serialisation.cpp b/src/kv/test/kv_serialisation.cpp index bfe0b9f61940..cbbfb287a56c 100644 --- a/src/kv/test/kv_serialisation.cpp +++ b/src/kv/test/kv_serialisation.cpp @@ -722,7 +722,7 @@ TEST_CASE( ccf::kv::RawCopySerialisedValue> tree( ccf::Tables::SERIALISED_MERKLE_TREE); - auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); + auto tx = kv_store.create_reserved_tx(kv_store.next_txid().value()); tx.wo(tree)->put(std::vector(512, 'A')); const auto [result, data, claims, commit_evidence, hooks] = diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index 2e5ed52e9ec1..d7df96818af5 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -160,7 +160,7 @@ TEST_CASE("Live transactions cannot acquire signature table handles") CHECK(store.current_version() == 0); INFO("Denied while a signature reservation is pending and after it commits"); - const auto signature_txid = store.next_txid(); + const auto signature_txid = store.next_txid().value(); check_denied(); MapTypes::StringString ordinary("public:ordinary"); { @@ -200,7 +200,7 @@ TEST_CASE("Historical signature entries remain readable") { ccf::kv::Store source; source.set_encryptor(std::make_shared()); - const auto txid = source.next_txid(); + const auto txid = source.next_txid().value(); auto info = make_signature_entry(source, txid, 42); REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); @@ -248,7 +248,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") INFO("Cannot access non-signature maps or upgrade signature handles"); { - auto reserved = store.create_reserved_tx(store.next_txid()); + auto reserved = store.create_reserved_tx(store.next_txid().value()); CHECK_THROWS_AS( reserved.wo("public:ordinary"), ccf::kv::MapAccessDenied); @@ -277,7 +277,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") INFO("Clear on an empty signature table records a read and is rejected"); { - auto reserved = store.create_reserved_tx(store.next_txid()); + auto reserved = store.create_reserved_tx(store.next_txid().value()); auto* tree = reserved.wo( ccf::Tables::SERIALISED_MERKLE_TREE); tree->clear(); @@ -286,7 +286,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") } INFO("Recorded read dependencies on populated signature tables are rejected"); - const auto baseline = store.next_txid(); + const auto baseline = store.next_txid().value(); REQUIRE( publish_signature_entry(store, baseline, 1) == ccf::kv::CommitResult::SUCCESS); @@ -299,7 +299,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") "has_globally_committed"}) { INFO("Reserved observation: ", observation); - auto reserved = store.create_reserved_tx(store.next_txid()); + auto reserved = store.create_reserved_tx(store.next_txid().value()); auto* handle = reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); const auto key = ccf::SerialisedMerkleTree::create_unit(); @@ -342,11 +342,11 @@ TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") tx.rw(raw)->put("key", "old"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto old_signature = store.next_txid(); + const auto old_signature = store.next_txid().value(); REQUIRE( publish_signature_entry(store, old_signature, 1) == ccf::kv::CommitResult::SUCCESS); - const auto pending_signature = store.next_txid(); + const auto pending_signature = store.next_txid().value(); { auto tx = store.create_tx(); tx.rw(raw)->put("key", "new"); @@ -415,7 +415,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") tx.rw(raw)->put("key", "old"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto initial_signature = store.next_txid(); + const auto initial_signature = store.next_txid().value(); REQUIRE( publish_signature_entry(store, initial_signature, 1) == ccf::kv::CommitResult::SUCCESS); @@ -436,7 +436,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") tx.rw(raw)->put("key", "replacement"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto replacement_signature = store.next_txid(); + const auto replacement_signature = store.next_txid().value(); REQUIRE(replacement_signature.seqno == initial_signature.seqno); REQUIRE( publish_signature_entry(store, replacement_signature, 2) == @@ -487,7 +487,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") store.set_consensus(consensus); store.initialise_term(2); ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - const auto initial_signature = store.next_txid(); + const auto initial_signature = store.next_txid().value(); REQUIRE( publish_signature_entry(store, initial_signature, 1) == ccf::kv::CommitResult::SUCCESS); @@ -498,7 +498,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") consensus->view_history.rollback(0); consensus->flush(); REQUIRE( - publish_signature_entry(store, store.next_txid(), 2) == + publish_signature_entry(store, store.next_txid().value(), 2) == ccf::kv::CommitResult::SUCCESS); }; @@ -535,7 +535,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") store.set_encryptor(std::make_shared()); auto consensus = std::make_shared(store); store.set_consensus(consensus); - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); REQUIRE( publish_signature_entry(store, txid, 1) == ccf::kv::CommitResult::SUCCESS); @@ -3289,7 +3289,7 @@ TEST_CASE("Deserialise return status") } { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto sig_handle = tx.wo(signatures); auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); @@ -4375,7 +4375,7 @@ TEST_CASE("CommittableTx guards") const auto baseline_txid = kv_store.current_txid(); - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({42}); @@ -4399,7 +4399,7 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); REQUIRE_THROWS_WITH_AS( reserved.commit_reserved(), "Reserved transaction cannot be empty", @@ -4411,7 +4411,7 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - const auto reserved_txid = kv_store.next_txid(); + const auto reserved_txid = kv_store.next_txid().value(); auto reserved = kv_store.create_reserved_tx(reserved_txid); reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({42}); @@ -4441,7 +4441,7 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({42}); REQUIRE( @@ -4482,14 +4482,14 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - const auto baseline = kv_store.next_txid(); + const auto baseline = kv_store.next_txid().value(); REQUIRE( make_signature_entry(kv_store, baseline, 42).success == ccf::kv::CommitResult::SUCCESS); // Such a transaction would otherwise succeed with an empty ledger entry, // leaving nothing at its reserved version - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); auto* handle = reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); @@ -4705,8 +4705,8 @@ TEST_CASE("Stale-view writes which took their version early are rejected") if (reuse_versions) { // New reservations must not make the old-view transaction valid. - REQUIRE(store.next_txid() == ccf::TxID(new_term, 3)); - REQUIRE(store.next_txid() == ccf::TxID(new_term, 4)); + REQUIRE(store.next_txid().value() == ccf::TxID(new_term, 3)); + REQUIRE(store.next_txid().value() == ccf::TxID(new_term, 4)); } }; @@ -5171,7 +5171,7 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") { // Rollback removes the signature tables so the next reservation creates // them again, exercising add_dynamic_map on every iteration. - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); REQUIRE( make_signature_entry(store, txid, 42).success == ccf::kv::CommitResult::SUCCESS); @@ -5271,7 +5271,7 @@ TEST_CASE("Chunk metadata is not restored by a batch a rollback discarded") "A batch whose writes are discarded by a rollback must not leave chunk " "metadata behind"); { - const auto reserved = store.next_txid(); + const auto reserved = store.next_txid().value(); REQUIRE(reserved.seqno == baseline_txid.seqno + 1); // The rollback target is below the reserved version, so it truncates and @@ -5773,7 +5773,7 @@ TEST_CASE("Ledger entry chunk request") INFO( "Add a signature transaction which triggers chunk via entry header flag"); { - auto txid = store.next_txid(); + auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); auto sig_handle = tx.wo(signatures); auto tree_handle = tx.wo(serialised_tree); @@ -5844,7 +5844,7 @@ TEST_CASE("Ledger entry chunk request") INFO("Add a signature that triggers a snapshot"); { - auto txid = store.next_txid(); + auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); // The store must know that we need a new ledger chunk at this version @@ -5895,12 +5895,12 @@ TEST_CASE("Store version wraps to 0 past INT64_MAX") ccf::kv::ApplyResult::PASS); REQUIRE(kv_store.current_version() == max_signed_version); - const auto wrapped_txid = kv_store.next_txid(); + const auto wrapped_txid = kv_store.next_txid().value(); REQUIRE(wrapped_txid.view == 2); REQUIRE(wrapped_txid.seqno == 0); REQUIRE(kv_store.current_version() == 0); - const auto next_txid = kv_store.next_txid(); + const auto next_txid = kv_store.next_txid().value(); REQUIRE(next_txid.view == 2); REQUIRE(next_txid.seqno == 1); REQUIRE(kv_store.current_version() == 1); @@ -5931,8 +5931,8 @@ TEST_CASE("Store::commit edge cases") store.set_consensus(consensus); store.initialise_term(1); - const auto txid1 = store.next_txid(); - const auto txid2 = store.next_txid(); + const auto txid1 = store.next_txid().value(); + const auto txid2 = store.next_txid().value(); REQUIRE(txid1.seqno == 1); REQUIRE(txid2.seqno == 2); @@ -5965,7 +5965,7 @@ TEST_CASE("Store::commit edge cases") store.set_consensus(consensus); store.initialise_term(1); - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); REQUIRE( store.commit( txid, diff --git a/src/kv/test/null_tx_history.h b/src/kv/test/null_tx_history.h index 5d8ee93551e4..d50ebc329351 100644 --- a/src/kv/test/null_tx_history.h +++ b/src/kv/test/null_tx_history.h @@ -116,7 +116,12 @@ namespace ccf void emit_signature() override { - auto txid = store.next_txid(); + auto next_txid = store.next_txid(); + if (!next_txid.has_value()) + { + return; + } + const auto txid = next_txid.value(); LOG_DEBUG_FMT("Issuing signature at {}.{}", txid.view, txid.seqno); store.commit( txid, std::make_unique(txid, store, id), true); diff --git a/src/node/history.h b/src/node/history.h index c4f16937c373..4653bf331902 100644 --- a/src/node/history.h +++ b/src/node/history.h @@ -829,7 +829,15 @@ namespace ccf fmt::format("No endorsed certificate set to emit signature")); } - auto txid = store.next_txid(); + // Refused if this node has stopped being primary, or completed + // retirement, since the caller checked, so do not sign. + auto next_txid = store.next_txid(); + if (!next_txid.has_value()) + { + LOG_DEBUG_FMT("Not signing because local writes are disabled"); + return; + } + const auto txid = next_txid.value(); LOG_DEBUG_FMT("Signed at {} in view: {}", txid.seqno, txid.view); diff --git a/src/node/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index 6d9ded974d4e..b0585ce90e98 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -833,7 +833,7 @@ TEST_CASE("Node state is explicitly nontransactional metadata") network.tables->initialise_term(2); auto publish_signature = [&](ccf::kv::Version reported_seqno) { - const auto txid = network.tables->next_txid(); + const auto txid = network.tables->next_txid().value(); auto tx = network.tables->create_reserved_tx(txid); tx.wo(Tables::SIGNATURES) ->put( diff --git a/src/node/snapshotter.h b/src/node/snapshotter.h index 14678559c800..b3ee45edb431 100644 --- a/src/node/snapshotter.h +++ b/src/node/snapshotter.h @@ -74,6 +74,10 @@ namespace ccf std::optional cose_sigs = std::nullopt; std::optional> tree = std::nullopt; + // Index of the signature that cose_sigs and tree were recorded from. + // They are only valid while that signature is not rolled back, and are + // only used once it is committed. + std::optional<::consensus::Index> receipt_sig_idx = std::nullopt; // Outputs of the serialise action, handed to the persist action. std::shared_ptr serialised; @@ -402,7 +406,10 @@ namespace ccf if ( snapshot_info.evidence_idx.has_value() && idx > snapshot_info.evidence_idx.value() && - snapshot_info.cose_sigs.has_value() && snapshot_info.tree.has_value()) + snapshot_info.cose_sigs.has_value() && + snapshot_info.tree.has_value() && + snapshot_info.receipt_sig_idx.has_value() && + idx >= snapshot_info.receipt_sig_idx.value()) { // Commit evidence is durable. Enqueue the persist action on this // generation's ordered task collection. OrderedTasks guarantees it @@ -567,7 +574,8 @@ namespace ccf if ( pending_snapshot.evidence_idx.has_value() && idx > pending_snapshot.evidence_idx.value() && - !pending_snapshot.cose_sigs.has_value()) + !pending_snapshot.cose_sigs.has_value() && + pending_snapshot.receipt_sig_idx.value_or(idx) == idx) { LOG_TRACE_FMT( "Recording {} COSE signature(s) at {} for snapshot {} with " @@ -578,6 +586,7 @@ namespace ccf pending_snapshot.evidence_idx.value()); pending_snapshot.cose_sigs = cose_sigs; + pending_snapshot.receipt_sig_idx = idx; } } } @@ -592,7 +601,8 @@ namespace ccf if ( pending_snapshot.evidence_idx.has_value() && idx > pending_snapshot.evidence_idx.value() && - !pending_snapshot.tree.has_value()) + !pending_snapshot.tree.has_value() && + pending_snapshot.receipt_sig_idx.value_or(idx) == idx) { LOG_TRACE_FMT( "Recording serialised tree at {} for snapshot {} with evidence at " @@ -602,6 +612,7 @@ namespace ccf pending_snapshot.evidence_idx.value()); pending_snapshot.tree = tree; + pending_snapshot.receipt_sig_idx = idx; } } } @@ -772,6 +783,33 @@ namespace ccf pending_snapshots.erase(last_snapshot); } + + // Evidence transactions from different generations may commit out of + // generation order, so an older snapshot may still have rolled back + // evidence. + std::erase_if(pending_snapshots, [idx](const auto& entry) { + const auto& evidence_idx = entry.second.evidence_idx; + return evidence_idx.has_value() && evidence_idx.value() > idx; + }); + + // A remaining snapshot's evidence survives, but the signature its + // receipt was taken from may not. Discard that receipt material, so + // that it is recorded again from the next signature. + for (auto& [_, pending_snapshot] : pending_snapshots) + { + if ( + pending_snapshot.receipt_sig_idx.has_value() && + pending_snapshot.receipt_sig_idx.value() > idx) + { + LOG_TRACE_FMT( + "Discarding receipt from signature at {} for snapshot {}", + pending_snapshot.receipt_sig_idx.value(), + pending_snapshot.version); + pending_snapshot.cose_sigs.reset(); + pending_snapshot.tree.reset(); + pending_snapshot.receipt_sig_idx.reset(); + } + } } }; } diff --git a/src/node/test/historical_queries.cpp b/src/node/test/historical_queries.cpp index 3ba0384ca70c..99be84e5b2f7 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -1792,7 +1792,7 @@ TEST_CASE("Historical receipts preserve the transaction view across signatures") auto state = create_and_init_state(); auto& store = *state.kv_store; const auto emit_signature = [&]() { - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); auto history = store.get_history(); auto cert = std::make_shared( state.node_kp->self_sign("CN=Test node", valid_from, valid_to)); @@ -1965,7 +1965,7 @@ TEST_CASE("Historical cache rejects signatures which misreport their TxID") // Write a signature transaction by hand, which declares a TxID in a later // view than the one it is actually committed in - const auto signature_txid = store.next_txid(); + const auto signature_txid = store.next_txid().value(); const auto signature_seqno = signature_txid.seqno; const ccf::TxID declared_id{signature_txid.view + 1, signature_seqno}; { @@ -4126,7 +4126,7 @@ TEST_CASE( for (const auto& written_signatures : signature_transactions) { - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); for (const auto& [identity_type, signature] : written_signatures) diff --git a/src/node/test/history.cpp b/src/node/test/history.cpp index d2e2fc64601e..2d664aab97d9 100644 --- a/src/node/test/history.cpp +++ b/src/node/test/history.cpp @@ -226,7 +226,7 @@ struct SigningFixture std::optional emit_signature( CustomSignaturePendingTx::WriteSignatures write_signatures) { - const auto txid = primary_store.next_txid(); + const auto txid = primary_store.next_txid().value(); primary_store.commit( txid, std::make_unique( @@ -316,7 +316,7 @@ TEST_CASE("Check signature verification") INFO("Issue a bogus signature, rejected by verification on the backup"); { - const auto txid = primary_store.next_txid(); + const auto txid = primary_store.next_txid().value(); auto txs = primary_store.create_reserved_tx(txid); auto sigs = txs.wo(signatures); ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, txid.seqno); @@ -930,7 +930,7 @@ TEST_CASE("Pending signatures retain their endorsed certificate") constexpr auto store_term = 2; store.initialise_term(store_term); - const auto gap_txid = store.next_txid(); + const auto gap_txid = store.next_txid().value(); history->emit_signature(); REQUIRE(consensus->number_of_replicas() == 0); @@ -1108,7 +1108,7 @@ TEST_CASE( INFO("Batch of two, starting with a commitable"); { - auto rv = store.next_txid(); + auto rv = store.next_txid().value(); auto tx = store.create_tx(); auto txv = tx.rw(table); @@ -1260,7 +1260,7 @@ TEST_CASE( REQUIRE(store.current_version() == 2); - auto txid = store.next_txid(); + auto txid = store.next_txid().value(); REQUIRE(txid == ccf::TxID(store_term, 3)); PausedSignatureCommit paused; @@ -1373,7 +1373,7 @@ TEST_CASE("COSE signature table holds one entry per identity") INFO("A table carrying two identities round-trips both"); { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto* handle = tx.wo(ccf::Tables::COSE_SIGNATURES); handle->put(ccf::IdentityType::CLASSICAL, ec384_sig); handle->put(ccf::IdentityType::PQ, mldsa65_sig); @@ -1410,7 +1410,7 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") const ccf::CoseSignature keyed_signature{4, 5, 6}; { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); tx.wo(ccf::Tables::COSE_SIGNATURES) ->put(legacy_signature); tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) @@ -1426,7 +1426,7 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") } { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); signatures->put(ccf::IdentityType::CLASSICAL, keyed_signature); tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index a73e341e34ee..7895b968d455 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -1274,6 +1274,128 @@ TEST_CASE("Rollback before snapshot is committed") } } +TEST_CASE("Rollback discards a snapshot receipt from a rolled back signature") +{ + ccf::NetworkState network; + auto consensus = std::make_shared(); + auto history = std::make_shared( + *network.tables.get(), ccf::kv::test::PrimaryNodeId, *node_kp); + network.tables->set_history(history); + network.tables->initialise_term(2); + network.tables->set_consensus(consensus); + auto encryptor = std::make_shared(); + network.tables->set_encryptor(encryptor); + + ScopedSnapshotDir snapshot_dir; + + size_t snapshot_tx_interval = 10; + issue_transactions(network, snapshot_tx_interval); + + auto snapshotter = std::make_shared( + snapshot_dir.path.string(), network.tables, snapshot_tx_interval); + + const size_t snapshot_idx = snapshot_tx_interval; + const size_t evidence_idx = snapshot_idx + 1; + const size_t receipt_sig_idx = snapshot_idx + 2; + + INFO("Generate snapshot, its evidence, and a signature after it"); + { + REQUIRE(record_signature(history, snapshotter, snapshot_idx)); + snapshotter->commit(snapshot_idx, true); + run_one_task(); + REQUIRE(read_latest_snapshot_evidence(network.tables) == snapshot_idx); + + issue_transactions(network, 1); + record_snapshot_evidence(snapshotter, snapshot_idx, evidence_idx); + REQUIRE_FALSE(record_signature(history, snapshotter, receipt_sig_idx)); + } + + INFO("Roll back the signature, but not the evidence"); + snapshotter->rollback(evidence_idx); + + INFO("The snapshot is not released without a receipt from a new signature"); + { + issue_transactions(network, 1); + snapshotter->commit(receipt_sig_idx + 1, true); + run_one_task(); + REQUIRE_FALSE(latest_committed_snapshot_idx(snapshot_dir.path).has_value()); + } + + INFO("The snapshot is released with a receipt from the new signature"); + { + REQUIRE_FALSE(record_signature(history, snapshotter, receipt_sig_idx + 1)); + snapshotter->commit(receipt_sig_idx + 1, true); + run_one_task(); + REQUIRE(latest_committed_snapshot_idx(snapshot_dir.path) == snapshot_idx); + } +} + +TEST_CASE("Rollback discards evidence recorded out of generation order") +{ + ccf::NetworkState network; + auto consensus = std::make_shared(); + auto history = std::make_shared( + *network.tables.get(), ccf::kv::test::PrimaryNodeId, *node_kp); + network.tables->set_history(history); + network.tables->initialise_term(2); + network.tables->set_consensus(consensus); + auto encryptor = std::make_shared(); + network.tables->set_encryptor(encryptor); + + ScopedSnapshotDir snapshot_dir; + + size_t snapshot_tx_interval = 10; + issue_transactions(network, snapshot_tx_interval); + + auto snapshotter = std::make_shared( + snapshot_dir.path.string(), network.tables, snapshot_tx_interval); + + const size_t older_snapshot_idx = snapshot_tx_interval; + const size_t newer_snapshot_idx = 2 * snapshot_tx_interval; + + INFO("Generate two snapshots, neither of which has evidence yet"); + { + REQUIRE(record_signature(history, snapshotter, older_snapshot_idx)); + snapshotter->commit(older_snapshot_idx, true); + run_one_task(); + + issue_transactions(network, newer_snapshot_idx - 1 - older_snapshot_idx); + REQUIRE(record_signature(history, snapshotter, newer_snapshot_idx)); + snapshotter->commit(newer_snapshot_idx, true); + run_one_task(); + } + + INFO("The newer snapshot's evidence is recorded before the older one's"); + const size_t kept_evidence_idx = newer_snapshot_idx + 1; + const size_t rolled_back_evidence_idx = newer_snapshot_idx + 2; + record_snapshot_evidence(snapshotter, newer_snapshot_idx, kept_evidence_idx); + record_snapshot_evidence( + snapshotter, older_snapshot_idx, rolled_back_evidence_idx); + + INFO("Roll back the older snapshot's evidence, but not the newer one's"); + snapshotter->rollback(kept_evidence_idx); + + INFO("Only the snapshot with surviving evidence is released"); + { + issue_transactions(network, 2); + const size_t sig_idx = rolled_back_evidence_idx + 1; + REQUIRE(network.tables->current_version() == sig_idx); + REQUIRE_FALSE(record_signature(history, snapshotter, sig_idx)); + snapshotter->commit(sig_idx, true); + run_one_task(); + run_one_task(); + + REQUIRE( + latest_committed_snapshot_idx(snapshot_dir.path) == newer_snapshot_idx); + for (const auto& entry : fs::directory_iterator(snapshot_dir.path)) + { + CHECK( + ccf::snapshots::get_snapshot_idx_from_file_name( + entry.path().filename()) != older_snapshot_idx); + } + } +} + TEST_CASE("Failed snapshot evidence commits do not block later snapshots") { ccf::NetworkState network; @@ -1448,7 +1570,7 @@ TEST_CASE("Rekey ledger while snapshot is in progress") { // It is necessary to record a signature for the snapshot to be // deserialisable by the backup store - const auto txid = network.tables->next_txid(); + const auto txid = network.tables->next_txid().value(); auto tx = network.tables->create_reserved_tx(txid); auto sigs = tx.wo(ccf::Tables::SIGNATURES); auto trees = From 85b6d486166de7d1c77335232d38e79b7be29d47 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Fri, 4 Dec 2026 15:05:56 +0000 Subject: [PATCH 3/3] Revert #8921 cherry-pick prep and adapt 7.x tests Remove temporary 8.0 context from cft.h (#include and trace::tick) and restore 7.x test files with next_txid().value() updates, 7.x baseline seqno adjustments in view_straddling tests, and the new snapshotter rollback tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8734db1e936445abbf809bd1a0477afa --- src/consensus/aft/cft.h | 3 - src/consensus/aft/test/main.cpp | 674 ------------- .../aft/test/view_straddling_common.h | 45 +- .../aft/test/view_straddling_history.cpp | 67 +- .../aft/test/view_straddling_rollback.cpp | 60 +- src/js/test/js.cpp | 451 +-------- src/kv/test/kv_serialisation.cpp | 25 +- src/kv/test/kv_test.cpp | 917 ++---------------- src/node/rpc/test/node_frontend_test.cpp | 519 +--------- src/node/test/historical_queries.cpp | 301 ++---- src/node/test/history.cpp | 473 +-------- src/node/test/snapshotter.cpp | 55 +- 12 files changed, 360 insertions(+), 3230 deletions(-) diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index e09306d9a695..1b509069112d 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -21,7 +21,6 @@ #include #include -#include #include #include #include @@ -2108,8 +2107,6 @@ namespace aft return; } - trace::tick(*state); - set_leadership_state(ccf::kv::LeadershipState::PreVoteCandidate); leader_id.reset(); diff --git a/src/consensus/aft/test/main.cpp b/src/consensus/aft/test/main.cpp index d38be3e64379..e49147a0b396 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -1,10 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. -#include "kv/store.h" -#include "kv/test/stub_consensus.h" #include "node/commit_callback_subsystem.h" -#include "service/tables/signatures.h" #include "test_common.h" #include @@ -60,91 +57,6 @@ DOCTEST_TEST_CASE( DOCTEST_CHECK(calls.size() == 3); } -DOCTEST_TEST_CASE( - "Retirement nomination excludes every peer confirmed in the batch" * - doctest::test_suite("retirement")) -{ - for (const auto self_id : {"1", "3"}) - { - const ccf::NodeId self{self_id}; - DOCTEST_INFO("Primary ID: ", self); - const ccf::NodeId survivor{"0"}; - const ccf::NodeId retiring_peer{"2"}; - auto kv_store = std::make_shared(self); - auto state = std::make_shared(self); - TCft cft( - cft_settings, - std::make_unique(kv_store), - std::make_unique(self), - std::make_shared(), - state, - nullptr); - aft::Configuration::Nodes config; - config[self] = {}; - config[survivor] = {}; - config[retiring_peer] = {}; - cft.add_configuration(0, config); - cft.force_become_primary(); - state->membership_state = ccf::kv::MembershipState::Retired; - state->retirement_phase = ccf::kv::RetirementPhase::Completed; - auto channels = channel_stub_proxy(cft); - channels->messages.clear(); - - std::vector confirmed = {self, retiring_peer}; - std::sort(confirmed.begin(), confirmed.end()); - cft.set_retired_committed(5, confirmed); - - DOCTEST_REQUIRE(channels->messages.size() == 1); - DOCTEST_CHECK(channels->messages.front().first == survivor); - DOCTEST_CHECK( - channels->count_messages_with_type(aft::propose_request_vote) == 1); - DOCTEST_CHECK(state->retired_committed_idx == 5); - DOCTEST_CHECK(cft.is_retired_committed()); - DOCTEST_CHECK_FALSE(cft.is_primary()); - } -} - -DOCTEST_TEST_CASE( - "Retired primary sends a single entry but not a heartbeat" * - doctest::test_suite("retirement")) -{ - const auto self = ccf::kv::test::PrimaryNodeId; - const auto peer = ccf::kv::test::FirstBackupNodeId; - auto kv_store = std::make_shared(self); - auto state = std::make_shared(self); - TCft cft( - cft_settings, - std::make_unique(kv_store), - std::make_unique(self), - std::make_shared(), - state, - nullptr); - aft::Configuration::Nodes config; - config[self] = {}; - config[peer] = {}; - cft.add_configuration(0, config); - cft.force_become_primary(); - auto channels = channel_stub_proxy(cft); - channels->messages.clear(); - auto entry = std::make_shared>(3, 1); - DOCTEST_REQUIRE(cft.replicate( - ccf::kv::BatchVector{{1, entry, true, hooks}}, cft.get_view())); - - // Synthetic state: committing retirement normally clears the primary role. - state->membership_state = ccf::kv::MembershipState::Retired; - state->retirement_phase = ccf::kv::RetirementPhase::RetiredCommitted; - cft.periodic(request_timeout); - auto message = channels->pop_first(aft::append_entries, peer); - DOCTEST_REQUIRE(message.has_value()); - const uint8_t* data = message->data(); - auto size = message->size(); - const auto ae = serialized::read(data, size); - DOCTEST_CHECK(ae.idx == 1); - DOCTEST_CHECK(ae.prev_idx == 0); - cft.periodic(request_timeout); - DOCTEST_CHECK(channels->messages.empty()); -} - DOCTEST_TEST_CASE("cft owns its periodic timer" * doctest::test_suite("single")) { const auto self = ccf::kv::test::PrimaryNodeId; @@ -1958,71 +1870,6 @@ DOCTEST_TEST_CASE( DOCTEST_REQUIRE(r0.is_primary()); } -DOCTEST_TEST_CASE( - "Nodes added by a rolled back configuration are forgotten" * - doctest::test_suite("multiple")) -{ - ccf::NodeId node_id0 = ccf::kv::test::PrimaryNodeId; - ccf::NodeId node_id1 = ccf::kv::test::FirstBackupNodeId; - ccf::NodeId node_id2 = ccf::kv::test::SecondBackupNodeId; - ccf::NodeId node_id3 = ccf::kv::test::ThirdBackupNodeId; - - TestNode node0(node_id0); - auto& r0 = node0.cft; - auto r0c = channel_stub_proxy(r0); - - aft::Configuration::Nodes config; - config[node_id0] = {}; - config[node_id1] = {}; - config[node_id2] = {}; - r0.add_configuration(0, config); - r0.force_become_primary(); - - DOCTEST_INFO( - "Node 2 retires: its retirement is committed, and not confirmed"); - config.erase(node_id2); - auto retire_hooks = std::make_shared(); - retire_hooks->push_back( - std::make_unique(config, 1)); - auto data = std::make_shared>(3, 1); - DOCTEST_REQUIRE(r0.replicate( - ccf::kv::BatchVector{{1, data, true, retire_hooks}}, r0.get_view())); - const auto ack = as_bytes(aft::AppendEntriesResponse{ - .term = r0.get_view(), - .last_log_idx = 1, - .success = aft::AppendEntriesResponseType::OK}); - r0.recv_message(node_id1, ack); - DOCTEST_REQUIRE(r0.get_committed_seqno() == 1); - DOCTEST_REQUIRE(r0.get_details().configs.size() == 1); - - DOCTEST_INFO("A configuration which is not committed adds node 3"); - config[node_id3] = {}; - auto trust_hooks = std::make_shared(); - trust_hooks->push_back( - std::make_unique(config, 2)); - DOCTEST_REQUIRE(r0.replicate( - ccf::kv::BatchVector{{2, data, true, trust_hooks}}, r0.get_view())); - DOCTEST_REQUIRE(r0.get_details().configs.size() == 2); - DOCTEST_REQUIRE(r0.get_details().acks.contains(node_id3)); - - DOCTEST_INFO("Once it is rolled back, no configuration names node 3"); - r0.rollback(1); - DOCTEST_REQUIRE(r0.get_details().configs.size() == 1); - DOCTEST_REQUIRE_FALSE(r0.get_details().acks.contains(node_id3)); - - DOCTEST_INFO( - "Node 1 is in the configuration which remains, and the retirement of " - "node 2 is still to confirm"); - DOCTEST_REQUIRE(r0.get_details().acks.contains(node_id1)); - DOCTEST_REQUIRE(r0.get_details().acks.contains(node_id2)); - r0c->messages.clear(); - r0.periodic(request_timeout); - DOCTEST_REQUIRE_FALSE( - r0c->pop_first(aft::append_entries, node_id3).has_value()); - DOCTEST_REQUIRE(r0c->pop_first(aft::append_entries, node_id1).has_value()); - DOCTEST_REQUIRE(r0c->pop_first(aft::append_entries, node_id2).has_value()); -} - DOCTEST_TEST_CASE( "cft messages that cannot be parsed are ignored" * doctest::test_suite("multiple")) @@ -3323,527 +3170,6 @@ DOCTEST_TEST_CASE( DOCTEST_REQUIRE(r0.ledger->ledger.size() == 1); } -DOCTEST_TEST_CASE( - "Nodes refuse a configuration with no nodes" * doctest::test_suite("single")) -{ - ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; - TestNode node(node_id); - auto& r0 = node.cft; - - aft::Configuration::Nodes config; - config[node_id] = {}; - r0.add_configuration(0, config); - - r0.start_ticking(); - r0.periodic(election_timeout * 2); - DOCTEST_REQUIRE(r0.is_primary()); - - auto entry = - std::make_shared>(std::vector{1, 2, 3}); - DOCTEST_REQUIRE( - r0.replicate(ccf::kv::BatchVector{{1, entry, true, hooks}}, 1)); - DOCTEST_REQUIRE(r0.get_committed_seqno() == 1); - - DOCTEST_INFO("The transaction which removes the only node is refused"); - auto removal_hooks = std::make_shared(); - removal_hooks->push_back(std::make_unique( - aft::Configuration::Nodes{}, 2)); - DOCTEST_REQUIRE_THROWS_WITH_AS( - r0.replicate(ccf::kv::BatchVector{{2, entry, false, removal_hooks}}, 1), - "Configuration at 2 has no nodes", - std::logic_error); - - DOCTEST_INFO("Nothing is appended, and the configuration is as it was"); - DOCTEST_REQUIRE(r0.get_last_idx() == 1); - DOCTEST_REQUIRE(r0.ledger->ledger.size() == 1); - const auto details = r0.get_details(); - DOCTEST_REQUIRE(details.configs.size() == 1); - DOCTEST_REQUIRE(details.configs.back().nodes == config); - DOCTEST_REQUIRE(details.membership_state == ccf::kv::MembershipState::Active); - DOCTEST_REQUIRE(r0.is_primary()); - - DOCTEST_INFO("A backup also refuses add_configuration with no nodes"); - TestNode backup(ccf::kv::test::FirstBackupNodeId); - backup.cft.add_configuration(0, config); - DOCTEST_REQUIRE_THROWS_WITH_AS( - backup.cft.add_configuration(2, {}), - "Configuration at 2 has no nodes", - std::logic_error); - DOCTEST_REQUIRE(backup.cft.get_details().configs.size() == 1); - DOCTEST_REQUIRE(backup.cft.get_details().configs.back().nodes == config); - - DOCTEST_INFO( - "A follower receiving an AppendEntries with an empty configuration " - "rolls back its KV, ledger, and configurations and NACKs"); - - using ValueMap = ccf::kv::Map; - using ConfigMap = ccf::kv::Map; - - class TermPreservingEncryptor : public ccf::kv::AbstractTxEncryptor - { - public: - bool encrypt( - const std::vector& plain, - const std::vector&, - std::vector& serialised_header, - std::vector& cipher, - const ccf::TxID& tx_id, - ccf::kv::EntryType = ccf::kv::EntryType::WriteSet, - bool = false) override - { - serialised_header.resize(sizeof(ccf::kv::Term)); - uint8_t* p = serialised_header.data(); - size_t s = serialised_header.size(); - serialized::write(p, s, tx_id.view); - cipher = plain; - return true; - } - - bool decrypt( - const std::vector& cipher, - const std::vector&, - const std::vector& serialised_header, - std::vector& plain, - ccf::kv::Version, - ccf::kv::Term& term, - bool = false) override - { - plain = cipher; - term = get_term(serialised_header.data(), serialised_header.size()); - return true; - } - - ccf::crypto::HashBytes get_commit_nonce( - const ccf::TxID&, bool = false) override - { - return {}; - } - - size_t get_header_length() override - { - return sizeof(ccf::kv::Term); - } - - uint64_t get_term(const uint8_t* data, size_t size) override - { - return serialized::read(data, size); - } - - void rollback(ccf::kv::Version) override {} - }; - - struct FollowerFixture - { - const ccf::NodeId primary_id = ccf::kv::test::PrimaryNodeId; - const ccf::NodeId follower_id = ccf::kv::test::FirstBackupNodeId; - const ccf::NodeId third_id = ccf::kv::test::SecondBackupNodeId; - - ValueMap values{"public:table"}; - ConfigMap configs{"public:test_config"}; - ccf::Signatures signatures{ccf::Tables::SIGNATURES}; - ccf::SerialisedMerkleTree serialised_tree{ - ccf::Tables::SERIALISED_MERKLE_TREE}; - - ccf::kv::Store sender_store; - std::shared_ptr sender_consensus = - std::make_shared(); - std::shared_ptr follower_store = - std::make_shared(); - std::shared_ptr follower_channels = - std::make_shared(); - aft::Aft follower; - std::vector> raw_entries; - - aft::Configuration::Nodes two_node_config; - aft::Configuration::Nodes three_node_config; - - FollowerFixture() : - follower( - cft_settings, - std::make_unique>(follower_store), - std::make_unique(follower_id), - follower_channels, - std::make_shared(follower_id), - nullptr) - { - auto encryptor = std::make_shared(); - sender_store.set_encryptor(encryptor); - sender_store.set_consensus(sender_consensus); - sender_store.initialise_term(1); - - follower_store->set_encryptor(encryptor); - follower_store->set_map_hook( - configs.get_name(), - configs.wrap_map_hook( - [](ccf::kv::Version v, const ConfigMap::Write& w) - -> ccf::kv::ConsensusHookPtr { - if (const auto it = w.find(0); - it != w.end() && it->second.has_value()) - { - return std::make_unique( - *it->second, v); - } - return nullptr; - })); - - two_node_config[primary_id] = {}; - two_node_config[follower_id] = {}; - three_node_config = two_node_config; - three_node_config[third_id] = {}; - - follower.add_configuration(0, two_node_config); - } - - ccf::kv::Version append_signature() - { - const auto txid = sender_store.next_txid().value(); - auto tx = sender_store.create_reserved_tx(txid); - tx.wo(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); - tx.wo(serialised_tree)->put({}); - auto [rc, data, claims_digest, commit_evidence_digest, tx_hooks] = - tx.commit_reserved(); - DOCTEST_REQUIRE(rc == ccf::kv::CommitResult::SUCCESS); - DOCTEST_REQUIRE( - sender_store.commit( - txid, - std::make_unique( - std::move(data), - std::move(claims_digest), - std::move(commit_evidence_digest), - std::move(tx_hooks)), - true) == ccf::kv::CommitResult::SUCCESS); - const auto replicated = sender_consensus->get_latest_data(); - DOCTEST_REQUIRE(replicated.has_value()); - raw_entries.push_back(*replicated); - return txid.seqno; - } - - ccf::kv::Version append_entry( - size_t key, - size_t value, - const std::optional& new_config = std::nullopt) - { - auto tx = sender_store.create_tx(); - tx.rw(values)->put(key, value); - if (new_config.has_value()) - { - tx.rw(configs)->put(0, *new_config); - } - DOCTEST_REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - const auto replicated = sender_consensus->get_latest_data(); - DOCTEST_REQUIRE(replicated.has_value()); - raw_entries.push_back(*replicated); - return tx.commit_version(); - } - - void deliver( - aft::Index prev_idx, - aft::Index idx, - aft::Term prev_term, - aft::Index leader_commit_idx) - { - std::vector payload; - for (aft::Index i = prev_idx + 1; i <= idx; ++i) - { - const auto& entry = raw_entries.at(i - 1); - const size_t entry_size = entry.size(); - const size_t offset = payload.size(); - payload.resize(offset + sizeof(size_t) + entry_size); - uint8_t* ptr = payload.data() + offset; - size_t remaining = sizeof(size_t); - serialized::write(ptr, remaining, entry_size); - std::copy( - entry.begin(), - entry.end(), - payload.begin() + offset + sizeof(size_t)); - } - - aft::AppendEntries ae{}; - ae.idx = idx; - ae.prev_idx = prev_idx; - ae.term = 1; - ae.prev_term = prev_term; - ae.leader_commit_idx = leader_commit_idx; - ae.term_of_idx = 1; - follower.recv_message( - primary_id, - {reinterpret_cast(&ae), sizeof(ae)}, - payload); - } - - std::optional read_value(size_t key) - { - auto tx = follower_store->create_read_only_tx(); - return tx.ro(values)->get(key); - } - - aft::AppendEntriesResponse pop_response() - { - auto resp_msg = - follower_channels->pop_first(aft::append_entries_response, primary_id); - DOCTEST_REQUIRE(resp_msg.has_value()); - return read_msg(*resp_msg); - } - }; - - DOCTEST_SUBCASE("Preserves existing unsigned suffix on rollback") - { - FollowerFixture fx; - DOCTEST_REQUIRE(fx.append_signature() == 1); - DOCTEST_REQUIRE(fx.append_entry(2, 200, fx.three_node_config) == 2); - DOCTEST_REQUIRE(fx.append_entry(3, 300, fx.two_node_config) == 3); - DOCTEST_REQUIRE(fx.append_entry(4, 400, aft::Configuration::Nodes{}) == 4); - - fx.deliver(0, 1, 0, 1); - fx.deliver(1, 2, 1, 1); - DOCTEST_REQUIRE(fx.follower.get_last_idx() == 2); - DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 1); - DOCTEST_REQUIRE(fx.follower_store->current_version() == 2); - DOCTEST_REQUIRE(fx.read_value(2) == 200); - DOCTEST_REQUIRE(fx.follower.ledger->ledger.size() == 2); - fx.follower_channels->messages.clear(); - - fx.deliver(2, 4, 1, 1); - - DOCTEST_REQUIRE(fx.follower.get_last_idx() == 2); - DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 1); - DOCTEST_REQUIRE(fx.follower_store->current_version() == 2); - DOCTEST_REQUIRE(fx.read_value(2) == 200); - DOCTEST_REQUIRE_FALSE(fx.read_value(3).has_value()); - DOCTEST_REQUIRE_FALSE(fx.read_value(4).has_value()); - DOCTEST_REQUIRE(fx.follower.ledger->ledger.size() == 2); - const auto follower_details = fx.follower.get_details(); - DOCTEST_REQUIRE(follower_details.configs.size() == 2); - DOCTEST_REQUIRE(follower_details.configs[0].idx == 0); - DOCTEST_REQUIRE(follower_details.configs[0].nodes == fx.two_node_config); - DOCTEST_REQUIRE(follower_details.configs[1].idx == 2); - DOCTEST_REQUIRE(follower_details.configs[1].nodes == fx.three_node_config); - DOCTEST_REQUIRE( - follower_details.membership_state == ccf::kv::MembershipState::Active); - - const auto resp = fx.pop_response(); - DOCTEST_REQUIRE(resp.success == aft::AppendEntriesResponseType::FAIL); - DOCTEST_REQUIRE(resp.last_log_idx == 2); - } - - DOCTEST_SUBCASE( - "Preserves signature accepted earlier in the same AppendEntries batch") - { - FollowerFixture fx; - DOCTEST_REQUIRE(fx.append_signature() == 1); - DOCTEST_REQUIRE(fx.append_entry(2, 200, fx.three_node_config) == 2); - DOCTEST_REQUIRE(fx.append_signature() == 3); - DOCTEST_REQUIRE(fx.append_entry(4, 400, fx.two_node_config) == 4); - DOCTEST_REQUIRE(fx.append_entry(5, 500, aft::Configuration::Nodes{}) == 5); - - fx.deliver(0, 1, 0, 1); - DOCTEST_REQUIRE(fx.follower.get_last_idx() == 1); - DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 1); - DOCTEST_REQUIRE(fx.follower_store->current_version() == 1); - fx.follower_channels->messages.clear(); - - fx.deliver(1, 5, 1, 3); - - DOCTEST_REQUIRE(fx.follower.get_last_idx() == 3); - DOCTEST_REQUIRE(fx.follower.get_committed_seqno() == 3); - DOCTEST_REQUIRE(fx.follower_store->current_version() == 3); - DOCTEST_REQUIRE(fx.read_value(2) == 200); - DOCTEST_REQUIRE_FALSE(fx.read_value(4).has_value()); - DOCTEST_REQUIRE_FALSE(fx.read_value(5).has_value()); - DOCTEST_REQUIRE(fx.follower.ledger->ledger.size() == 3); - const auto follower_details = fx.follower.get_details(); - DOCTEST_REQUIRE(follower_details.configs.size() == 1); - DOCTEST_REQUIRE(follower_details.configs[0].idx == 2); - DOCTEST_REQUIRE(follower_details.configs[0].nodes == fx.three_node_config); - DOCTEST_REQUIRE( - follower_details.membership_state == ccf::kv::MembershipState::Active); - - const auto resp = fx.pop_response(); - DOCTEST_REQUIRE(resp.success == aft::AppendEntriesResponseType::FAIL); - DOCTEST_REQUIRE(resp.last_log_idx == 3); - } -} - -DOCTEST_TEST_CASE( - "Retired-committed node refuses forced leadership" * - doctest::test_suite("retirement")) -{ - PrimaryAndBackup n; - - aft::Configuration::Nodes peer_only; - peer_only[n.id1] = {}; - auto retire_hooks = std::make_shared(); - retire_hooks->push_back( - std::make_unique(peer_only, 1)); - auto entry = std::make_shared>(3, 1); - DOCTEST_REQUIRE(n.r0.replicate( - ccf::kv::BatchVector{{1, entry, false, retire_hooks}}, n.r0.get_view())); - n.replicate(2, 2, true); - - // Peer acknowledges the retirement and following signature so retirement - // commits on node 0 (RetirementPhase::Completed). - n.r0.periodic(request_timeout); - require_ack( - n.backup_receives(n.with_payload(n.take_append_entries_header())), 2); - n.primary_receives(aft::AppendEntriesResponse{ - .term = n.r0.get_view(), - .last_log_idx = 2, - .success = aft::AppendEntriesResponseType::OK}); - DOCTEST_REQUIRE(n.r0.get_committed_seqno() == 2); - DOCTEST_REQUIRE( - n.r0.get_details().retirement_phase == ccf::kv::RetirementPhase::Completed); - - n.r0.set_retired_committed(3, {n.id0}); - DOCTEST_REQUIRE(n.r0.is_retired_committed()); - DOCTEST_REQUIRE_FALSE(n.r0.is_primary()); - DOCTEST_REQUIRE_FALSE(n.r0.primary().has_value()); - - // Forcing leadership on a retired-committed node must not re-elect it. - n.r0.force_become_primary(); - DOCTEST_REQUIRE_FALSE(n.r0.is_primary()); - DOCTEST_REQUIRE_FALSE(n.r0.primary().has_value()); - DOCTEST_REQUIRE( - n.r0.get_details().leadership_state == ccf::kv::LeadershipState::None); -} - -DOCTEST_TEST_CASE( - "Backup rolls back and NACKs when a consensus hook throws a " - "non-std::exception" * - doctest::test_suite("multiple")) -{ - struct UnknownHookError - {}; - - class ThrowingHook : public ccf::kv::ConsensusHook - { - public: - void call(ccf::kv::ConfigurableConsensus*) override - { - throw UnknownHookError{}; - } - }; - - class ThrowingHookStore : public Store - { - public: - using Store::Store; - - aft::Index throw_at_idx = 0; - - std::unique_ptr deserialize( - const std::vector& data, - bool public_only = false, - const std::optional& expected_txid = std::nullopt) override - { - ccf::kv::ConsensusHookPtrs entry_hooks; - if (expected_txid.has_value() && expected_txid->seqno == throw_at_idx) - { - entry_hooks.push_back(std::make_unique()); - } - return std::make_unique( - data, expected_txid, std::move(entry_hooks)); - } - }; - - auto kv1 = - std::make_shared(ccf::kv::test::FirstBackupNodeId); - PrimaryAndBackup n({}, {.kv = kv1}); - - n.replicate(1, 1, true); - n.r0.periodic(request_timeout); - const auto ack = - n.backup_receives(n.with_payload(n.take_append_entries_header())); - require_ack(ack, 1); - n.primary_receives(ack.value()); - DOCTEST_REQUIRE(n.r1.get_last_idx() == 1); - - kv1->throw_at_idx = 3; - n.replicate(2, 3, false); - n.r0.periodic(request_timeout); - const auto nack = - n.backup_receives(n.with_payload(n.take_append_entries_header())); - require_nack(nack, 1); - DOCTEST_REQUIRE(n.r1.get_last_idx() == 1); - DOCTEST_REQUIRE(n.r1.ledger->ledger.size() == 1); -} - -DOCTEST_TEST_CASE( - "Follower retains conflicting suffix on a second conflict in the same term" * - doctest::test_suite("multiple")) -{ - PrimaryAndBackup n; - - // Commit entry 1.1 and replicate uncommitted entry 1.2 to the backup. - n.replicate(1, 1, true); - n.r0.periodic(request_timeout); - const auto ack1 = - n.backup_receives(n.with_payload(n.take_append_entries_header())); - require_ack(ack1, 1); - n.primary_receives(ack1.value()); - - n.replicate(2, 2, false); - n.r0.periodic(request_timeout); - const auto ack2 = - n.backup_receives(n.with_payload(n.take_append_entries_header())); - require_ack(ack2, 2); - DOCTEST_REQUIRE(n.r1.get_view(2) == 1); - DOCTEST_REQUIRE(n.r1.get_committed_seqno() == 1); - - // Helper to build a single-entry AppendEntries payload matching - // LoggingStubStore's wire format. - const auto make_ae_payload = - [](bool committable, aft::Term term, aft::Index idx) { - const std::vector body = {1, 2, 3}; - std::vector buf(sizeof(size_t) + aft::ADDITIONAL_METADATA_SIZE); - uint8_t* ptr = buf.data(); - size_t rem = buf.size(); - serialized::write(ptr, rem, aft::ADDITIONAL_METADATA_SIZE + body.size()); - serialized::write(ptr, rem, committable); - serialized::write(ptr, rem, term); - serialized::write(ptr, rem, idx); - buf.insert(buf.end(), body.begin(), body.end()); - return buf; - }; - - // First conflict in view 2: as a new follower in view 2, node 1 rolls back - // entry 1.2 and accepts 2.2 (clearing is_new_follower). - aft::AppendEntries term2_ae{}; - term2_ae.idx = 2; - term2_ae.prev_idx = 1; - term2_ae.term = 2; - term2_ae.prev_term = 1; - term2_ae.leader_commit_idx = 1; - term2_ae.term_of_idx = 2; - const auto term2_header = as_bytes(term2_ae); - const auto term2_payload = make_ae_payload(false, 2, 2); - n.r1.recv_message(n.id0, term2_header, term2_payload); - auto resp = n.c1->pop_first(aft::append_entries_response, n.id0); - DOCTEST_REQUIRE(resp.has_value()); - require_ack(read_msg(*resp), 2); - DOCTEST_REQUIRE(n.r1.get_view() == 2); - DOCTEST_REQUIRE(n.r1.get_view(2) == 2); - DOCTEST_REQUIRE(n.r1.primary() == n.id0); - - // Second conflicting AppendEntries in the same term (simulating an - // equivocating sender in view 2 claiming term_of_idx = 1 at index 2): - // is_new_follower is now false, so node 1 retains 2.2 without rolling back - // or sending a response. - const auto equivocator = ccf::kv::test::SecondBackupNodeId; - aft::AppendEntries conflicting_ae{}; - conflicting_ae.idx = 2; - conflicting_ae.prev_idx = 1; - conflicting_ae.term = 2; - conflicting_ae.prev_term = 1; - conflicting_ae.leader_commit_idx = 1; - conflicting_ae.term_of_idx = 1; - const auto conflicting_header = as_bytes(conflicting_ae); - const auto conflicting_payload = make_ae_payload(false, 1, 2); - n.r1.recv_message(equivocator, conflicting_header, conflicting_payload); - DOCTEST_REQUIRE(n.c1->messages.empty()); - DOCTEST_REQUIRE(n.r1.get_last_idx() == 2); - DOCTEST_REQUIRE(n.r1.get_view(2) == 2); -} - int main(int argc, char** argv) { doctest::Context context; diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index 00f4ff2ab4e0..7e1d67167cee 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -8,7 +8,6 @@ #include "kv/null_encryptor.h" #include "kv/store.h" -#include "service/tables/signatures.h" #include "test_common.h" #include @@ -24,29 +23,24 @@ namespace straddling { using TestMap = ccf::kv::Map; - class SignaturePendingTx : public ccf::kv::PendingTx + class BaselinePendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; - uint8_t marker; + TestMap& table; public: - SignaturePendingTx( - ccf::TxID txid_, ccf::kv::Store& store_, uint8_t marker_) : + BaselinePendingTx( + ccf::TxID txid_, ccf::kv::Store& store_, TestMap& table_) : txid(txid_), store(store_), - marker(marker_) + table(table_) {} ccf::kv::PendingTxInfo call() override { auto tx = store.create_reserved_tx(txid); - tx.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); - tx.wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, {marker}); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({marker}); + tx.rw(table)->put(0, 1); return tx.commit_reserved(); } }; @@ -198,18 +192,6 @@ namespace straddling return tx.ro(table)->get(key); } - static std::optional read_signature_seqno(ccf::kv::Store& store) - { - auto tx = store.create_read_only_tx_at_replicated_state(); - const auto signature = - tx.ro(ccf::Tables::SIGNATURES)->get(); - if (!signature.has_value()) - { - return std::nullopt; - } - return signature->seqno; - } - struct Fixture { const ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; @@ -230,20 +212,15 @@ namespace straddling { start_consensus(); - { - auto tx = store->create_tx(); - tx.rw(table)->put(0, 1); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } const auto baseline_txid = store->next_txid().value(); REQUIRE( store->commit( baseline_txid, - std::make_unique(baseline_txid, *store, 1), + std::make_unique(baseline_txid, *store, table), true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(store->current_txid() == ccf::TxID(initial_view, 2)); - REQUIRE(cft->get_committed_seqno() == 2); - REQUIRE(cft->ledger->ledger.size() == 2); + REQUIRE(store->current_txid() == ccf::TxID(initial_view, 1)); + REQUIRE(cft->get_committed_seqno() == 1); + REQUIRE(cft->ledger->ledger.size() == 1); } // Creates CFT and makes this node primary, with nothing committed. @@ -273,7 +250,7 @@ namespace straddling } // Lose leadership, then win a later election. become_leader() rolls the - // Store back to the last committable index (2) under the new view. + // Store back to the last committable index (1) under the new view. ccf::View reelect() { step_down(); diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index 9de314bea265..e610bd23fb23 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -20,7 +20,7 @@ // // - Tx A is published locally by Store::commit(), which then releases the // role lock before calling CFT. -// - An election rolls the Store and the ledger history back to seqno 2. +// - An election rolls the Store and the ledger history back to seqno 1. // - CFT rejects A, which must not reappear in the history. #include "node/history.h" @@ -59,12 +59,14 @@ namespace return txid.seqno; } - // Applies a signature at the next TxID, without committing it to the - // Store. - std::pair prepare(uint8_t marker) + // Applies a write at the next TxID, without committing it to the Store. + std::pair prepare( + size_t key, size_t value) { const auto txid = store->next_txid().value(); - return {txid, SignaturePendingTx(txid, *store, marker).call()}; + auto tx = store->create_reserved_tx(txid); + tx.rw(table)->put(key, value); + return {txid, tx.commit_reserved()}; } }; } @@ -76,11 +78,11 @@ TEST_CASE( HistoryFixture fixture; const auto baseline_root = fixture.root(); - REQUIRE(fixture.history_seqno() == 2); + REQUIRE(fixture.history_seqno() == 1); - INFO("Apply and serialise A at seqno 3 in the initial view"); - auto [stale_txid, stale_info] = fixture.prepare(2); - REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); + INFO("Apply and serialise A at seqno 2 in the initial view"); + auto [stale_txid, stale_info] = fixture.prepare(1, 2); + REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); INFO( @@ -96,11 +98,11 @@ TEST_CASE( false); }); REQUIRE(replicate_pause.wait_until_paused()); - REQUIRE(fixture.history_seqno() == 3); + REQUIRE(fixture.history_seqno() == 2); - INFO("Lose leadership and win a later election, rolling back to seqno 2"); + INFO("Lose leadership and win a later election, rolling back to seqno 1"); fixture.reelect(); - REQUIRE(fixture.history_seqno() == 2); + REQUIRE(fixture.history_seqno() == 1); REQUIRE(fixture.root() == baseline_root); INFO("Resume A: cft rejects it, and history, KV and ledger agree"); @@ -108,11 +110,11 @@ TEST_CASE( stale_worker.join(); REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); - CHECK(fixture.history_seqno() == 2); + CHECK(fixture.history_seqno() == 1); CHECK(fixture.root() == baseline_root); - CHECK(fixture.store->current_txid().seqno == 2); - CHECK(fixture.cft->get_last_idx() == 2); - CHECK(fixture.cft->ledger->ledger.size() == 2); + CHECK(fixture.store->current_txid().seqno == 1); + CHECK(fixture.cft->get_last_idx() == 1); + CHECK(fixture.cft->ledger->ledger.size() == 1); } TEST_CASE( @@ -124,7 +126,7 @@ TEST_CASE( const auto baseline_root = fixture.root(); INFO("A enters Store::commit and is descheduled while publishing"); - auto [txid, info] = fixture.prepare(2); + auto [txid, info] = fixture.prepare(1, 2); CommitPause publish_pause; std::optional result; Worker writer({&publish_pause}, [&]() { @@ -161,12 +163,12 @@ TEST_CASE( REQUIRE(stepped_down.load()); REQUIRE(result.has_value()); CHECK(result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); - CHECK(fixture.history_seqno() == 2); + CHECK(fixture.history_seqno() == 1); CHECK(fixture.root() == baseline_root); - CHECK(fixture.store->current_txid().seqno == 2); - CHECK(read_signature_seqno(*fixture.store) == 2); - CHECK(fixture.cft->get_last_idx() == 2); - CHECK(fixture.cft->ledger->ledger.size() == 2); + CHECK(fixture.store->current_txid().seqno == 1); + CHECK_FALSE(read_value(*fixture.store, fixture.table, 1).has_value()); + CHECK(fixture.cft->get_last_idx() == 1); + CHECK(fixture.cft->ledger->ledger.size() == 1); } TEST_CASE( @@ -197,11 +199,14 @@ TEST_CASE( CHECK(fixture.root() == baseline_root); INFO("A transaction reserved before stepping down cannot write"); - CHECK( - SignaturePendingTx(reserved_txid.value(), *fixture.store, 2) - .call() - .success == ccf::kv::CommitResult::FAIL_NO_REPLICATE); - CHECK(read_signature_seqno(*fixture.store) == 2); + { + auto reserved_tx = fixture.store->create_reserved_tx(reserved_txid.value()); + reserved_tx.rw(fixture.table)->put(1, 2); + CHECK( + reserved_tx.commit_reserved().success == + ccf::kv::CommitResult::FAIL_NO_REPLICATE); + } + CHECK_FALSE(read_value(*fixture.store, fixture.table, 1).has_value()); INFO("Writes are refused, whether started before or after stepping down"); CHECK(stale_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); @@ -254,8 +259,8 @@ TEST_CASE( // nodes, so start from its last phase before RetiredCommitted. fixture.state->membership_state = ccf::kv::MembershipState::Retired; fixture.state->retirement_phase = ccf::kv::RetirementPhase::Completed; - fixture.state->retirement_idx = 2; - fixture.state->retirement_committable_idx = 2; + fixture.state->retirement_idx = 1; + fixture.state->retirement_committable_idx = 1; INFO("Committing the retirement completes it, without deadlocking"); auto tx = fixture.store->create_tx(); @@ -265,9 +270,9 @@ TEST_CASE( REQUIRE( fixture.store->commit( txid, - std::make_unique(txid, *fixture.store, 2), + std::make_unique(txid, *fixture.store, fixture.table), true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(fixture.cft->get_committed_seqno() == 4); + REQUIRE(fixture.cft->get_committed_seqno() == 3); REQUIRE(fixture.cft->is_retired_committed()); const auto baseline_root = fixture.root(); diff --git a/src/consensus/aft/test/view_straddling_rollback.cpp b/src/consensus/aft/test/view_straddling_rollback.cpp index b5da38874f64..bdfb2e98ff82 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -15,23 +15,21 @@ // Interleaving, from review of PR #8209 (cjen1-msft, // src/consensus/aft/cft.h): // -// - Tx A is applied locally in view V and given TxID V.3. It enters +// - Tx A is applied locally in view V and given TxID V.2. It enters // Store::commit(), is published locally, and is descheduled before it // reaches CFT. // - An election happens. Stepping down rolls the Store back past A, to seqno -// 2, and the node then wins in view W > V. -// - Tx B is applied locally in view W and given TxID W.3. It has not yet +// 1, and the node then wins in view W > V. +// - Tx B is applied locally in view W and given TxID W.2. It has not yet // entered Store::commit(). // - A continues. CFT rejects it. If that rejection rolls the Store -// back to CFT's last log index (2), it discards B's local application as +// back to CFT's last log index (1), it discards B's local application as // well. // - B enters Store::commit(), passes the view check (W == W), and is // replicated. It is in the ledger, but no longer in the KV. #include "view_straddling_common.h" -#include - using namespace straddling; namespace @@ -39,7 +37,7 @@ namespace std::string describe(Fixture& fixture) { const auto value = read_value(*fixture.store, fixture.table, 2); - return std::format( + return fmt::format( "store txid {}, key 2 -> {}, cft last_idx {}, ledger entries " "{}", fixture.store->current_txid().to_str(), @@ -57,12 +55,16 @@ TEST_CASE( Fixture fixture; fixture.start(); - INFO("Apply and serialise A at seqno 3 in the initial view"); + INFO("Apply and serialise A at seqno 2 in the initial view"); const auto stale_txid = fixture.store->next_txid().value(); - REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); - auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); + REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); + auto stale_info = [&]() { + auto tx = fixture.store->create_reserved_tx(stale_txid); + tx.rw(fixture.table)->put(1, 2); + return tx.commit_reserved(); + }(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE(read_signature_seqno(*fixture.store) == 2); + REQUIRE(read_value(*fixture.store, fixture.table, 1) == 2); INFO( "A enters Store::commit, is published locally, then is descheduled " @@ -78,15 +80,14 @@ TEST_CASE( }); REQUIRE(stale_pause.wait_until_paused()); - INFO("Lose leadership and win a later election, rolling back to seqno 2"); + INFO("Lose leadership and win a later election, rolling back to seqno 1"); const auto reelection_view = fixture.reelect(); - REQUIRE(fixture.store->current_txid() == ccf::TxID(fixture.initial_view, 2)); - REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); - REQUIRE(read_signature_seqno(*fixture.store) == 2); - REQUIRE(fixture.cft->get_last_idx() == 2); + REQUIRE(fixture.store->current_txid() == ccf::TxID(fixture.initial_view, 1)); + REQUIRE_FALSE(read_value(*fixture.store, fixture.table, 1).has_value()); + REQUIRE(fixture.cft->get_last_idx() == 1); INFO( - "B is applied at seqno 3 in the new view, then pauses before " + "B is applied at seqno 2 in the new view, then pauses before " "Store::commit"); auto current_tx = fixture.store->create_tx(); current_tx.rw(fixture.table)->put(2, 3); @@ -98,8 +99,8 @@ TEST_CASE( [¤t_pause](const auto&, const auto&) { current_pause.pause(); }); }); REQUIRE(current_pause.wait_until_paused()); - REQUIRE(current_tx.get_txid() == ccf::TxID(reelection_view, 3)); - REQUIRE(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); + REQUIRE(current_tx.get_txid() == ccf::TxID(reelection_view, 2)); + REQUIRE(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); REQUIRE(read_value(*fixture.store, fixture.table, 2) == 3); INFO( @@ -110,9 +111,9 @@ TEST_CASE( REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); MESSAGE("After A is rejected: " << describe(fixture)); - CHECK(fixture.cft->get_last_idx() == 2); - CHECK(fixture.cft->ledger->ledger.size() == 2); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); + CHECK(fixture.cft->get_last_idx() == 1); + CHECK(fixture.cft->ledger->ledger.size() == 1); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); INFO("Resume B: whatever consensus decides, KV and ledger must agree"); @@ -121,11 +122,10 @@ TEST_CASE( REQUIRE(current_result.has_value()); CHECK(current_result.value() == ccf::kv::CommitResult::SUCCESS); MESSAGE("After B is replicated: " << describe(fixture)); - CHECK(fixture.cft->get_last_idx() == 3); - CHECK(fixture.cft->ledger->ledger.size() == 3); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); + CHECK(fixture.cft->get_last_idx() == 2); + CHECK(fixture.cft->ledger->ledger.size() == 2); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 2)); CHECK(read_value(*fixture.store, fixture.table, 2) == 3); - CHECK(read_signature_seqno(*fixture.store) == 2); INFO("The next transaction gets a fresh seqno and replicates normally"); auto next_tx = fixture.store->create_tx(); @@ -136,9 +136,9 @@ TEST_CASE( "After next tx " << (next_txid.has_value() ? next_txid->to_str() : std::string("none")) << ": " << describe(fixture)); - CHECK(next_txid == ccf::TxID(reelection_view, 4)); - CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 4)); + CHECK(next_txid == ccf::TxID(reelection_view, 3)); + CHECK(fixture.store->current_txid() == ccf::TxID(reelection_view, 3)); CHECK(read_value(*fixture.store, fixture.table, 3) == 4); - CHECK(fixture.cft->get_last_idx() == 4); - CHECK(fixture.cft->ledger->ledger.size() == 4); + CHECK(fixture.cft->get_last_idx() == 3); + CHECK(fixture.cft->ledger->ledger.size() == 3); } diff --git a/src/js/test/js.cpp b/src/js/test/js.cpp index 28741e8d88c5..0b1c4d4b43e0 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -2,7 +2,6 @@ // Licensed under the Apache 2.0 License. #include "ccf/crypto/ec_key_pair.h" #include "ccf/ds/x509_time_fmt.h" -#include "ccf/endpoints/common_auth_policies.h" #include "ccf/js/common_context.h" #include "ccf/js/core/wrapped_value.h" #include "ccf/js/extensions/ccf/consensus.h" @@ -27,9 +26,6 @@ #include "node/rpc/http_rpc_context.h" #include "node/rpc/test/node_stub.h" #include "node/tx_receipt_impl.h" -#include "service/tables/signatures.h" - -#include #define DOCTEST_CONFIG_IMPLEMENT #include @@ -39,26 +35,6 @@ #include #include #include -#include - -namespace registry_compatibility -{ - class BaseRegistry : public ccf::js::BaseDynamicJSEndpointRegistry - { - public: - BaseRegistry(ccf::AbstractNodeContext& context) : - BaseDynamicJSEndpointRegistry(context) - {} - }; - - class AuditedRegistry : public ccf::js::DynamicJSEndpointRegistry - { - public: - AuditedRegistry(ccf::AbstractNodeContext& context) : - DynamicJSEndpointRegistry(context) - {} - }; -} using namespace ccf::js; @@ -534,44 +510,6 @@ TEST_CASE("Check KV Map access") } } - for (const auto access : - {TxAccess::APP_RO, TxAccess::APP_RW, TxAccess::GOV_RO, TxAccess::GOV_RW}) - { - CAPTURE(access); - for (const auto* table : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - CAPTURE(table); - CHECK(check_kv_map_access(access, table) == KVAccessPermissions::ILLEGAL); - CHECK( - check_kv_map_access( - access, table, extensions::kvhelpers::KVSource::CurrentTx) == - KVAccessPermissions::ILLEGAL); - CHECK( - check_kv_map_access( - access, table, extensions::kvhelpers::KVSource::Historical) == - KVAccessPermissions::READ_ONLY); - } - - for (const auto* table : - {"public:ccf.internal.table", - "public:ccf.internal.signatures_other", - "public:ccf.internal.signatures.nested", - "public:ccf.internal.cose_signatures_other", - "public:ccf.internal.tree_other"}) - { - CAPTURE(table); - CHECK( - check_kv_map_access(access, table) == KVAccessPermissions::READ_ONLY); - CHECK( - check_kv_map_access( - access, table, extensions::kvhelpers::KVSource::Historical) == - KVAccessPermissions::READ_ONLY); - } - } - { INFO("Every permission is described accurately"); REQUIRE( @@ -601,7 +539,7 @@ TEST_CASE("Check KV Map access") REQUIRE_THROWS_WITH_AS( explain_kv_map_access( static_cast(permission_value), TxAccess::APP_RW), - std::format("Unexpected KV access permission: {}", permission_value), + fmt::format("Unexpected KV access permission: {}", permission_value), std::logic_error); } } @@ -612,7 +550,7 @@ bool str_contains(const std::string& s, std::string_view sv) const auto b = s.contains(sv); if (!b) { - std::cout << std::format("Didn't find\n {}\nin\n {}\n", sv, s); + fmt::print("Didn't find\n {}\nin\n {}\n", sv, s); } return b; } @@ -638,16 +576,12 @@ using KVMap = ccf::kv::untyped::Map; // Returns an error message if the JS script throws. std::optional run_kv_script( - ccf::kv::Tx& tx, - TxAccess access, - const std::string& body, - ccf::js::NamespaceRestriction namespace_restriction = {}) + ccf::kv::Tx& tx, TxAccess access, const std::string& body) { ccf::js::core::Context ctx(access); - ctx.add_extension(std::make_shared( - &tx, std::move(namespace_restriction))); + ctx.add_extension(std::make_shared(&tx)); - const auto module = std::format("export function run() {{\n{}\n}}", body); + const auto module = fmt::format("export function run() {{\n{}\n}}", body); auto func = ctx.get_exported_function(module, "run", "/test/kv_script"); const auto result = ctx.call_with_rt_options( @@ -700,110 +634,6 @@ TEST_CASE("Interpreter cache without a clearing override") std::logic_error); } -TEST_CASE_TEMPLATE( - "JS registry instantiations and legacy subclass constructors link", - Registry, - registry_compatibility::BaseRegistry, - registry_compatibility::AuditedRegistry, - BaseDynamicJSEndpointRegistryT, - DynamicJSEndpointRegistryT, - BaseDynamicJSEndpointRegistryT, - DynamicJSEndpointRegistryT) -{ - ccf::AbstractNodeContext context; - context.install_subsystem(std::make_shared()); - context.install_subsystem(std::make_shared(1)); - if constexpr (std::is_base_of_v) - { - [[maybe_unused]] Registry registry(context); - } - else - { - [[maybe_unused]] Registry registry( - context, default_js_registry_kv_prefix, "app"); - } -} - -TEST_CASE("JS registry without built-ins dispatches JS and native endpoints") -{ - ccf::AbstractNodeContext context; - context.install_subsystem(std::make_shared()); - context.install_subsystem(std::make_shared(1)); - const std::string prefix = "custom"; - DynamicJSEndpointRegistryT registry( - context, "public:test", prefix); - registry.init_handlers(); - registry - .make_endpoint( - "/native", - HTTP_GET, - [](auto& ctx) { ctx.rpc_ctx->set_response_status(HTTP_STATUS_ACCEPTED); }, - ccf::no_auth_required) - .install(); - - ccf::kv::Store store; - Bundle bundle; - auto& properties = bundle.metadata.endpoints["/js/{id}"]["GET"]; - properties.js_module = "/handler.js"; - properties.js_function = "handler"; - properties.mode = ccf::endpoints::Mode::ReadOnly; - properties.authn_policies = {"no_auth"}; - bundle.modules.push_back( - {"/handler.js", - "export function handler(request) { return {body: request.params.id}; }"}); - auto tx = store.create_tx(); - REQUIRE( - registry.install_custom_endpoints_v1(tx, bundle) == ccf::ApiResult::OK); - - auto make_rpc_context = [](const std::string& path) { - return std::make_shared( - std::make_shared(0, std::vector{}), - HTTP_GET, - path, - ccf::http::HeaderMap{}, - std::vector{}); - }; - for (const auto* path : {"/tx", "/commit", "/receipt", "/api"}) - { - INFO(path); - auto rpc_ctx = make_rpc_context(path); - CHECK(registry.find_endpoint(tx, *rpc_ctx) == nullptr); - CHECK(registry.get_allowed_verbs(tx, *rpc_ctx).empty()); - } - - for (const auto* path : {"/native", "/js/42"}) - { - auto rpc_ctx = make_rpc_context(path); - auto endpoint = registry.find_endpoint(tx, *rpc_ctx); - REQUIRE(endpoint != nullptr); - CHECK( - endpoint->full_uri_path == - (std::string_view(path) == "/native" ? "/custom/native" : - "/custom/js/{id}")); - CHECK(registry.get_allowed_verbs(tx, *rpc_ctx).contains(HTTP_GET)); - ccf::endpoints::EndpointContext endpoint_ctx(rpc_ctx, tx); - registry.execute_endpoint(endpoint, endpoint_ctx); - if (std::string_view(path) == "/native") - { - CHECK(rpc_ctx->get_response_status() == HTTP_STATUS_ACCEPTED); - } - else - { - CHECK(rpc_ctx->get_response_status() == HTTP_STATUS_OK); - CHECK(rpc_ctx->get_response_body() == std::vector{'4', '2'}); - } - } - - nlohmann::json document; - REQUIRE( - registry.generate_openapi_document_v1( - tx, "Test", "Registry base selection", "1.0", document) == - ccf::ApiResult::OK); - CHECK(document["paths"].contains("/custom/native")); - CHECK(document["paths"].contains("/custom/js/{id}")); - CHECK_FALSE(document["paths"].contains("/custom/tx")); -} - TEST_CASE("JS registry namespace restrictions") { class ReassignedRegistry : public DynamicJSEndpointRegistry @@ -951,6 +781,7 @@ export function write(request) { INFO(table); auto rpc_ctx = std::make_shared( std::make_shared(0, std::vector{}), + ccf::HttpVersion::HTTP1, HTTP_POST, "/write", ccf::http::HeaderMap{}, @@ -991,7 +822,7 @@ export function write(request) { "my_table"}) { check_write( - std::format("public:custom_endpoints.{}", suffix), + fmt::format("public:custom_endpoints.{}", suffix), can_write_default_namespace); } check_write( @@ -1029,7 +860,7 @@ TEST_CASE("KV handle permissions") // Every script below operates on a single key, and refers to tables by these // names rather than repeating the string literals - const auto js_prelude = std::format( + const auto js_prelude = fmt::format( R"JS( const key = new Uint8Array([107]).buffer; const value = new Uint8Array([118]).buffer; @@ -1302,7 +1133,7 @@ std::optional call_validate_constitution( const auto path = "/path/to/constitution"; - auto module = std::format( + auto module = fmt::format( "export function call_validate () {{\n" " {}\n" " let constitution = {};\n" @@ -1711,7 +1542,7 @@ export function call_validate_catching () { ccf::js::core::Context ctx(TxAccess::GOV_RO); ctx.add_extension(std::make_shared()); const auto module = - std::format( + fmt::format( "export function call_validate () {{\n" " let constitution = {};\n" " return ccf.gov.validateConstitution(constitution);\n" @@ -1975,7 +1806,7 @@ TEST_CASE("QuickJS commits the maximum length of growable SharedArrayBuffers") JSMemoryUsage before; JS_ComputeMemoryUsage(rt, &before); - const auto script = std::format( + const auto script = fmt::format( R"( globalThis.shared = new SharedArrayBuffer(8, {{maxByteLength: {0}}}); shared.grow({0}); @@ -1998,7 +1829,7 @@ view[{0} - 1] + view[{0} >> 1]; JS_SetMemoryLimit(rt, after.malloc_size + max_length / 2); const auto over_limit = - std::format("new SharedArrayBuffer(8, {{maxByteLength: {}}});", max_length); + fmt::format("new SharedArrayBuffer(8, {{maxByteLength: {}}});", max_length); result = JS_Eval( ctx, over_limit.c_str(), @@ -2242,7 +2073,7 @@ TEST_CASE("QuickJS does not resume compiling after exceeding the heap limit") // miss the default value of 'b', compile 'f' without a separate parameter // scope, and so make f() return "inner". constexpr size_t key_size = 64 * 1024; - const std::string script = std::format( + const std::string script = fmt::format( "var x = 'outer';" "function f({{\"{}\": a}}, b = () => x) {{ var x = 'inner'; return b(); }}" "f({{}});", @@ -2394,7 +2225,7 @@ TEST_CASE("QuickJS frees a module which could not be read from bytecode") std::string source; for (size_t i = 0; i < entries; ++i) { - source += std::format( + source += fmt::format( "import {{a as a{0}}} from 'dep{0}.js'; export const b{0} = a{0};\n", i); } const auto bytecode = compile_module_to_bytecode(source, "tables.js"); @@ -3105,8 +2936,6 @@ namespace public: size_t tx_creations = 0; - CountingStore() : ccf::kv::Store(true) {} - std::unique_ptr create_read_only_tx_ptr() override { ++tx_creations; @@ -3124,245 +2953,6 @@ namespace ccf::NodeId("test-node"), std::nullopt); } - - std::vector make_test_signature_transaction(ccf::kv::Store& store) - { - const auto txid = store.next_txid().value(); - auto tx = store.create_reserved_tx(txid); - tx.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature(ccf::NodeId("test-node"), txid.seqno)); - tx.wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, {1, 2, 3}); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({4, 5, 6}); - auto info = tx.commit_reserved(); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - return std::move(info.data); - } - - constexpr auto signature_table_test_prelude = R"JS( -const signatureTables = [ - "public:ccf.internal.signatures", - "public:ccf.internal.cose_signatures", - "public:ccf.internal.tree" -]; -const key = new ArrayBuffer(8); -const value = new Uint8Array([118]).buffer; -function expectTypeError(operation, ...fragments) { - try { - operation(); - } catch (e) { - if (!(e instanceof TypeError) || - fragments.some(fragment => !e.message.includes(fragment))) { - throw new Error(`Unexpected error: ${e}`); - } - return; - } - throw new Error(`Operation was permitted: ${fragments.join(", ")}`); -} -function readOperations(donor) { - return [ - ["get", target => donor.get.call(target, key)], - ["has", target => donor.has.call(target, key)], - ["getVersionOfPreviousWrite", - target => donor.getVersionOfPreviousWrite.call(target, key)], - ["forEach", target => donor.forEach.call(target, () => {})], - ["size", target => - Object.getOwnPropertyDescriptor(donor, "size").get.call(target)] - ]; -} -function writeOperations(donor) { - return [ - ["set", target => donor.set.call(target, key, value)], - ["delete", target => donor.delete.call(target, key)], - ["clear", target => donor.clear.call(target)] - ]; -} -)JS"; -} - -TEST_CASE("Current JS signature table handles deny every operation") -{ - NamespaceRestriction namespace_restriction; - SUBCASE("Default namespace policy") {} - SUBCASE("A namespace callback cannot grant signature table access") - { - namespace_restriction = [](const std::string&, std::string&) { - return KVAccessPermissions::READ_WRITE; - }; - } - - for (const bool populated : {false, true}) - { - CAPTURE(populated); - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - if (populated) - { - make_test_signature_transaction(store); - } - - for (const auto access : - {TxAccess::APP_RO, - TxAccess::APP_RW, - TxAccess::GOV_RO, - TxAccess::GOV_RW}) - { - CAPTURE(access); - auto tx = store.create_tx(); - const auto body = std::string(signature_table_test_prelude) + R"JS( -for (const table of signatureTables) { - const handle = ccf.kv[table]; - for (const [, operation] of [ - ...readOperations(handle), ...writeOperations(handle) - ]) { - expectTypeError(() => operation(handle), table, "inaccessible"); - } -} -for (const table of [ - "public:ccf.internal.table", - "public:ccf.internal.signatures_other", - "public:ccf.internal.cose_signatures.nested", - "public:ccf.internal.tree_other" -]) { - const handle = ccf.kv[table]; - for (const [, operation] of readOperations(handle)) { - operation(handle); - } - for (const [, operation] of writeOperations(handle)) { - expectTypeError(() => operation(handle), table, "read-only"); - } -} -)JS"; - const auto error = run_kv_script(tx, access, body, namespace_restriction); - CHECK_MESSAGE(!error.has_value(), error.value_or("")); - for (const auto* table : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - CHECK( - (store.get_map(store.current_version(), table) != nullptr) == - populated); - } - } - } -} - -TEST_CASE("Historical JS signature table handles retain read-only access") -{ - bool restricted = false; - SUBCASE("Permitted historical reads") {} - SUBCASE("Namespace restrictions can deny historical signature reads") - { - restricted = true; - } - - for (const bool populated : {false, true}) - { - CAPTURE(populated); - ccf::kv::Store source; - source.set_encryptor(std::make_shared()); - auto historical_store = std::make_shared(true); - historical_store->set_encryptor( - std::make_shared()); - if (populated) - { - const auto data = make_test_signature_transaction(source); - REQUIRE( - historical_store->deserialize(data)->apply() == - ccf::kv::ApplyResult::PASS_SIGNATURE); - } - - auto state = std::make_shared( - historical_store, make_test_receipt(), ccf::TxID{1, 1}); - for (const auto access : - {TxAccess::APP_RO, - TxAccess::APP_RW, - TxAccess::GOV_RO, - TxAccess::GOV_RW}) - { - CAPTURE(access); - ccf::js::core::Context ctx(access); - auto tx = source.create_tx(); - ctx.add_extension(std::make_shared( - &tx, [restricted](const std::string& name, std::string& explanation) { - if (restricted && ccf::kv::is_signature_table(name)) - { - explanation = "Restricted test signature table"; - return KVAccessPermissions::ILLEGAL; - } - return KVAccessPermissions::READ_WRITE; - })); - auto historical = - std::make_shared(nullptr); - ctx.add_extension(historical); - auto js_state = historical->create_historical_state_object(ctx, state); - REQUIRE_FALSE(js_state.is_exception()); - REQUIRE(ctx.get_global_obj().set("testState", std::move(js_state)) == 1); - - const auto script = std::format( - "const populated = {};\nconst restricted = {};\n", - populated, - restricted) + - signature_table_test_prelude + R"JS( -export function run() { - for (const table of signatureTables) { - const handle = testState.kv[table]; - if (restricted) { - for (const [name, operation] of [ - ...readOperations(handle), ...writeOperations(handle) - ]) { - expectTypeError( - () => operation(handle), table, "Restricted test signature table"); - } - continue; - } - if (handle.size !== (populated ? 1 : 0)) { - throw new Error(`Unexpected size for ${table}`); - } - if (handle.has(key) !== populated || - (handle.get(key) !== undefined) !== populated || - (handle.getVersionOfPreviousWrite(key) !== undefined) !== populated) { - throw new Error(`Unexpected singleton lookup for ${table}`); - } - let seen = 0; - handle.forEach((value, entryKey) => { - const storedValue = handle.get(entryKey); - if (!handle.has(entryKey) || value.byteLength === 0 || - storedValue === undefined || - handle.getVersionOfPreviousWrite(entryKey) !== 1) { - throw new Error(`Unreadable historical entry for ${table}`); - } - const bytes = new Uint8Array(value); - const storedBytes = new Uint8Array(storedValue); - if (bytes.length !== storedBytes.length || - !bytes.every((byte, i) => byte === storedBytes[i])) { - throw new Error(`Mismatched historical value for ${table}`); - } - seen++; - }); - if (seen !== handle.size) { - throw new Error(`Unexpected iteration count for ${table}`); - } - for (const [, operation] of writeOperations(handle)) { - expectTypeError(() => operation(handle), table, "read-only"); - } - } -} -)JS"; - auto func = ctx.get_exported_function( - script, "run", "/test/historical-signature-tables.js"); - const auto result = ctx.call_with_rt_options( - func, {}, std::nullopt, ccf::js::core::RuntimeLimitsPolicy::NONE); - if (result.is_exception()) - { - const auto [reason, trace] = ctx.error_message(); - FAIL_CHECK(reason); - } - CHECK(JS_HasException(ctx) == 0); - } - } } TEST_CASE("Historical state") @@ -3585,6 +3175,7 @@ export function run(request) { auto rpc_ctx = std::make_shared( std::make_shared( ccf::InvalidSessionId, std::vector{}), + ccf::HttpVersion::HTTP1, HTTP_GET, "/response?" + query, ccf::http::HeaderMap{}, @@ -3791,7 +3382,7 @@ namespace ccf::js::CommonContext ctx(TxAccess::APP_RW); JS_UpdateStackTop(ctx.runtime()); const auto module = - std::format("export function handler() {{\n{}\n}}", body); + fmt::format("export function handler() {{\n{}\n}}", body); auto handler = ctx.get_exported_function(module, "handler", "/test/crypto.js"); const auto result = ctx.call_with_rt_options( @@ -4377,7 +3968,7 @@ TEST_CASE("ccf.crypto.verifySignature against an X.509 certificate") ccf::ds::to_x509_time_string(ccf::nonstd::SystemClock::now() + 24h * 3650); auto cert_pem = kp->self_sign("CN=verify test", valid_from, valid_to); - run_crypto_handler(std::format( + run_crypto_handler(fmt::format( R"JS( const cert = {}; const privateKey = {}; @@ -4511,12 +4102,12 @@ TEST_CASE("ccf.tcbHexToPolicy") auto js_field = [](const char* field, auto opt) { if (!opt.has_value()) { - return std::format( + return fmt::format( "if (\"{}\" in policy) throw new Error(\"unexpected {}\");\n", field, field); } - return std::format( + return fmt::format( "if (policy.{} !== {}) throw new Error(\"bad {}: \" + policy.{});\n", field, opt.value(), @@ -4525,7 +4116,7 @@ TEST_CASE("ccf.tcbHexToPolicy") }; std::string checks; - checks += std::format( + checks += fmt::format( "if (policy.hexstring !== {}) throw new Error(\"bad hexstring: \" + " "policy.hexstring);\n", js_string_literal(expected.hexstring.value())); @@ -4535,7 +4126,7 @@ TEST_CASE("ccf.tcbHexToPolicy") checks += js_field("boot_loader", expected.boot_loader); checks += js_field("fmc", expected.fmc); - run_crypto_handler(std::format( + run_crypto_handler(fmt::format( R"JS( const policy = ccf.tcbHexToPolicy("{}", "{}"); {} diff --git a/src/kv/test/kv_serialisation.cpp b/src/kv/test/kv_serialisation.cpp index cbbfb287a56c..cc3f892916c9 100644 --- a/src/kv/test/kv_serialisation.cpp +++ b/src/kv/test/kv_serialisation.cpp @@ -1,6 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. -#include "ccf/kv/value.h" #include "ds/internal_logger.h" #include "kv/kv_serialiser.h" #include "kv/null_encryptor.h" @@ -10,7 +9,6 @@ #include "node/encryptor.h" #include -#include #undef FAIL #include #include @@ -720,10 +718,9 @@ TEST_CASE( kv_store.set_encryptor(encryptor); kv_store.set_max_transaction_size(1); - ccf::kv::RawCopySerialisedValue> tree( - ccf::Tables::SERIALISED_MERKLE_TREE); + MapTypes::StringString map("public:signature"); auto tx = kv_store.create_reserved_tx(kv_store.next_txid().value()); - tx.wo(tree)->put(std::vector(512, 'A')); + tx.rw(map)->put("signature", std::string(512, 'A')); const auto [result, data, claims, commit_evidence, hooks] = tx.commit_reserved(); @@ -1184,7 +1181,7 @@ struct CustomVerboseDumbSerialiser static Bytes to_serialised(const CustomClass& c) { - const auto verbose = std::format("{}\ns={}\nn={}", T::prefix, c.s, c.n); + const auto verbose = fmt::format("{}\ns={}\nn={}", T::prefix, c.s, c.n); return Bytes(verbose.begin(), verbose.end()); } @@ -1250,8 +1247,6 @@ TEST_CASE_TEMPLATE( ccf::kv::Store kv_store; auto encryptor = std::make_shared(); kv_store.set_encryptor(encryptor); - auto consensus = std::make_shared(); - kv_store.set_consensus(consensus); MapType map("public:map"); @@ -1268,19 +1263,19 @@ TEST_CASE_TEMPLATE( MapType map2("public:map"); - auto tx = kv_store.create_tx(); + auto tx = kv_store.create_reserved_tx(kv_store.next_txid().value()); auto handle = tx.rw(map); handle->put(k1, v1); handle->put(k2, v2); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - const auto data = consensus->get_latest_data(); - REQUIRE(data.has_value()); + auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = + tx.commit_reserved(); + auto& success = success_; + auto& data = data_; + REQUIRE(success == ccf::kv::CommitResult::SUCCESS); kv_store.compact(kv_store.current_version()); - REQUIRE( - kv_store2.deserialize(data.value())->apply() == - ccf::kv::ApplyResult::PASS); + REQUIRE(kv_store2.deserialize(data)->apply() == ccf::kv::ApplyResult::PASS); auto tx2 = kv_store2.create_tx(); auto handle2 = tx2.rw(map2); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index d7df96818af5..41afee682d10 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -13,20 +13,16 @@ #include "kv/compacted_version_conflict.h" #include "kv/kv_serialiser.h" #include "kv/ledger_chunker.h" -#include "kv/map_access_denied.h" #include "kv/null_encryptor.h" #include "kv/store.h" #include "kv/test/null_tx_history.h" #include "kv/test/stub_consensus.h" -#include - #define DOCTEST_CONFIG_IMPLEMENT #include #undef FAIL #include #include -#include #include #include #include @@ -44,37 +40,6 @@ struct MapTypes using UntypedMap = ccf::kv::untyped::Map; }; -static ccf::kv::PendingTxInfo make_signature_entry( - ccf::kv::Store& store, const ccf::TxID& txid, uint8_t marker) -{ - auto signature = store.create_reserved_tx(txid); - signature.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); - signature.wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, {marker}); - signature.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({marker}); - return signature.commit_reserved(); -} - -static ccf::kv::CommitResult publish_signature_entry( - ccf::kv::Store& store, const ccf::TxID& txid, uint8_t marker) -{ - auto info = make_signature_entry(store, txid, marker); - if (info.success != ccf::kv::CommitResult::SUCCESS) - { - return info.success; - } - return store.commit( - txid, - std::make_unique( - std::move(info.data), - std::move(info.claims_digest), - std::move(info.commit_evidence_digest), - std::move(info.hooks)), - true); -} - TEST_CASE("Map name parsing") { using SD = ccf::kv::SecurityDomain; @@ -101,448 +66,6 @@ TEST_CASE("Map name parsing") REQUIRE(parse("public:ccf_foo") == mp(SD::PUBLIC, AC::APPLICATION)); } -TEST_CASE("Live transactions cannot acquire signature table handles") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - - auto check_denied = [&store]() { - for (const auto* name : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - INFO("Restricted table: ", std::string_view(name)); - MapTypes::StringString typed_map(name); - - auto tx = store.create_tx(); - CHECK_THROWS_AS(tx.ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx.rw(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS(tx.wo(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.ro(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.rw(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - tx.wo(name), ccf::kv::MapAccessDenied); - - auto ro = store.create_read_only_tx(); - CHECK_THROWS_AS(ro.ro(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - ro.ro(name), ccf::kv::MapAccessDenied); - - auto diff = store.create_tx_diff(); - CHECK_THROWS_AS(diff.diff(typed_map), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - diff.diff(name), ccf::kv::MapAccessDenied); - } - }; - - INFO("Denied before any signature exists, without creating maps or snapshot"); - auto deferred_tx = store.create_tx(); - auto deferred_ro = store.create_read_only_tx(); - CHECK_THROWS_AS( - deferred_tx.ro(ccf::Tables::SIGNATURES), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - deferred_ro.ro(ccf::Tables::SIGNATURES), - ccf::kv::MapAccessDenied); - check_denied(); - for (const auto* name : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - CHECK(store.get_map(store.current_version(), name) == nullptr); - } - CHECK(store.current_version() == 0); - - INFO("Denied while a signature reservation is pending and after it commits"); - const auto signature_txid = store.next_txid().value(); - check_denied(); - MapTypes::StringString ordinary("public:ordinary"); - { - auto writer = store.create_tx(); - writer.rw(ordinary)->put("key", "value"); - REQUIRE(writer.commit() == ccf::kv::CommitResult::SUCCESS); - } - REQUIRE(deferred_tx.ro(ordinary)->get("key") == "value"); - REQUIRE(deferred_ro.ro(ordinary)->get("key") == "value"); - REQUIRE( - publish_signature_entry(store, signature_txid, 42) == - ccf::kv::CommitResult::SUCCESS); - check_denied(); - - INFO("Restrictions apply only to the exact three public signature tables"); - for (const auto* name : - {"public:ccf.internal.signatures_extra", - "public:ccf.internal.cose_signatures.extra", - "public:ccf.internal.tree_extra", - "ccf.internal.signatures", - ccf::Tables::ENCRYPTED_PAST_LEDGER_SECRET}) - { - INFO("Allowed table: ", std::string_view(name)); - MapTypes::StringString map(name); - auto tx = store.create_tx(); - tx.wo(map)->put("key", "value"); - REQUIRE(tx.ro(map)->get("key") == "value"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - auto read = store.create_read_only_tx(); - REQUIRE(read.ro(map)->get("key") == "value"); - auto diff = store.create_tx_diff(); - REQUIRE(diff.diff(map)->size() == 1); - } -} - -TEST_CASE("Historical signature entries remain readable") -{ - ccf::kv::Store source; - source.set_encryptor(std::make_shared()); - const auto txid = source.next_txid().value(); - auto info = make_signature_entry(source, txid, 42); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - - ccf::kv::Store historical(true); - historical.set_encryptor(std::make_shared()); - REQUIRE( - historical.deserialize(info.data)->apply() == - ccf::kv::ApplyResult::PASS_SIGNATURE); - - auto tx = historical.create_read_only_tx(); - REQUIRE( - tx.ro(ccf::Tables::SIGNATURES)->get()->seqno == - txid.seqno); - REQUIRE( - tx.ro(ccf::Tables::COSE_SIGNATURES) - ->get(ccf::IdentityType::CLASSICAL) == std::vector{42}); - REQUIRE( - tx.ro(ccf::Tables::SERIALISED_MERKLE_TREE) - ->get() == std::vector{42}); - - auto ptr = historical.create_read_only_tx_ptr(); - auto diff = historical.create_tx_diff(); - for (const auto* name : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - INFO("Historical table: ", std::string_view(name)); - REQUIRE(ptr->ro(name)->size() == 1); - REQUIRE(diff.diff(name)->size() == 1); - - auto ordinary = historical.create_tx(); - CHECK_THROWS_AS( - ordinary.ro(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - ordinary.wo(name), ccf::kv::MapAccessDenied); - } -} - -TEST_CASE("Reserved transactions are write-only on signature tables") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - store.set_consensus(std::make_shared()); - - INFO("Cannot access non-signature maps or upgrade signature handles"); - { - auto reserved = store.create_reserved_tx(store.next_txid().value()); - CHECK_THROWS_AS( - reserved.wo("public:ordinary"), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.rw("public:ordinary"), - ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.ro("public:ordinary"), - ccf::kv::MapAccessDenied); - CHECK(store.get_map(store.current_version(), "public:ordinary") == nullptr); - - for (const auto* name : - {ccf::Tables::SIGNATURES, - ccf::Tables::COSE_SIGNATURES, - ccf::Tables::SERIALISED_MERKLE_TREE}) - { - INFO("Reserved table: ", std::string_view(name)); - auto* handle = reserved.wo(name); - CHECK(reserved.wo(name) == handle); - CHECK_THROWS_AS( - reserved.ro(name), ccf::kv::MapAccessDenied); - CHECK_THROWS_AS( - reserved.rw(name), ccf::kv::MapAccessDenied); - } - } - - INFO("Clear on an empty signature table records a read and is rejected"); - { - auto reserved = store.create_reserved_tx(store.next_txid().value()); - auto* tree = reserved.wo( - ccf::Tables::SERIALISED_MERKLE_TREE); - tree->clear(); - tree->put({1}); - CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); - } - - INFO("Recorded read dependencies on populated signature tables are rejected"); - const auto baseline = store.next_txid().value(); - REQUIRE( - publish_signature_entry(store, baseline, 1) == - ccf::kv::CommitResult::SUCCESS); - store.compact(baseline.seqno); - for (const std::string_view observation : - {"get", - "foreach", - "clear", - "get_globally_committed", - "has_globally_committed"}) - { - INFO("Reserved observation: ", observation); - auto reserved = store.create_reserved_tx(store.next_txid().value()); - auto* handle = - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); - const auto key = ccf::SerialisedMerkleTree::create_unit(); - if (observation == "get") - { - REQUIRE(handle->get(key).has_value()); - } - else if (observation == "foreach") - { - handle->foreach([](const auto&, const auto&) { return true; }); - } - else if (observation == "clear") - { - reserved - .wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->clear(); - } - else if (observation == "get_globally_committed") - { - REQUIRE(handle->get_globally_committed(key).has_value()); - } - else - { - REQUIRE(handle->has_globally_committed(key)); - } - handle->put(key, {2}); - CHECK_THROWS_AS(reserved.commit_reserved(), ccf::kv::MapAccessDenied); - } -} - -TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - MapTypes::StringString raw("public:raw"); - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "old"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - const auto old_signature = store.next_txid().value(); - REQUIRE( - publish_signature_entry(store, old_signature, 1) == - ccf::kv::CommitResult::SUCCESS); - const auto pending_signature = store.next_txid().value(); - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "new"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - REQUIRE(store.current_version() == pending_signature.seqno + 1); - REQUIRE(consensus->number_of_replicas() == old_signature.seqno); - - auto cold = store.create_read_only_tx_at_replicated_state(); - auto warm = store.create_read_only_tx_at_replicated_state(); - REQUIRE( - warm.ro(ccf::Tables::SIGNATURES)->get()->seqno == - old_signature.seqno); - REQUIRE(warm.ro(raw)->get("key") == "old"); - REQUIRE( - publish_signature_entry(store, pending_signature, 2) == - ccf::kv::CommitResult::SUCCESS); - - for (auto* read : {&cold, &warm}) - { - REQUIRE(read->ro(raw)->get("key") == "old"); - REQUIRE( - read->ro(ccf::Tables::SIGNATURES)->get()->seqno == - old_signature.seqno); - REQUIRE( - read->ro(ccf::Tables::COSE_SIGNATURES) - ->get(ccf::IdentityType::CLASSICAL) == std::vector{1}); - REQUIRE( - read->ro(ccf::Tables::SERIALISED_MERKLE_TREE) - ->get() == std::vector{1}); - } - - auto current = store.create_read_only_tx_at_replicated_state(); - REQUIRE(current.ro(raw)->get("key") == "new"); - REQUIRE( - current.ro(ccf::Tables::SIGNATURES)->get()->seqno == - pending_signature.seqno); - REQUIRE( - current.ro(ccf::Tables::COSE_SIGNATURES) - ->get(ccf::IdentityType::CLASSICAL) == std::vector{2}); - REQUIRE( - current.ro(ccf::Tables::SERIALISED_MERKLE_TREE) - ->get() == std::vector{2}); -} - -TEST_CASE("Materialised reads reject rollback and see replication compaction") -{ - SUBCASE("Rollback before lookup invalidates live and historical views") - { - for (const bool is_historical : {false, true}) - { - INFO("Historical store: ", is_historical); - ccf::kv::Store store(is_historical); - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - constexpr ccf::View initial_view = 2; - constexpr ccf::View replacement_view = 3; - store.initialise_term(initial_view); - MapTypes::StringString raw("public:raw"); - ccf::Signatures signatures(ccf::Tables::SIGNATURES); - ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "old"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - const auto initial_signature = store.next_txid().value(); - REQUIRE( - publish_signature_entry(store, initial_signature, 1) == - ccf::kv::CommitResult::SUCCESS); - - auto old = store.create_read_only_tx_at_replicated_state(); - REQUIRE(old.ro(signatures)->get()->seqno == initial_signature.seqno); - auto diff = store.create_tx_diff(); - if (is_historical) - { - REQUIRE(diff.diff(cose_signatures)->size() == 1); - } - - store.rollback({initial_view, 0}, replacement_view); - consensus->view_history.rollback(0); - consensus->flush(); - { - auto tx = store.create_tx(); - tx.rw(raw)->put("key", "replacement"); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - const auto replacement_signature = store.next_txid().value(); - REQUIRE(replacement_signature.seqno == initial_signature.seqno); - REQUIRE( - publish_signature_entry(store, replacement_signature, 2) == - ccf::kv::CommitResult::SUCCESS); - - CHECK_THROWS_AS(old.ro(raw), ccf::kv::CompactedVersionConflict); - CHECK_THROWS_AS(old.ro(signatures), ccf::kv::CompactedVersionConflict); - if (is_historical) - { - CHECK_THROWS_AS( - diff.diff(cose_signatures), ccf::kv::CompactedVersionConflict); - } - - auto fresh = store.create_read_only_tx_at_replicated_state(); - REQUIRE(fresh.ro(raw)->get("key") == "replacement"); - REQUIRE( - fresh.ro(cose_signatures)->get(ccf::IdentityType::CLASSICAL) == - std::vector{2}); - } - } - - SUBCASE("Rollback during snapshot acquisition is detected") - { - class ReplacingStore : public ccf::kv::Store - { - public: - std::function replace_during_lookup = nullptr; - bool replacement_triggered = false; - - std::shared_ptr get_map( - ccf::kv::Version version, const std::string& name) override - { - if ( - name == ccf::Tables::COSE_SIGNATURES && - replace_during_lookup != nullptr) - { - auto replace = std::exchange(replace_during_lookup, nullptr); - replacement_triggered = true; - replace(); - } - return ccf::kv::Store::get_map(version, name); - } - }; - - ReplacingStore store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - store.initialise_term(2); - ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - const auto initial_signature = store.next_txid().value(); - REQUIRE( - publish_signature_entry(store, initial_signature, 1) == - ccf::kv::CommitResult::SUCCESS); - auto old = store.create_read_only_tx_at_replicated_state(); - - store.replace_during_lookup = [&]() { - store.rollback({2, 0}, 3); - consensus->view_history.rollback(0); - consensus->flush(); - REQUIRE( - publish_signature_entry(store, store.next_txid().value(), 2) == - ccf::kv::CommitResult::SUCCESS); - }; - - CHECK_THROWS_AS(old.ro(cose_signatures), ccf::kv::CompactedVersionConflict); - REQUIRE(store.replacement_triggered); - } - - SUBCASE("Prefix compacted synchronously inside replication is visible") - { - class CompactingConsensus : public ccf::kv::test::PrimaryStubConsensus - { - ccf::kv::Store& store; - - public: - std::optional observed_signature; - - explicit CompactingConsensus(ccf::kv::Store& store_) : store(store_) {} - - bool replicate( - const ccf::kv::BatchVector& entries, ccf::View view) override - { - const auto result = PrimaryStubConsensus::replicate(entries, view); - store.compact(std::get<0>(entries.back())); - auto read = store.create_read_only_tx_at_replicated_state(); - if (auto sig = read.ro(ccf::Tables::SIGNATURES)->get()) - { - observed_signature = sig->seqno; - } - return result; - } - }; - - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(store); - store.set_consensus(consensus); - const auto txid = store.next_txid().value(); - REQUIRE( - publish_signature_entry(store, txid, 1) == - ccf::kv::CommitResult::SUCCESS); - REQUIRE(consensus->observed_signature == txid.seqno); - } -} - TEST_CASE("Zero-revision whole-map dependencies") { using Result = ccf::kv::CommitResult; @@ -3066,25 +2589,24 @@ TEST_CASE("Deserialising from other Store") auto encryptor = std::make_shared(); ccf::kv::Store store; store.set_encryptor(encryptor); - auto consensus = std::make_shared(); - store.set_consensus(consensus); MapTypes::NumString public_map("public:public"); MapTypes::NumString private_map("private"); - auto tx1 = store.create_tx(); + auto tx1 = store.create_reserved_tx(store.next_txid().value()); auto handle1 = tx1.rw(public_map); auto handle2 = tx1.rw(private_map); handle1->put(42, "aardvark"); handle2->put(14, "alligator"); - REQUIRE(tx1.commit() == ccf::kv::CommitResult::SUCCESS); - const auto data = consensus->get_latest_data(); - REQUIRE(data.has_value()); + auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = + tx1.commit_reserved(); + auto& success = success_; + auto& data = data_; + REQUIRE(success == ccf::kv::CommitResult::SUCCESS); ccf::kv::Store clone; clone.set_encryptor(encryptor); - REQUIRE( - clone.deserialize(data.value())->apply() == ccf::kv::ApplyResult::PASS); + REQUIRE(clone.deserialize(data)->apply() == ccf::kv::ApplyResult::PASS); } TEST_CASE("Transaction diffs") @@ -3258,8 +2780,6 @@ TEST_CASE("Deserialise return status") ccf::kv::Store store; auto encryptor = std::make_shared(); store.set_encryptor(encryptor); - auto consensus = std::make_shared(); - store.set_consensus(consensus); ccf::Signatures signatures(ccf::Tables::SIGNATURES); ccf::SerialisedMerkleTree serialised_tree( @@ -3276,22 +2796,24 @@ TEST_CASE("Deserialise return status") store.set_history(history); { - auto tx = store.create_tx(); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto data_handle = tx.rw(data); data_handle->put(42, 42); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - const auto serialised_data = consensus->get_latest_data(); - REQUIRE(serialised_data.has_value()); + auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = + tx.commit_reserved(); + auto& success = success_; + auto& serialised_data = data_; + REQUIRE(success == ccf::kv::CommitResult::SUCCESS); REQUIRE( - store.deserialize(serialised_data.value())->apply() == + store.deserialize(serialised_data)->apply() == ccf::kv::ApplyResult::PASS); } { auto tx = store.create_reserved_tx(store.next_txid().value()); - auto sig_handle = tx.wo(signatures); - auto tree_handle = tx.wo(serialised_tree); + auto sig_handle = tx.rw(signatures); + auto tree_handle = tx.rw(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); sig_handle->put(sigv); tree_handle->put({}); @@ -3308,35 +2830,17 @@ TEST_CASE("Deserialise return status") INFO("Signature transactions with additional contents should fail"); { - // The transaction API rejects this mixture, so exercise ledger admission - // with an explicitly malformed serialised entry. - ccf::kv::RawKvStoreSerialiser serialiser( - encryptor, - ccf::TxID{store.commit_view(), store.current_version() + 1}, - ccf::kv::EntryType::WriteSet, - 0); - const auto serialise_single_write = - [&serialiser]( - const std::string& name, - const ccf::kv::serialisers::SerialisedEntry& key, - const ccf::kv::serialisers::SerialisedEntry& value) { - serialiser.start_map(name, ccf::kv::SecurityDomain::PUBLIC); - serialiser.serialise_entry_version(ccf::kv::NoVersion); - serialiser.serialise_count_header(0); - serialiser.serialise_count_header(1); - serialiser.serialise_write(key, value); - serialiser.serialise_count_header(0); - }; + auto tx = store.create_reserved_tx(store.next_txid().value()); + auto sig_handle = tx.rw(signatures); + auto data_handle = tx.rw(data); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); - serialise_single_write( - signatures.get_name(), - ccf::Signatures::create_unit(), - ccf::Signatures::ValueSerialiser::to_serialised(sigv)); - serialise_single_write( - data.get_name(), - MapTypes::NumNum::KeySerialiser::to_serialised(43), - MapTypes::NumNum::ValueSerialiser::to_serialised(43)); - const auto serialised_data = serialiser.get_raw_data(); + sig_handle->put(sigv); + data_handle->put(43, 43); + auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = + tx.commit_reserved(); + auto& success = success_; + auto& serialised_data = data_; + REQUIRE(success == ccf::kv::CommitResult::SUCCESS); REQUIRE( store.deserialize(serialised_data)->apply() == @@ -4122,7 +3626,7 @@ TEST_CASE("Cross-map conflicts") std::string rand_string(size_t i) { - return std::format("{}: {}", i, rand()); + return fmt::format("{}: {}", i, rand()); } TEST_CASE("Mid-tx compaction") @@ -4376,8 +3880,7 @@ TEST_CASE("CommittableTx guards") const auto baseline_txid = kv_store.current_txid(); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({42}); + reserved.rw(map)->put("k", "from_reserved"); // Roll the store back, invalidating the rollback_count that `reserved` // captured when it was created. @@ -4406,44 +3909,13 @@ TEST_CASE("CommittableTx guards") std::logic_error); } - SUBCASE("commit rejects a reserved transaction directly and via base ref") - { - ccf::kv::Store kv_store; - kv_store.set_encryptor(std::make_shared()); - - const auto reserved_txid = kv_store.next_txid().value(); - auto reserved = kv_store.create_reserved_tx(reserved_txid); - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({42}); - - REQUIRE_THROWS_WITH_AS( - reserved.commit(), - "Reserved transaction must be committed with commit_reserved()", - std::logic_error); - - ccf::kv::CommittableTx& base = reserved; - REQUIRE_THROWS_WITH_AS( - base.commit(), - "Reserved transaction must be committed with commit_reserved()", - std::logic_error); - - REQUIRE(kv_store.current_version() == reserved_txid.seqno); - REQUIRE_THROWS_WITH_AS( - auto _ = reserved.commit_version(), - "Transaction not yet committed", - std::logic_error); - REQUIRE( - reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); - } - SUBCASE("commit_reserved rejects being called twice") { ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({42}); + reserved.rw(map)->put("k", "v"); REQUIRE( reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); @@ -4482,31 +3954,22 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - const auto baseline = kv_store.next_txid().value(); - REQUIRE( - make_signature_entry(kv_store, baseline, 42).success == - ccf::kv::CommitResult::SUCCESS); + { + // Establish the map, so the reserved tx below can read from it without + // creating it + auto tx = kv_store.create_tx(); + tx.rw(map)->put("k", "v"); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + } // Such a transaction would otherwise succeed with an empty ledger entry, // leaving nothing at its reserved version auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); - auto* handle = - reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); - REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); - bool denied = false; - try - { - reserved.commit_reserved(); - } - catch (const ccf::kv::MapAccessDenied& e) - { - denied = true; - CHECK( - std::string_view(e.what()) == - "Reserved transaction cannot depend on reads from map " - "'public:ccf.internal.tree'"); - } - REQUIRE(denied); + REQUIRE(reserved.rw(map)->get("k") == "v"); + REQUIRE_THROWS_WITH_AS( + reserved.commit_reserved(), + "Reserved transaction cannot be empty", + std::logic_error); REQUIRE_THROWS_WITH_AS( auto _ = reserved.commit_version(), "Transaction not yet committed", @@ -5156,11 +4619,11 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") size_t n = 0; while (!stop_token.stop_requested()) { - // These names are repeatedly created and removed. The lookup holds - // maps_lock, and avoids any additional ordering with the writer. - const auto* name = (n % 2 == 0) ? ccf::Tables::SIGNATURES : - ccf::Tables::SERIALISED_MERKLE_TREE; - (void)store.get_map(2, name); + // Takes maps_lock and searches the map set. Looks up names in the + // range being inserted, so the search path traverses the nodes + // add_dynamic_map is writing. Deliberately avoids current_version(), + // so this contends only on maps_lock. + (void)store.get_map(1, fmt::format("public:reserved_{}", n % 2000)); n++; } }); @@ -5169,16 +4632,16 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") constexpr size_t reserved_txs = 2000; for (size_t i = 0; i < reserved_txs; ++i) { - // Rollback removes the signature tables so the next reservation creates - // them again, exercising add_dynamic_map on every iteration. - const auto txid = store.next_txid().value(); - REQUIRE( - make_signature_entry(store, txid, 42).success == - ccf::kv::CommitResult::SUCCESS); - if (i + 1 < reserved_txs) - { - store.rollback({txid.view, 1}, txid.view); - } + // Each reserved transaction writes to a map that does not exist yet, so + // committing it adds to the Store's map set. Nothing else here may take + // maps_lock, or it would order the write against the readers and hide the + // race being reproduced. + auto tx = store.create_reserved_tx(store.next_txid().value()); + tx.rw(fmt::format("public:reserved_{}", i)) + ->put("k", "v"); + const auto [result, data, claims, commit_evidence, hooks] = + tx.commit_reserved(); + REQUIRE(result == ccf::kv::CommitResult::SUCCESS); } for (auto& reader : readers) @@ -5187,12 +4650,14 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") } readers.clear(); - // Confirm the final reservation really recreated the signature tables. + // Confirm the writes really did extend the map set, so this exercises + // Store::add_dynamic_map rather than silently doing nothing. REQUIRE( - store.get_map(store.current_version(), ccf::Tables::SIGNATURES) != nullptr); + store.get_map(store.current_version(), "public:reserved_0") != nullptr); REQUIRE( store.get_map( - store.current_version(), ccf::Tables::SERIALISED_MERKLE_TREE) != nullptr); + store.current_version(), + fmt::format("public:reserved_{}", reserved_txs - 1)) != nullptr); } // Exposes the version the chunker has recorded entries up to, which is the @@ -5221,6 +4686,7 @@ class RollingBackPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; + MapTypes::StringString& table; ccf::TxID rollback_to; ccf::kv::Term rollback_term; @@ -5228,17 +4694,21 @@ class RollingBackPendingTx : public ccf::kv::PendingTx RollingBackPendingTx( ccf::TxID txid_, ccf::kv::Store& store_, + MapTypes::StringString& table_, ccf::TxID rollback_to_, ccf::kv::Term rollback_term_) : txid(txid_), store(store_), + table(table_), rollback_to(rollback_to_), rollback_term(rollback_term_) {} ccf::kv::PendingTxInfo call() override { - auto info = make_signature_entry(store, txid, 42); + auto tx = store.create_reserved_tx(txid); + tx.rw(table)->put("key", "value"); + auto info = tx.commit_reserved(); store.rollback(rollback_to, rollback_term); return info; } @@ -5279,7 +4749,7 @@ TEST_CASE("Chunk metadata is not restored by a batch a rollback discarded") store.commit( reserved, std::make_unique( - reserved, store, baseline_txid, initial_term + 1), + reserved, store, map, baseline_txid, initial_term + 1), false); } @@ -5566,7 +5036,7 @@ TEST_CASE("committable_gap after replaying a ledger ending in a signature") for (size_t i = 1; i <= tx_count; ++i) { auto tx = primary.create_tx(); - tx.rw(map)->put(std::format("key{}", i), "value"); + tx.rw(map)->put(fmt::format("key{}", i), "value"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(primary.committable_gap() == i); } @@ -5607,7 +5077,7 @@ TEST_CASE("committable_gap after replaying a ledger ending in a signature") for (size_t i = 1; i <= tx_count; ++i) { auto tx = store.create_tx(); - tx.rw(map)->put("key", std::format("value{}", i)); + tx.rw(map)->put("key", fmt::format("value{}", i)); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(store.committable_gap() == i); } @@ -5637,7 +5107,7 @@ TEST_CASE("committable_gap after rolling back replayed entries") for (size_t i = 0; i < count; ++i) { auto tx = primary.create_tx(); - tx.rw(map)->put("key", std::format("value{}", primary.current_version())); + tx.rw(map)->put("key", fmt::format("value{}", primary.current_version())); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } }; @@ -5775,8 +5245,8 @@ TEST_CASE("Ledger entry chunk request") { auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); - auto sig_handle = tx.wo(signatures); - auto tree_handle = tx.wo(serialised_tree); + auto sig_handle = tx.rw(signatures); + auto tree_handle = tx.rw(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, txid.seqno); sig_handle->put(sigv); tree_handle->put({}); @@ -5851,8 +5321,8 @@ TEST_CASE("Ledger entry chunk request") REQUIRE(store.should_create_ledger_chunk(txid.seqno)); // Add the signature - auto sig_handle = tx.wo(signatures); - auto tree_handle = tx.wo(serialised_tree); + auto sig_handle = tx.rw(signatures); + auto tree_handle = tx.rw(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, txid.seqno); sig_handle->put(sigv); tree_handle->put({}); @@ -5877,243 +5347,6 @@ TEST_CASE("Ledger entry chunk request") } } -TEST_CASE("Store version wraps to 0 past INT64_MAX") -{ - ccf::kv::Store kv_store; - auto encryptor = std::make_shared(); - kv_store.set_encryptor(encryptor); - kv_store.initialise_term(2); - - constexpr auto max_signed_version = - static_cast(std::numeric_limits::max()); - ccf::kv::StoreSnapshot snapshot(max_signed_version); - auto serialised = snapshot.serialise(encryptor); - ccf::kv::ConsensusHookPtrs hooks; - REQUIRE( - kv_store.deserialise_snapshot( - serialised.data(), serialised.size(), hooks) == - ccf::kv::ApplyResult::PASS); - REQUIRE(kv_store.current_version() == max_signed_version); - - const auto wrapped_txid = kv_store.next_txid().value(); - REQUIRE(wrapped_txid.view == 2); - REQUIRE(wrapped_txid.seqno == 0); - REQUIRE(kv_store.current_version() == 0); - - const auto next_txid = kv_store.next_txid().value(); - REQUIRE(next_txid.view == 2); - REQUIRE(next_txid.seqno == 1); - REQUIRE(kv_store.current_version() == 1); -} - -TEST_CASE("Store::commit edge cases") -{ - class FixedResultPendingTx : public ccf::kv::PendingTx - { - ccf::kv::CommitResult result; - - public: - explicit FixedResultPendingTx(ccf::kv::CommitResult result_) : - result(result_) - {} - - ccf::kv::PendingTxInfo call() override - { - return {result, {}, ccf::empty_claims(), {}, {}}; - } - }; - - SUBCASE("Out-of-order committable commits do not regress last_committable") - { - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - store.initialise_term(1); - - const auto txid1 = store.next_txid().value(); - const auto txid2 = store.next_txid().value(); - REQUIRE(txid1.seqno == 1); - REQUIRE(txid2.seqno == 2); - - // Commit seqno 2 first so last_committable advances to 2 while seqno 2 - // waits in pending_txs for seqno 1. - REQUIRE( - store.commit( - txid2, - std::make_unique(ccf::kv::CommitResult::SUCCESS), - true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(consensus->number_of_replicas() == 0); - REQUIRE(store.committable_gap() == 0); - - // Committing an earlier committable seqno must not lower last_committable, - // and should drain both queued entries in order. - REQUIRE( - store.commit( - txid1, - std::make_unique(ccf::kv::CommitResult::SUCCESS), - true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(consensus->number_of_replicas() == 2); - REQUIRE(store.committable_gap() == 0); - } - - SUBCASE("Unexpected non-SUCCESS PendingTx result is handled without aborting") - { - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - store.set_consensus(consensus); - store.initialise_term(1); - - const auto txid = store.next_txid().value(); - REQUIRE( - store.commit( - txid, - std::make_unique( - ccf::kv::CommitResult::FAIL_CONFLICT), - false) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(consensus->number_of_replicas() == 1); - } -} - -TEST_CASE("untyped::Map::create_committer rejects unexpected AbstractChangeSet") -{ - class DummyChangeSet : public ccf::kv::AbstractChangeSet - { - public: - [[nodiscard]] bool has_writes() const override - { - return false; - } - }; - - ccf::kv::Store store; - ccf::kv::untyped::Map map(&store, "public:map"); - DummyChangeSet dummy; - - REQUIRE_THROWS_WITH_AS( - map.create_committer(&dummy), "Type confusion error", std::logic_error); -} - -TEST_CASE("apply_changes ignores new_maps entries absent from changes") -{ - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - - auto written_map = - std::make_shared(&store, "public:written"); - auto untracked_map = - std::make_shared(&store, "public:untracked"); - - auto changeset = written_map->create_change_set(0, false); - REQUIRE(changeset != nullptr); - const auto key = - ccf::kv::serialisers::JsonSerialiser::to_serialised("k"); - const auto val = - ccf::kv::serialisers::JsonSerialiser::to_serialised("v"); - changeset->writes[key] = val; - - ccf::kv::OrderedChanges changes; - changes.emplace( - std::piecewise_construct, - std::forward_as_tuple("public:written"), - std::forward_as_tuple(written_map, std::move(changeset))); - - ccf::kv::MapCollection new_maps; - new_maps["public:written"] = written_map; - new_maps["public:untracked"] = untracked_map; - - ccf::kv::ConsensusHookPtrs hooks; - store.lock_map_set(); - const auto committed_v = ccf::kv::apply_changes( - changes, - []() -> std::optional { return 1; }, - hooks, - new_maps, - std::nullopt, - false); - store.unlock_map_set(); - - REQUIRE(committed_v.has_value()); - REQUIRE(*committed_v == 1); - REQUIRE(store.get_map(1, "public:written") == written_map); - REQUIRE(store.get_map(1, "public:untracked") == nullptr); -} - -TEST_CASE("BaseTx internal invariant guards") -{ - class TestBaseTx : public ccf::kv::BaseTx - { - public: - using BaseTx::BaseTx; - using BaseTx::compacted_version_conflict; - using BaseTx::get_map_and_change_set_by_name; - using BaseTx::retain_change_set; - }; - - ccf::kv::Store store; - store.set_encryptor(std::make_shared()); - - SUBCASE("retain_change_set rejects duplicate map name") - { - TestBaseTx tx(&store); - auto mc = tx.get_map_and_change_set_by_name("public:dup", false); - auto untyped_map = std::dynamic_pointer_cast(mc.map); - REQUIRE(untyped_map != nullptr); - - tx.retain_change_set("public:dup", std::move(mc.changeset), mc.map); - - auto duplicate_cs = untyped_map->create_change_set(0, false); - REQUIRE_THROWS_WITH_AS( - tx.retain_change_set("public:dup", std::move(duplicate_cs), mc.map), - "Re-creating change set for map public:dup", - std::logic_error); - } - - SUBCASE( - "get_map_and_change_set_by_name rejects duplicate created map without " - "handle") - { - TestBaseTx tx(&store); - auto mc = tx.get_map_and_change_set_by_name("public:unretained", false); - REQUIRE(mc.map != nullptr); - - REQUIRE_THROWS_WITH_AS( - tx.get_map_and_change_set_by_name("public:unretained", false), - "Created map without creating handle over it", - std::logic_error); - } - - SUBCASE("get_map_and_change_set_by_name rejects non-untyped AbstractMap") - { - class WrongMapStore : public ccf::kv::Store - { - public: - std::shared_ptr get_map( - ccf::kv::Version, const std::string& map_name) override - { - return std::make_shared(map_name); - } - }; - - WrongMapStore wrong_store; - ccf::kv::ReadOnlyTx tx(&wrong_store); - REQUIRE_THROWS_WITH_AS( - tx.ro("public:wrong_type"), - "Map public:wrong_type has unexpected type", - std::logic_error); - } - - SUBCASE("compacted_version_conflict requires read_txid to be set") - { - TestBaseTx tx(&store); - REQUIRE_THROWS_WITH_AS( - tx.compacted_version_conflict("public:map"), - "read_txid should have already been set", - std::logic_error); - } -} - int main(int argc, char** argv) { ccf::logger::config::default_init(); diff --git a/src/node/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index b0585ce90e98..442da3085183 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -1,18 +1,17 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. -#include "ccf/crypto/eddsa_key_pair.h" #include "ccf/crypto/pem.h" #include "ccf/crypto/verifier.h" -#include "crypto/certs.h" +#include "ccf/node/node_configuration_interface.h" #include "crypto/openssl/hash.h" +#include "crypto/openssl/mldsa_support.h" #include "ds/internal_logger.h" #include "frontend_test_infra.h" #include "kv/null_encryptor.h" #include "nlohmann/json.hpp" #include "node/http_node_client.h" #include "node/internal_tables_access.h" -#include "node/node_configuration_state.h" #include "node/rpc/node_frontend.h" #include "node/rpc/self_cert_auth.h" #include "node/startup_inputs.h" @@ -20,7 +19,6 @@ #include #include -#include #include #include #include @@ -82,7 +80,7 @@ class TestNodeRpcFrontend : public NodeRpcFrontend } }; -class StubNodeConfiguration : public NodeConfigurationStateInterface +class StubNodeConfiguration : public NodeConfigurationInterface { public: CCFConfig config = {}; @@ -110,7 +108,6 @@ TEST_CASE("Node configuration retains operator file paths") { const json input = { {"network", CCFConfig{}.network}, - {"node_certificate", {{"id_format", "did:key"}}}, {"node_data_json_file", "not-loaded/node.json"}, {"service_data_json_file", "not-loaded/service.json"}, {"tick_interval", "25ms"}, @@ -144,7 +141,6 @@ TEST_CASE("Node configuration retains operator file paths") {"service_mldsa_parameter_set", "ML-DSA-44"}}}}}}; auto config = input.get(); - CHECK(config.node_certificate.id_format == IdentityIdFormat::DIDKey); CHECK(config.command.type == StartType::Start); CHECK( config.command.start.members.front().certificate_file == @@ -209,7 +205,6 @@ TEST_CASE("Node configuration retains operator file paths") {{"type", "Join"}}}}.get(); CHECK(defaults.command.join.retry_timeout.count_ms() == 1000); CHECK(defaults.command.join.follow_redirect); - CHECK(defaults.node_certificate.id_format == IdentityIdFormat::SHA256); CHECK(defaults.command.join.fetch_recent_snapshot); CHECK( defaults.command.recover.initial_service_certificate_validity_days == 1); @@ -388,17 +383,13 @@ TEST_CASE("Startup inputs are read from files") MemberRecoveryRole::Owner}); start.members.push_back( {write_test_file(dir, "member1_cert.pem", member_cert.str())}); - ParsedMemberInfo did_member; - did_member.did_key = ccf::crypto::did_key_from_public_key_der( - ccf::crypto::make_verifier(member_cert)->public_key_der()); - start.members.push_back(did_member); start.constitution_files = { write_test_file(dir, "first.js", "first"), write_test_file(dir, "second.js", "second")}; start.service_configuration.recovery_threshold = 1; const auto genesis = resolve_genesis_info(start); - REQUIRE(genesis.members.size() == 3); + REQUIRE(genesis.members.size() == 2); CHECK(genesis.members[0].cert == member_cert); CHECK(genesis.members[0].encryption_pub_key == encryption_key); CHECK(genesis.members[0].member_data == json{{"is_operator", true}}); @@ -407,11 +398,6 @@ TEST_CASE("Startup inputs are read from files") CHECK_FALSE(genesis.members[1].encryption_pub_key.has_value()); CHECK(genesis.members[1].member_data.is_null()); CHECK_FALSE(genesis.members[1].recovery_role.has_value()); - CHECK(genesis.members[2].cert.empty()); - CHECK(genesis.members[2].did_key == did_member.did_key); - auto conflicting = start; - conflicting.members[2].certificate_file = "must-not-be-read.pem"; - CHECK_THROWS_AS(resolve_genesis_info(conflicting), std::logic_error); CHECK(genesis.constitution == "first\nsecond"); CHECK(genesis.service_configuration == start.service_configuration); @@ -424,7 +410,7 @@ TEST_CASE("Startup inputs are read from files") CHECK( logic_error_message([&]() { resolve_genesis_info(empty_member_data); }) .starts_with( - std::format("Could not parse member data from {}:", empty_file))); + fmt::format("Could not parse member data from {}:", empty_file))); } { @@ -432,7 +418,7 @@ TEST_CASE("Startup inputs are read from files") const auto malformed_file = write_test_file(dir, "malformed.json", "{"); CHECK(logic_error_message( [&]() { read_startup_json(malformed_file, "node data", true); }) - .starts_with(std::format( + .starts_with(fmt::format( "Could not parse node data from {}:", malformed_file))); } @@ -442,17 +428,17 @@ TEST_CASE("Startup inputs are read from files") CHECK( logic_error_message( [&]() { read_startup_file(missing_file, "service certificate"); }) == - std::format("Could not read service certificate from {}", missing_file)); + fmt::format("Could not read service certificate from {}", missing_file)); CHECK( logic_error_message( [&]() { read_startup_file(dir.path.string(), "constitution"); }) == - std::format("Could not read constitution from {}", dir.path.string())); + fmt::format("Could not read constitution from {}", dir.path.string())); auto missing_constitution = start; missing_constitution.constitution_files.push_back(missing_file); CHECK( logic_error_message([&]() { resolve_genesis_info(missing_constitution); - }) == std::format("Could not read constitution from {}", missing_file)); + }) == fmt::format("Could not read constitution from {}", missing_file)); } } @@ -535,7 +521,7 @@ TEST_CASE("Startup inputs are resolved by start type") CHECK( logic_error_message( [&]() { resolve_startup_inputs(no_service_cert, StartType::Join); }) == - std::format("Could not read service certificate from {}", missing_file)); + fmt::format("Could not read service certificate from {}", missing_file)); auto no_service_data = config; no_service_data.service_data_json_file = missing_file; @@ -544,7 +530,7 @@ TEST_CASE("Startup inputs are resolved by start type") CHECK( logic_error_message([&]() { resolve_startup_inputs(no_service_data, type); - }) == std::format("Could not read service data from {}", missing_file)); + }) == fmt::format("Could not read service data from {}", missing_file)); } auto no_node_data = config; @@ -555,7 +541,7 @@ TEST_CASE("Startup inputs are resolved by start type") CHECK( logic_error_message([&]() { resolve_startup_inputs(no_node_data, type); - }) == std::format("Could not read node data from {}", missing_file)); + }) == fmt::format("Could not read node data from {}", missing_file)); } } } @@ -634,323 +620,6 @@ TEST_CASE("Self certificate authentication") CHECK(error_reason.contains("before certificate's Not Before")); } -TEST_CASE("Node state is explicitly nontransactional metadata") -{ - class MinimalNodeState : public ccf::AbstractNodeState - { - ccf::CCFConfig config = {}; - nlohmann::json node_data = nullptr; - - public: - void transition_service_to_open( - ccf::kv::Tx&, AbstractGovernanceEffects::ServiceIdentities) override - { - throw std::logic_error("Unimplemented"); - } - - bool rekey_ledger(ccf::kv::Tx&) override - { - throw std::logic_error("Unimplemented"); - } - - void trigger_recovery_shares_refresh(ccf::kv::Tx&) override - { - throw std::logic_error("Unimplemented"); - } - - void trigger_ledger_chunk(ccf::kv::Tx&) override - { - throw std::logic_error("Unimplemented"); - } - - void trigger_snapshot(ccf::kv::Tx&) override - { - throw std::logic_error("Unimplemented"); - } - - [[nodiscard]] bool is_in_initialised_state() const override - { - return false; - } - - [[nodiscard]] bool is_part_of_public_network() const override - { - return false; - } - - [[nodiscard]] bool is_primary() const override - { - return false; - } - - bool can_replicate() override - { - return false; - } - - std::optional get_primary() override - { - return std::nullopt; - } - - [[nodiscard]] bool is_reading_public_ledger() const override - { - return false; - } - - [[nodiscard]] bool is_reading_private_ledger() const override - { - return false; - } - - [[nodiscard]] bool is_part_of_network() const override - { - return false; - } - - ccf::kv::Version get_last_recovered_signed_idx() override - { - return 0; - } - - void initiate_private_recovery(ccf::kv::Tx&) override - { - throw std::logic_error("Unimplemented"); - } - - ExtendedState state() override - { - return {NodeStartupState::uninitialized, std::nullopt, std::nullopt}; - } - - QuoteVerificationResult verify_quote( - ccf::kv::ReadOnlyTx&, - const QuoteInfo&, - const std::vector&, - pal::PlatformAttestationMeasurement&, - const std::optional>&, - std::shared_ptr) override - { - throw std::logic_error("Unimplemented"); - } - - ccf::kv::Version get_startup_snapshot_seqno() override - { - return 0; - } - - SessionMetrics get_session_metrics() override - { - return {}; - } - - ccf::crypto::Pem get_self_signed_certificate() override - { - return {}; - } - - const ccf::COSESignaturesConfig& get_cose_signatures_config() override - { - throw std::logic_error("Unimplemented"); - } - - RecoveryDecisionProtocolSubsystem& get_recovery_decision_protocol() override - { - throw std::logic_error("Unimplemented"); - } - - void shuffle_sealed_shares(ccf::kv::Tx&) override - { - throw std::logic_error("Unimplemented"); - } - - [[nodiscard]] const ccf::CCFConfig& get_node_config() const override - { - return config; - } - - [[nodiscard]] const nlohmann::json& get_node_data() const override - { - return node_data; - } - - ccf::crypto::Pem get_network_cert() override - { - return {}; - } - - void stop_notice() override {} - - bool has_received_stop_notice() override - { - return false; - } - - bool is_member_frontend_open() override - { - return false; - } - - bool is_user_frontend_open() override - { - return false; - } - - [[nodiscard]] bool is_accessible_to_members() const override - { - return false; - } - - std::shared_ptr get_store() override - { - return nullptr; - } - }; - - class RollbackingStore : public ccf::kv::Store - { - public: - std::function on_signature_lookup = nullptr; - - std::shared_ptr get_map( - ccf::kv::Version version, const std::string& name) override - { - if (name == Tables::SIGNATURES && on_signature_lookup != nullptr) - { - auto callback = std::exchange(on_signature_lookup, nullptr); - callback(); - } - return ccf::kv::Store::get_map(version, name); - } - }; - - NetworkState network; - auto store = std::make_shared(); - network.tables = store; - network.tables->set_encryptor(std::make_shared()); - auto consensus = std::make_shared(); - network.tables->set_consensus(consensus); - network.tables->initialise_term(2); - - auto publish_signature = [&](ccf::kv::Version reported_seqno) { - const auto txid = network.tables->next_txid().value(); - auto tx = network.tables->create_reserved_tx(txid); - tx.wo(Tables::SIGNATURES) - ->put( - ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, reported_seqno)); - tx.wo(Tables::SERIALISED_MERKLE_TREE)->put({}); - auto info = tx.commit_reserved(); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE( - network.tables->commit( - txid, - std::make_unique( - std::move(info.data), - std::move(info.claims_digest), - std::move(info.commit_evidence_digest), - std::move(info.hooks)), - true) == ccf::kv::CommitResult::SUCCESS); - }; - - // Record a higher signed seqno in the KV so pre-readiness checks fail if - // they accidentally read from the store instead of node progress metadata. - constexpr ccf::kv::Version kv_signed_seqno = 99; - publish_signature(kv_signed_seqno); - - MinimalNodeState node_state; - StubNodeContext context; - context.install_subsystem(std::make_shared( - node_state, NodeConfigurationSubsystem::InterfaceRegexes{})); - TestNodeRpcFrontend frontend(network, context); - frontend.open(); - - ::http::Request request("state", HTTP_GET); - auto session = std::make_shared( - ccf::InvalidSessionId, std::vector{}); - auto rpc_ctx = ccf::make_rpc_context(session, request.build_request()); - const auto endpoint = - frontend.get_node_endpoints().find_endpoint_without_kv(*rpc_ctx); - REQUIRE(endpoint != nullptr); - CHECK( - endpoint->execution_mode == ccf::endpoints::EndpointExecutionMode::Command); - CHECK( - endpoint->properties.forwarding_required == - ccf::endpoints::ForwardingRequired::Never); - CHECK(endpoint->authn_policies.empty()); - - for (const auto readiness : - {ccf::kv::StoreReadiness::Unavailable, - ccf::kv::StoreReadiness::InstallingSnapshot}) - { - network.tables->set_readiness(readiness); - context.node_operation->extended_state = { - NodeStartupState::readingPublicLedger, std::nullopt, std::nullopt}; - - for (const auto& [recovered, startup, expected] : std::vector< - std::tuple>{ - {25, 10, 25}, {10, 40, 40}}) - { - context.node_operation->last_recovered_signed_idx = recovered; - context.node_operation->startup_snapshot_seqno = startup; - - const auto response = - frontend_process(frontend, nullptr, "state", {}, HTTP_GET); - REQUIRE(response.status == HTTP_STATUS_OK); - CHECK_FALSE(response.headers.contains(ccf::http::headers::CCF_TX_ID)); - - const auto out = parse_response_body(response); - CHECK(out.state == NodeStartupState::readingPublicLedger); - CHECK(out.startup_seqno == startup); - CHECK(out.last_signed_seqno == expected); - } - } - - network.tables->set_readiness(ccf::kv::StoreReadiness::Ready); - context.node_operation->extended_state = { - NodeStartupState::partOfNetwork, std::nullopt, std::nullopt}; - context.node_operation->last_recovered_signed_idx = 0; - context.node_operation->startup_snapshot_seqno = 10; - - const auto response = - frontend_process(frontend, nullptr, "state", {}, HTTP_GET); - REQUIRE(response.status == HTTP_STATUS_OK); - CHECK_FALSE(response.headers.contains(ccf::http::headers::CCF_TX_ID)); - const auto out = parse_response_body(response); - CHECK(out.state == NodeStartupState::partOfNetwork); - CHECK(out.startup_seqno == 10); - CHECK(out.last_signed_seqno == kv_signed_seqno); - - // Regression: if readiness flips to Ready after RpcFrontend enters - // process_command_without_kv(), a concurrent rollback during get_state()'s - // signature lookup throws CompactedVersionConflict (not a std::exception). - // The frontend must catch and retry it rather than terminating the node. - constexpr ccf::kv::Version post_rollback_seqno = 105; - bool transitioned_to_ready = false; - bool rollback_triggered = false; - network.tables->set_readiness(ccf::kv::StoreReadiness::Unavailable); - context.node_operation->on_state = [&]() { - transitioned_to_ready = true; - network.tables->set_readiness(ccf::kv::StoreReadiness::Ready); - context.node_operation->on_state = nullptr; - }; - store->on_signature_lookup = [&]() { - rollback_triggered = true; - network.tables->rollback({2, 0}, 3); - consensus->view_history.rollback(0); - consensus->flush(); - publish_signature(post_rollback_seqno); - }; - - const auto raced_response = - frontend_process(frontend, nullptr, "state", {}, HTTP_GET); - CHECK(transitioned_to_ready); - CHECK(rollback_triggered); - REQUIRE(raced_response.status == HTTP_STATUS_OK); - CHECK_FALSE(raced_response.headers.contains(ccf::http::headers::CCF_TX_ID)); - const auto raced_out = parse_response_body(raced_response); - CHECK(raced_out.last_signed_seqno == post_rollback_seqno); -} - TEST_CASE("Pending-node cleanup uses renewed client certificates") { NetworkState network; @@ -1006,13 +675,6 @@ TEST_CASE("Pending-node cleanup uses renewed client certificates") TEST_CASE("Add a node to an opening service") { - auto id_format = IdentityIdFormat::SHA256; - SUBCASE("Legacy node ID") {} - SUBCASE("DID node ID") - { - id_format = IdentityIdFormat::DIDKey; - } - NetworkState network; auto tx_encryptor = std::make_shared(); network.tables->set_encryptor(tx_encryptor); @@ -1042,9 +704,8 @@ TEST_CASE("Add a node to an opening service") INFO("Add first node before a service exists"); { JoinNetworkNodeToNode::In join_input; - join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = true; + join_input.mldsa_supported = ccf::crypto::mldsa_supported(); const auto response = frontend_process(frontend, join_input, "join", caller); @@ -1058,11 +719,15 @@ TEST_CASE("Add a node to an opening service") auto tx = network.tables->create_tx(); INFO("A service with an ML-DSA identity only admits ML-DSA capable nodes"); - REQUIRE(network.identity->pq_cert.has_value()); + REQUIRE( + network.identity->pq_cert.has_value() == ccf::crypto::mldsa_supported()); + // Without ML-DSA the service has no such identity, and the main flow below + // shows that a joiner declaring no support is then accepted + if (ccf::crypto::mldsa_supported()) { auto pk_der = node_kp->public_key_der(); const NodeId joiner_node_id = ccf::crypto::Sha256Hash(pk_der).hex_str(); - // Nodes that declare no ML-DSA support, and nodes that predate the field + // Nodes of this build without ML-DSA, and nodes that predate the field const std::vector> incapable = {false, std::nullopt}; for (const auto& declared : incapable) { @@ -1079,48 +744,11 @@ TEST_CASE("Add a node to an opening service") } } - const NodeId tls_peer{std::string(64, '1')}; - const std::map expected_tls_addresses{ - {tls_peer, "tls-peer.example:8082"}}; - { - auto peers_tx = network.tables->create_tx(); - auto* peers = peers_tx.rw(network.nodes); - const auto add_peer = [peers, &node_public_encryption_key]( - const NodeId& id, - NodeStatus status, - const std::optional& tls_address) { - NodeInfo info; - info.encryption_pub_key = node_public_encryption_key; - info.status = status; - info.node_to_node_interface.published_address = - std::format("{}.example:8081", id.value()); - if (tls_address.has_value()) - { - info.node_to_node_tls_interface = NodeInfoNetwork::NodeToNodeInterface{ - "localhost:8082", tls_address.value()}; - } - peers->put(id, info); - }; - add_peer( - tls_peer, NodeStatus::TRUSTED, expected_tls_addresses.at(tls_peer)); - add_peer(NodeId{std::string(64, '2')}, NodeStatus::TRUSTED, std::nullopt); - add_peer( - NodeId{std::string(64, '3')}, - NodeStatus::PENDING, - "pending-peer.example:8082"); - add_peer( - NodeId{std::string(64, '4')}, - NodeStatus::RETIRED, - "retired-peer.example:8082"); - REQUIRE(peers_tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - INFO("Add first node which should be trusted straight away"); { JoinNetworkNodeToNode::In join_input; - join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = true; + join_input.mldsa_supported = ccf::crypto::mldsa_supported(); // Join input does not include CSR (1.x) join_input.certificate_signing_request = std::nullopt; @@ -1134,14 +762,11 @@ TEST_CASE("Add a node to an opening service") CHECK(response.network_info.has_value()); CHECK(response.network_info->identity == *network.identity.get()); CHECK(response.network_info->public_only == false); - CHECK( - response.network_info->node_to_node_tls_addresses == - expected_tls_addresses); // No endorsed certificate since no CSR was passed in CHECK(response.network_info->endorsed_certificate == std::nullopt); - const auto joiner_node_id = compute_node_id_from_kp(node_kp, id_format); - CHECK(response.node_id == joiner_node_id); + auto pk_der = node_kp->public_key_der(); + const NodeId joiner_node_id = ccf::crypto::Sha256Hash(pk_der).hex_str(); auto nodes = tx.rw(network.nodes); auto node_info = nodes->get(joiner_node_id); @@ -1150,30 +775,6 @@ TEST_CASE("Add a node to an opening service") CHECK(node_kp->public_key_pem() == node_info->public_key); } - INFO("A key outside the did:key profile cannot request a DID node ID"); - { - const auto eddsa_kp = - ccf::crypto::make_eddsa_key_pair(ccf::crypto::CurveID::CURVE25519); - const auto unsupported_caller = ccf::crypto::create_endorsed_cert( - eddsa_kp->public_key_pem(), - "CN=Unsupported Joiner", - {}, - valid_from, - valid_to, - node_kp->private_key_pem(), - caller); - JoinNetworkNodeToNode::In join_input; - join_input.id_format = IdentityIdFormat::DIDKey; - join_input.public_encryption_key = node_public_encryption_key; - const auto response = - frontend_process(frontend, join_input, "join", unsupported_caller); - check_error(response, HTTP_STATUS_BAD_REQUEST); - check_error_message( - response, "cannot be identified in the requested format"); - auto verify_tx = network.tables->create_tx(); - CHECK(verify_tx.ro(network.nodes)->size() == 5); - } - INFO("Adding the same node should return the same result"); { // Even if rekey occurs in between, the same ledger secrets should be @@ -1182,14 +783,10 @@ TEST_CASE("Add a node to an opening service") up_to_ledger_secret_seqno + 1, make_ledger_secret()); JoinNetworkNodeToNode::In join_input; - join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = true; + join_input.mldsa_supported = ccf::crypto::mldsa_supported(); - const auto replacement = - node_kp->self_sign("CN=Replacement", valid_from, valid_to); - auto http_response = - frontend_process(frontend, join_input, "join", replacement); + auto http_response = frontend_process(frontend, join_input, "join", caller); CHECK(http_response.status == HTTP_STATUS_OK); const auto response = @@ -1201,9 +798,6 @@ TEST_CASE("Add a node to an opening service") response.network_info->ledger_secrets, network.ledger_secrets->get(tx, up_to_ledger_secret_seqno)); CHECK(response.network_info->identity == *network.identity.get()); - CHECK( - response.network_info->node_to_node_tls_addresses == - expected_tls_addresses); } INFO( @@ -1217,7 +811,7 @@ TEST_CASE("Add a node to an opening service") // Network node info is empty (same as before) JoinNetworkNodeToNode::In join_input; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = true; + join_input.mldsa_supported = ccf::crypto::mldsa_supported(); auto http_response = frontend_process(frontend, join_input, "join", new_caller); @@ -1276,13 +870,6 @@ TEST_CASE("JWT refresh metrics are thread-safe") TEST_CASE("Add a node to an open service") { - auto id_format = IdentityIdFormat::SHA256; - SUBCASE("Legacy node ID") {} - SUBCASE("DID node ID") - { - id_format = IdentityIdFormat::DIDKey; - } - NetworkState network; auto gen_tx = network.tables->create_tx(); auto tx_encryptor = std::make_shared(); @@ -1327,9 +914,8 @@ TEST_CASE("Add a node to an open service") ccf::crypto::make_ec_key_pair()->public_key_pem(); JoinNetworkNodeToNode::In join_input; - join_input.id_format = id_format; join_input.public_encryption_key = node_public_encryption_key; - join_input.mldsa_supported = true; + join_input.mldsa_supported = ccf::crypto::mldsa_supported(); join_input.certificate_signing_request = node_kp->create_csr("CN=Joiner"); INFO("Add node once service is open"); @@ -1343,8 +929,8 @@ TEST_CASE("Add a node to an open service") CHECK(!response.network_info.has_value()); - const auto joiner_node_id = compute_node_id_from_kp(node_kp, id_format); - CHECK(response.node_id == joiner_node_id); + auto pk_der = node_kp->public_key_der(); + const NodeId joiner_node_id = ccf::crypto::Sha256Hash(pk_der).hex_str(); auto nodes = tx.rw(network.nodes); auto node_info = nodes->get(joiner_node_id); CHECK(node_info.has_value()); @@ -1363,7 +949,7 @@ TEST_CASE("Add a node to an open service") // Network node info is empty (same as before) JoinNetworkNodeToNode::In other_join_input; other_join_input.public_encryption_key = node_public_encryption_key; - other_join_input.mldsa_supported = true; + other_join_input.mldsa_supported = ccf::crypto::mldsa_supported(); auto http_response = frontend_process(frontend, other_join_input, "join", new_caller); @@ -1389,7 +975,7 @@ TEST_CASE("Add a node to an open service") { auto tx = network.tables->create_tx(); // In a real scenario, nodes are trusted via member governance. - auto joining_node_id = ccf::compute_node_id_from_kp(node_kp, id_format); + auto joining_node_id = ccf::compute_node_id_from_kp(node_kp); InternalTablesAccess::trust_node( tx, joining_node_id, network.ledger_secrets->get_latest(tx).first); const auto dummy_endorsed_certificate = @@ -1444,7 +1030,7 @@ TEST_CASE("Add a node to an open service") JoinNetworkNodeToNode::In expired_join_input; expired_join_input.public_encryption_key = ccf::crypto::make_ec_key_pair()->public_key_pem(); - expired_join_input.mldsa_supported = true; + expired_join_input.mldsa_supported = ccf::crypto::mldsa_supported(); expired_join_input.certificate_signing_request = expired_node_kp->create_csr("CN=Expired Joiner"); expired_join_input.node_info_network.node_to_node_interface @@ -1558,8 +1144,7 @@ TEST_CASE("Add a node to an open service") std::chrono::duration_cast( std::chrono::hours(2)) .count(); - const auto trusted_node_id = - ccf::compute_node_id_from_kp(node_kp, id_format); + const auto trusted_node_id = ccf::compute_node_id_from_kp(node_kp); set_last_seen(expired_node_id, expired); set_last_seen(trusted_node_id, expired); @@ -1615,7 +1200,7 @@ TEST_CASE("File range parsing preserves half-open bounds") {"bytes=99-99", 100, 99, 100}, {"bytes=0-100", 100, 0, 100}, {"bytes=10-100", 100, 10, 100}, - {std::format("bytes=0-{}", max), 100, 0, 100}, + {fmt::format("bytes=0-{}", max), 100, 0, 100}, {"bytes=0-", 100, 0, 100}, {"bytes=10-", 100, 10, 100}, {"bytes=99-", 100, 99, 100}, @@ -1623,7 +1208,7 @@ TEST_CASE("File range parsing preserves half-open bounds") {"bytes=-20", 100, 80, 100}, {"bytes=-100", 100, 0, 100}, {"bytes=-101", 100, 0, 100}, - {std::format("bytes=-{}", max), 100, 0, 100}, + {fmt::format("bytes=-{}", max), 100, 0, 100}, {"bytes=010-019", 100, 10, 20}, {"bytes=10x-19y", 100, 10, 20}, {"bytes=10 -19 ", 100, 10, 20}, @@ -1637,12 +1222,12 @@ TEST_CASE("File range parsing preserves half-open bounds") {"bytes=100-100", 100, 100, 100}, {"bytes=0-0", 1, 0, 1}, {"bytes=-1", 1, 0, 1}, - {std::format("bytes=0-{}", max), max, 0, max}, - {std::format("bytes={}-{}", max - 1, max), max, max - 1, max}, - {std::format("bytes={}-", max - 1), max, max - 1, max}, - {std::format("bytes=-{}", max), max, 0, max}, - {std::format("bytes={}-", max), max, max, max}, - {std::format("bytes={}-{}", max, max), max, max, max}}; + {fmt::format("bytes=0-{}", max), max, 0, max}, + {fmt::format("bytes={}-{}", max - 1, max), max, max - 1, max}, + {fmt::format("bytes={}-", max - 1), max, max - 1, max}, + {fmt::format("bytes=-{}", max), max, 0, max}, + {fmt::format("bytes={}-", max), max, max, max}, + {fmt::format("bytes={}-{}", max, max), max, max, max}}; for (const auto& test : cases) { @@ -1697,18 +1282,18 @@ TEST_CASE("File range parsing preserves exact errors") {"bytes=101-foo", "Start of range 101 is larger than total file size 100"}, {"bytes=50-48", "Invalid range: Start (50) and end (49) out of order"}, {"bytes=99-0", "Invalid range: Start (99) and end (1) out of order"}, - {std::format("bytes={}-", overflow), - std::format( + {fmt::format("bytes={}-", overflow), + fmt::format( "Unable to parse start of range value {} in bytes={}-", overflow, overflow)}, - {std::format("bytes=0-{}", overflow), - std::format( + {fmt::format("bytes=0-{}", overflow), + fmt::format( "Unable to parse end of range value {} in bytes=0-{}", overflow, overflow)}, - {std::format("bytes=-{}", overflow), - std::format( + {fmt::format("bytes=-{}", overflow), + fmt::format( "Unable to parse end of range offset value {} in bytes=-{}", overflow, overflow)}}; @@ -1748,7 +1333,7 @@ TEST_CASE("File range responses preserve GET and HEAD metadata") {"bytes=10-", 10, 100}, {"bytes=-20", 80, 100}, {"bytes=-101", 0, 100}, - {std::format("bytes=0-{}", std::numeric_limits::max()), 0, 100}, + {fmt::format("bytes=0-{}", std::numeric_limits::max()), 0, 100}, {"bytes=10junk-19junk", 10, 20}}; for (const auto& test : cases) @@ -1787,7 +1372,7 @@ TEST_CASE("File range responses preserve GET and HEAD metadata") { CHECK( headers.at(ccf::http::headers::CONTENT_RANGE) == - std::format("bytes {}-{}/100", test.start, test.end - 1)); + fmt::format("bytes {}-{}/100", test.start, test.end - 1)); } else { @@ -1797,7 +1382,7 @@ TEST_CASE("File range responses preserve GET and HEAD metadata") bytes.begin() + test.start, bytes.begin() + test.end); CHECK( headers.at(ccf::http::headers::ETAG) == - std::format( + fmt::format( "\"{}\"", ccf::node::format_repr_digest( "sha-256", @@ -1942,11 +1527,11 @@ TEST_CASE( const std::vector matches = { "*", etag, - std::format( + fmt::format( "\"{}\"", ccf::node::format_repr_digest( "sha-384", ccf::crypto::MDType::SHA384, body.data(), body.size())), - std::format( + fmt::format( "\"{}\"", ccf::node::format_repr_digest( "sha-512", ccf::crypto::MDType::SHA512, body.data(), body.size()))}; @@ -1998,7 +1583,7 @@ TEST_CASE( etag); for (const auto& invalid_match : - std::vector{"not etags", std::format("W/{}", etag)}) + std::vector{"not etags", fmt::format("W/{}", etag)}) { headers[ccf::http::headers::IF_NONE_MATCH] = invalid_match; const auto invalid_response = diff --git a/src/node/test/historical_queries.cpp b/src/node/test/historical_queries.cpp index 99be84e5b2f7..7cd5f97bc5eb 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -8,7 +8,6 @@ #include "node/historical_queries.h" #include "ccf/crypto/rsa_key_pair.h" -#include "ccf/ds/join.h" #include "ccf/ds/locking.h" #include "ccf/receipt.h" #include "consensus/test/ledger_stub.h" @@ -23,9 +22,7 @@ #include "node/signature_cache_subsystem.h" #include -#include #include -#include #include #include #include @@ -50,9 +47,7 @@ struct TestState std::shared_ptr service_kp = nullptr; }; -TestState create_and_init_state( - bool initialise_ledger_rekey = true, - ccf::crypto::MLDSAKeyPairPtr pq_service_kp = nullptr) +TestState create_and_init_state(bool initialise_ledger_rekey = true) { TestState ts; @@ -71,7 +66,7 @@ TestState create_and_init_state( std::make_shared(*ts.kv_store, node_id, *ts.node_kp); h->set_endorsed_certificate({}); h->set_service_signing_identity( - ts.service_kp, std::move(pq_service_kp), ccf::COSESignaturesConfig{}); + ts.service_kp, nullptr, ccf::COSESignaturesConfig{}); ts.kv_store->set_history(h); ts.kv_store->initialise_term(2); @@ -1807,7 +1802,6 @@ TEST_CASE("Historical receipts preserve the transaction view across signatures") ccf::NodeId{"node_id"}, *state.node_kp, *state.service_kp, - nullptr, cert, history->get_cose_signatures_config(), signing_mode), @@ -1965,94 +1959,39 @@ TEST_CASE("Historical cache rejects signatures which misreport their TxID") // Write a signature transaction by hand, which declares a TxID in a later // view than the one it is actually committed in - const auto signature_txid = store.next_txid().value(); - const auto signature_seqno = signature_txid.seqno; - const ccf::TxID declared_id{signature_txid.view + 1, signature_seqno}; + const auto signature_seqno = store.current_version() + 1; + const ccf::TxID declared_id{store.current_txid().view + 1, signature_seqno}; { - class MisreportedSignatureTx : public ccf::kv::PendingTx + auto tx = store.create_tx(); + const auto root = history->get_replicated_state_root(); + const std::vector root_hash(root.h.begin(), root.h.end()); + if (signing_mode == ccf::LedgerSignMode::Dual) { - ccf::kv::Store& store; - ccf::TxID txid; - ccf::TxID declared_id; - ccf::LedgerSignMode signing_mode; - ccf::crypto::Sha256Hash root; - std::vector serialised_tree; - ccf::crypto::ECKeyPairPtr node_kp; - ccf::crypto::Pem node_cert; - ccf::crypto::ECKeyPairPtr service_kp; - ccf::COSESignaturesConfig cose_config; - - public: - MisreportedSignatureTx( - ccf::kv::Store& store_, - ccf::TxID txid_, - ccf::TxID declared_id_, - ccf::LedgerSignMode signing_mode_, - ccf::crypto::Sha256Hash root_, - std::vector serialised_tree_, - ccf::crypto::ECKeyPairPtr node_kp_, - ccf::crypto::Pem node_cert_, - ccf::crypto::ECKeyPairPtr service_kp_, - ccf::COSESignaturesConfig cose_config_) : - store(store_), - txid(txid_), - declared_id(declared_id_), - signing_mode(signing_mode_), - root(root_), - serialised_tree(std::move(serialised_tree_)), - node_kp(std::move(node_kp_)), - node_cert(std::move(node_cert_)), - service_kp(std::move(service_kp_)), - cose_config(std::move(cose_config_)) - {} - - ccf::kv::PendingTxInfo call() override - { - auto tx = store.create_reserved_tx(txid); - const std::vector root_hash(root.h.begin(), root.h.end()); - if (signing_mode == ccf::LedgerSignMode::Dual) - { - tx.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature( - ccf::NodeId{"node_id"}, - declared_id.seqno, - declared_id.view, - root, - {}, - node_kp->sign_hash(root_hash.data(), root_hash.size()), - node_cert)); - } - tx.wo(ccf::Tables::COSE_SIGNATURES) - ->put( - ccf::IdentityType::CLASSICAL, - ccf::cose::sign_ledger( - *service_kp, - ccf::crypto::kid_from_key(service_kp->public_key_der()), - 0, - cose_config.issuer, - cose_config.subject, - declared_id.to_str(), - root_hash)); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put(serialised_tree); - return tx.commit_reserved(); - } - }; - - auto pending = std::make_unique( - store, - signature_txid, - declared_id, - signing_mode, - history->get_replicated_state_root(), - history->serialise_tree(signature_seqno - 1), - state.node_kp, - node_cert, - state.service_kp, - history->get_cose_signatures_config()); - REQUIRE( - store.commit(signature_txid, std::move(pending), true) == - ccf::kv::CommitResult::SUCCESS); + tx.wo(ccf::Tables::SIGNATURES) + ->put(ccf::PrimarySignature( + ccf::NodeId{"node_id"}, + declared_id.seqno, + declared_id.view, + root, + {}, + state.node_kp->sign_hash(root_hash.data(), root_hash.size()), + node_cert)); + } + const auto& cose_config = history->get_cose_signatures_config(); + tx.wo(ccf::Tables::COSE_SIGNATURES) + ->put( + ccf::IdentityType::CLASSICAL, + ccf::cose::sign_ledger( + *state.service_kp, + ccf::crypto::kid_from_key(state.service_kp->public_key_der()), + 0, + cose_config.issuer, + cose_config.subject, + declared_id.to_str(), + root_hash)); + tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) + ->put(history->serialise_tree(signature_seqno - 1)); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } const auto signature_id = store.current_txid(); REQUIRE(signature_id.seqno == signature_seqno); @@ -2228,13 +2167,13 @@ TEST_CASE("StateCache point queries") cache.drop_cached_states(low_handle); cache.drop_cached_states(high_handle); - INFO(std::format( + INFO(fmt::format( "Signature transactions can be requested between {} and {}", low_signature_transaction, high_signature_transaction)); for (const auto i : {low_signature_transaction, high_signature_transaction}) { - INFO(std::format("Requesting signature at {}", i)); + INFO(fmt::format("Requesting signature at {}", i)); auto state_at_seqno = cache.get_state_at(default_handle, i); REQUIRE(state_at_seqno == nullptr); @@ -2243,7 +2182,7 @@ TEST_CASE("StateCache point queries") state_at_seqno = cache.get_state_at(default_handle, i); REQUIRE(state_at_seqno != nullptr); - INFO(std::format("Receipt for transaction at {}", i)); + INFO(fmt::format("Receipt for transaction at {}", i)); REQUIRE(state_at_seqno->receipt.get() != nullptr); } @@ -3248,13 +3187,13 @@ namespace size_t i, const std::vector& previously_requested) { - std::cout << std::format( + std::cout << fmt::format( "Thread <{}>, i [{}]: {} - still no answer!", handle, i, previously_requested.back()) << std::endl; - std::cout << std::format( + std::cout << fmt::format( "I've previously used handle {} to request:", handle) << std::endl; for (const auto& s : previously_requested) @@ -3405,7 +3344,7 @@ namespace // Fetch a single point const auto target_seqno = random_seqno(); previously_requested.push_back( - std::format("Point {} [{}]", target_seqno, ss)); + fmt::format("Point {} [{}]", target_seqno, ss)); if (store_or_state) { query_random_point_store(target_seqno, handle, error_printer); @@ -3426,7 +3365,7 @@ namespace std::swap(range_start, range_end); } previously_requested.push_back( - std::format("Range {}->{} [{}]", range_start, range_end, ss)); + fmt::format("Range {}->{} [{}]", range_start, range_end, ss)); if (store_or_state) { query_random_range_stores( @@ -3463,11 +3402,11 @@ namespace for (const auto& [from, additional] : seqnos.get_ranges()) { range_descriptions.push_back( - std::format("{}->{}", from, from + additional)); + fmt::format("{}->{}", from, from + additional)); } - previously_requested.push_back(std::format( - "Ranges {} [{}]", ccf::ds::join(range_descriptions, ", "), ss)); + previously_requested.push_back(fmt::format( + "Ranges {} [{}]", fmt::join(range_descriptions, ", "), ss)); if (store_or_state) { @@ -3642,17 +3581,17 @@ TEST_CASE("StateCache concurrent access") } }; { - messages.push_back(std::format( + messages.push_back(fmt::format( "Handle {} requested stores (no sigs) from 3 to 8", handle_a)); queries.query_random_range_stores(3, 8, handle_a, error_printer); } { - messages.push_back(std::format( + messages.push_back(fmt::format( "Handle {} requested states (with sigs) from 5 to 8", handle_b)); queries.query_random_range_states(5, 8, handle_b, error_printer); } { - messages.push_back(std::format( + messages.push_back(fmt::format( "Handle {} requested states (with sigs) from 3 to 8", handle_b)); queries.query_random_range_states(3, 8, handle_b, error_printer); } @@ -4126,8 +4065,7 @@ TEST_CASE( for (const auto& written_signatures : signature_transactions) { - const auto txid = store.next_txid().value(); - auto tx = store.create_reserved_tx(txid); + auto tx = store.create_tx(); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); for (const auto& [identity_type, signature] : written_signatures) { @@ -4135,22 +4073,12 @@ TEST_CASE( } tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({}); - auto info = tx.commit_reserved(); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE( - store.commit( - txid, - std::make_unique( - std::move(info.data), - std::move(info.claims_digest), - std::move(info.commit_evidence_digest), - std::move(info.hooks)), - true) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - REQUIRE(store.current_txid() == txid); + const auto txid = store.current_txid(); INFO("Signature transaction: ", txid.to_str()); { - auto read_tx = store.create_read_only_tx_at_replicated_state(); + auto read_tx = store.create_read_only_tx(); REQUIRE( read_tx.ro(ccf::Tables::COSE_SIGNATURES)->size() == 2); @@ -4182,7 +4110,7 @@ TEST_CASE( } } -TEST_CASE("COSE receipt descriptions: _v1 are CLASSICAL, _v2 take the type") +TEST_CASE("Legacy COSE receipt descriptions select CLASSICAL, not PQ") { const ccf::CoseSignature classical_signature{1, 2, 3}; const ccf::CoseSignature pq_signature{4, 5, 6}; @@ -4196,115 +4124,15 @@ TEST_CASE("COSE receipt descriptions: _v1 are CLASSICAL, _v2 take the type") std::nullopt); REQUIRE(ccf::describe_cose_signature_v1(receipt) == classical_signature); - REQUIRE( - ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::CLASSICAL) == - classical_signature); - REQUIRE( - ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::PQ) == - pq_signature); REQUIRE( ccf::historical::select_described_cose_signature(receipt.cose_signatures) == classical_signature); - INFO("Endorsements are described for the identity types which have them"); - const ccf::CoseEndorsementsChain classical_endorsements{{7}, {8}}; - const ccf::CoseEndorsementsChain pq_endorsements{{9}}; - REQUIRE_FALSE(ccf::describe_cose_endorsements_v1(receipt).has_value()); - receipt.cose_endorsements[ccf::IdentityType::CLASSICAL] = - classical_endorsements; - REQUIRE( - ccf::describe_cose_endorsements_v1(receipt) == classical_endorsements); - REQUIRE_FALSE( - ccf::describe_cose_endorsements_v2(receipt, ccf::IdentityType::PQ) - .has_value()); - receipt.cose_endorsements[ccf::IdentityType::PQ] = pq_endorsements; - REQUIRE( - ccf::describe_cose_endorsements_v2(receipt, ccf::IdentityType::PQ) == - pq_endorsements); - REQUIRE( - ccf::describe_cose_endorsements_v1(receipt) == classical_endorsements); - receipt.cose_signatures.erase(ccf::IdentityType::CLASSICAL); REQUIRE_FALSE(ccf::describe_cose_signature_v1(receipt).has_value()); - REQUIRE( - ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::PQ) == - pq_signature); REQUIRE_FALSE( ccf::historical::select_described_cose_signature(receipt.cose_signatures) .has_value()); - - receipt.cose_signatures.erase(ccf::IdentityType::PQ); - REQUIRE_FALSE(ccf::describe_cose_signature_v2(receipt, ccf::IdentityType::PQ) - .has_value()); -} - -TEST_CASE("Historical receipts carry a COSE receipt of each identity type") -{ - const auto pq_service_kp = - ccf::crypto::make_mldsa_key_pair(ccf::crypto::MLDSAParameterSet::ML_DSA_65); - auto state = create_and_init_state(true, pq_service_kp); - auto& store = *state.kv_store; - - const auto seqno = write_transactions(store, 1); - const auto signature_seqno = write_transactions_and_signature(store, 0); - REQUIRE(signature_seqno == seqno + 1); - - auto ledger = construct_host_ledger(store.get_consensus()); - ccf::historical::StateCache cache( - store, - state.ledger_secrets, - std::make_shared()); - REQUIRE(cache.get_state_range(0, seqno, signature_seqno).empty()); - cache.tick(std::chrono::milliseconds(0)); - REQUIRE(cache.handle_ledger_entry(seqno, ledger.at(seqno))); - REQUIRE( - cache.handle_ledger_entry(signature_seqno, ledger.at(signature_seqno))); - const auto states = cache.get_state_range(0, seqno, signature_seqno); - REQUIRE(states.size() == 2); - REQUIRE(states[0]->receipt != nullptr); - const auto& receipt = *states[0]->receipt; - - const auto classical_receipt = ccf::describe_cose_receipt_v1(receipt); - const auto pq_receipt = - ccf::describe_cose_receipt_v2(receipt, ccf::IdentityType::PQ); - REQUIRE(classical_receipt.has_value()); - REQUIRE(pq_receipt.has_value()); - REQUIRE( - ccf::describe_cose_receipt_v2(receipt, ccf::IdentityType::CLASSICAL) == - classical_receipt); - - INFO("Both receipts prove the transaction against the same signed root"); - const auto decoded_classical = - ccf::cose::decode_ccf_receipt(classical_receipt.value(), true); - const auto decoded_pq = - ccf::cose::decode_ccf_receipt(pq_receipt.value(), true); - REQUIRE(decoded_pq.merkle_root == decoded_classical.merkle_root); - REQUIRE(decoded_pq.phdr.ccf.txid == decoded_classical.phdr.ccf.txid); - REQUIRE(decoded_pq.phdr.alg == ccf::cose::alg::ML_DSA_65); - REQUIRE( - std::string(decoded_pq.phdr.kid.begin(), decoded_pq.phdr.kid.end()) == - ccf::crypto::kid_from_key(pq_service_kp->public_key_der())); - - INFO("Each receipt is signed by the service key of its identity type"); - const auto classical_verifier = ccf::crypto::make_cose_verifier_from_key( - state.service_kp->public_key_pem()); - const auto pq_public_key = pq_service_kp->public_key_der(); - const auto pq_verifier = ccf::crypto::make_cose_verifier_from_key( - std::span(pq_public_key.data(), pq_public_key.size())); - REQUIRE(classical_verifier->verify_detached( - classical_receipt.value(), decoded_classical.merkle_root)); - REQUIRE( - pq_verifier->verify_detached(pq_receipt.value(), decoded_pq.merkle_root)); - REQUIRE_FALSE(pq_verifier->verify_detached( - classical_receipt.value(), decoded_classical.merkle_root)); - REQUIRE_FALSE(classical_verifier->verify_detached( - pq_receipt.value(), decoded_pq.merkle_root)); - - INFO("The signature transaction has a COSE signature of each type"); - REQUIRE(states[1]->receipt != nullptr); - REQUIRE( - ccf::describe_cose_signature_v2(*states[1]->receipt, ccf::IdentityType::PQ) - .has_value()); } // Opt-in: run with --test-case="StateCache tick scaling benchmark" --no-skip @@ -4343,7 +4171,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) constexpr size_t pending = 8; constexpr size_t ticks_per_sample = 200; constexpr size_t sample_count = 7; - std::cout << std::format( + fmt::print( "retained_requests,retained_stores,pending_fetches,tick_ns," "tick_and_mutations_ns,pending_visited,released_checked\n"); for (size_t retained : {0, 7300, 14600, 29200}) @@ -4403,7 +4231,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) REQUIRE(cache.store_slot_count() == 3 * retained + pending + 6); const auto work = cache.tick_work(); - std::cout << std::format( + fmt::print( "{},{},{},{:.0f},{:.0f},{},{}\n", retained, 3 * retained, @@ -4420,8 +4248,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) constexpr size_t retained = 7300; constexpr size_t ticks_per_sample = 200; constexpr size_t sample_count = 7; - std::cout << std::format( - "retained_requests,pending_fetches,tick_ns,pending_visited\n"); + fmt::print("retained_requests,pending_fetches,tick_ns,pending_visited\n"); for (size_t pending : {1, 10, 100, 1000}) { auto reader = std::make_shared(); @@ -4446,7 +4273,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) reader->writes.clear(); REQUIRE(cache.tick_work().pending_fetches_visited == pending); } - std::cout << std::format( + fmt::print( "{},{},{:.0f},{}\n", retained, pending, @@ -4458,8 +4285,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) SUBCASE("Expiring many requests at once") { constexpr size_t retained = 7300; - std::cout << std::format( - "retained_requests,due_requests,tick_ns,expired,released\n"); + fmt::print("retained_requests,due_requests,tick_ns,expired,released\n"); for (size_t due : {1, 100, 1000}) { auto reader = std::make_shared(); @@ -4483,7 +4309,7 @@ TEST_CASE("StateCache tick scaling benchmark" * doctest::skip()) REQUIRE(cache.request_count() == retained); REQUIRE(cache.store_slot_count() == 3 * retained); cache.check_no_expired_slots(); - std::cout << std::format( + fmt::print( "{},{},{:.0f},{},{}\n", retained, due, @@ -4574,7 +4400,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) SUBCASE("Fixed receipt consumers against growing retention") { constexpr size_t consumers = 4; - std::cout << std::format( + fmt::print( "retained,consumers,reply_ns,signature_reply_ns,new_get_ns," "renew_get_ns,range_mutation_ns,index_buckets,index_handles," "index_value_bytes,rss_kb,cache_rss_delta_kb,visited\n"); @@ -4617,7 +4443,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) REQUIRE(cache.drop_cached_states(mutation_handle)); cache.tick(0ms); cache.check_invariants(); - std::cout << std::format( + fmt::print( "{},{},{:.0f},{:.0f},{:.0f},{:.0f},{:.0f},{},{},{},{},{},{}\n", retained, consumers, @@ -4638,7 +4464,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) SUBCASE("Growing real receipt fan-out") { constexpr size_t retained = 7300; - std::cout << std::format( + fmt::print( "retained,consumers,reply_ns,signature_reply_ns,new_get_ns,visited\n"); for (size_t consumers : {1, 10, 100, 1000}) { @@ -4647,7 +4473,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) add_retained(cache, retained); const auto [reply_ns, signature_ns, get_ns] = measure_replies(cache, retained, consumers); - std::cout << std::format( + fmt::print( "{},{},{:.0f},{:.0f},{:.0f},{}\n", retained, consumers, @@ -4672,8 +4498,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) ccf::LedgerSecretsMap secrets; secrets.emplace(state.ledger_secrets->get_latest(tx)); recovered.ledger_secrets->restore_historical(std::move(secrets)); - std::cout << std::format( - "retained,secret_consumers,secret_reply_ns,visited\n"); + fmt::print("retained,secret_consumers,secret_reply_ns,visited\n"); auto measure_secret = [&](size_t retained, size_t consumers) { auto reader = std::make_shared(); BenchmarkCache cache( @@ -4693,7 +4518,7 @@ TEST_CASE("StateCache reply routing scaling benchmark" * doctest::skip()) REQUIRE(cache.secret_waiter_count(second_rekey) == 0); REQUIRE(cache.secret_waiter_count(first_rekey) == consumers); cache.check_invariants(); - std::cout << std::format( + fmt::print( "{},{},{:.0f},{}\n", retained, consumers, diff --git a/src/node/test/history.cpp b/src/node/test/history.cpp index 2d664aab97d9..a3752df021e4 100644 --- a/src/node/test/history.cpp +++ b/src/node/test/history.cpp @@ -9,6 +9,7 @@ #include "ccf/service/tables/nodes.h" #include "crypto/certs.h" #include "crypto/openssl/hash.h" +#include "crypto/openssl/mldsa_support.h" #include "ds/internal_logger.h" #include "kv/kv_types.h" #include "kv/null_encryptor.h" @@ -17,15 +18,12 @@ #include "service/tables/signatures.h" #include "service/tables/signing_identities.h" -#include - #define DOCTEST_CONFIG_IMPLEMENT #include #undef FAIL #include #include -#include #include #include #include @@ -81,161 +79,6 @@ class DummyConsensus : public ccf::kv::test::StubConsensus } }; -class CustomSignaturePendingTx : public ccf::kv::PendingTx -{ -public: - using WriteSignatures = std::function; - -private: - ccf::TxID txid; - ccf::kv::Store& store; - ccf::kv::TxHistory& history; - WriteSignatures write_signatures; - -public: - CustomSignaturePendingTx( - ccf::TxID txid_, - ccf::kv::Store& store_, - ccf::kv::TxHistory& history_, - WriteSignatures write_signatures_) : - txid(txid_), - store(store_), - history(history_), - write_signatures(std::move(write_signatures_)) - {} - - ccf::kv::PendingTxInfo call() override - { - auto tx = store.create_reserved_tx(txid); - write_signatures(tx, txid, history.get_replicated_state_root()); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put(history.serialise_tree(txid.seqno - 1)); - return tx.commit_reserved(); - } -}; - -template -ccf::CoseSignature sign_root( - const KeyPair& key, - const ccf::TxID& txid, - const ccf::crypto::Sha256Hash& root) -{ - return ccf::cose::sign_ledger( - key, - ccf::crypto::kid_from_key(key.public_key_der()), - 0, - "", - "", - txid.to_str(), - root.h); -} - -struct SigningFixture -{ - std::shared_ptr encryptor = - std::make_shared(); - ccf::crypto::ECKeyPairPtr node_kp = ccf::crypto::make_ec_key_pair(); - ccf::crypto::Pem node_cert = - node_kp->self_sign("CN=Node", valid_from, valid_to); - std::shared_ptr service_kp = - std::dynamic_pointer_cast( - ccf::crypto::make_ec_key_pair()); - ccf::crypto::Pem service_cert = - service_kp->self_sign("CN=Service", valid_from, valid_to); - ccf::crypto::MLDSAKeyPairPtr pq_service_kp; - std::optional pq_service_cert = std::nullopt; - - ccf::kv::Store primary_store; - ccf::kv::Store backup_store; - std::shared_ptr primary_history; - std::shared_ptr consensus; - - SigningFixture(ccf::crypto::MLDSAKeyPairPtr pq_service_kp_ = nullptr) : - pq_service_kp(std::move(pq_service_kp_)) - { - if (pq_service_kp != nullptr) - { - pq_service_cert = - pq_service_kp->self_sign("CN=Service", valid_from, valid_to); - } - - constexpr auto store_term = 2; - primary_store.set_encryptor(encryptor); - primary_history = std::make_shared( - primary_store, ccf::kv::test::PrimaryNodeId, *node_kp); - primary_history->set_endorsed_certificate(node_cert); - primary_history->set_service_signing_identity( - service_kp, pq_service_kp, ccf::COSESignaturesConfig{}); - primary_store.set_history(primary_history); - primary_store.initialise_term(store_term); - - backup_store.set_encryptor(encryptor); - backup_store.set_history(std::make_shared( - backup_store, ccf::kv::test::FirstBackupNodeId, *node_kp)); - backup_store.initialise_term(store_term); - backup_store.set_consensus(std::make_shared(nullptr)); - - consensus = std::make_shared(&backup_store); - primary_store.set_consensus(consensus); - - commit([this](ccf::kv::Tx& tx) { - ccf::NodeInfo node_info; - node_info.encryption_pub_key = node_kp->public_key_pem(); - node_info.cert = node_cert; - tx.wo(ccf::Tables::NODES) - ->put(ccf::kv::test::PrimaryNodeId, node_info); - }); - } - - void commit(const std::function& write) - { - auto tx = primary_store.create_tx(); - write(tx); - REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); - } - - void publish_service_keys() - { - commit([this](ccf::kv::Tx& tx) { - tx.wo(ccf::Tables::SERVICE) - ->put( - ccf::ServiceInfo{.cert = service_cert, .pq_cert = pq_service_cert}); - auto* identities = - tx.wo(ccf::Tables::SIGNING_IDENTITIES); - identities->put( - ccf::IdentityType::CLASSICAL, - ccf::signing_identity_from_cert(service_cert)); - if (pq_service_cert.has_value()) - { - identities->put( - ccf::IdentityType::PQ, - ccf::signing_identity_from_cert(pq_service_cert.value())); - } - }); - } - - std::optional emit_signature() - { - primary_history->emit_signature(); - return consensus->last_apply_result; - } - - std::optional emit_signature( - CustomSignaturePendingTx::WriteSignatures write_signatures) - { - const auto txid = primary_store.next_txid().value(); - primary_store.commit( - txid, - std::make_unique( - txid, primary_store, *primary_history, std::move(write_signatures)), - true); - return consensus->last_apply_result; - } -}; - TEST_CASE("Check signature verification") { auto encryptor = std::make_shared(); @@ -316,27 +159,12 @@ TEST_CASE("Check signature verification") INFO("Issue a bogus signature, rejected by verification on the backup"); { - const auto txid = primary_store.next_txid().value(); - auto txs = primary_store.create_reserved_tx(txid); - auto sigs = txs.wo(signatures); - ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, txid.seqno); - bogus.view = txid.view; - bogus.root = primary_history->get_replicated_state_root(); + auto txs = primary_store.create_tx(); + auto sigs = txs.rw(signatures); + ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, 0); bogus.sig = std::vector(256, 1); sigs->put(bogus); - txs.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put(primary_history->serialise_tree(txid.seqno - 1)); - auto info = txs.commit_reserved(); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE( - primary_store.commit( - txid, - std::make_unique( - std::move(info.data), - std::move(info.claims_digest), - std::move(info.commit_evidence_digest), - std::move(info.hooks)), - true) == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + REQUIRE(txs.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); } } @@ -454,13 +282,17 @@ TEST_CASE("Check signature verification with the signing identities table") TEST_CASE("Signing identity carries an ML-DSA key next to the classical key") { + if (!ccf::crypto::mldsa_supported()) + { + return; + } + auto encryptor = std::make_shared(); auto node_kp = ccf::crypto::make_ec_key_pair(); auto service_kp = std::dynamic_pointer_cast( ccf::crypto::make_ec_key_pair()); auto pq_service_kp = ccf::crypto::make_mldsa_key_pair(ccf::crypto::MLDSAParameterSet::ML_DSA_65); - const auto pq_public_key_der = pq_service_kp->public_key_der(); const auto self_signed = node_kp->self_sign("CN=Node", valid_from, valid_to); const auto service_cert = service_kp->self_sign("CN=Service", valid_from, valid_to); @@ -515,229 +347,14 @@ TEST_CASE("Signing identity carries an ML-DSA key next to the classical key") REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - INFO("Both signatures are emitted and verified on the backup"); + INFO("The classical signature is emitted and verified on the backup"); primary_history->emit_signature(); REQUIRE(consensus->last_apply_result == ccf::kv::ApplyResult::PASS_SIGNATURE); - auto tx = backup_store.create_read_only_tx_at_replicated_state(); + auto tx = backup_store.create_read_only_tx(); auto* cose_signatures = tx.ro(ccf::Tables::COSE_SIGNATURES); - const auto classical_signature = - cose_signatures->get(ccf::IdentityType::CLASSICAL); - const auto pq_signature = cose_signatures->get(ccf::IdentityType::PQ); - REQUIRE(classical_signature.has_value()); - REQUIRE(pq_signature.has_value()); - - INFO("The signatures share their protected header except alg and kid"); - const auto classical = - ccf::cose::decode_ccf_receipt(classical_signature.value(), false).phdr; - const auto pq = - ccf::cose::decode_ccf_receipt(pq_signature.value(), false).phdr; - const auto kid_bytes = [](const std::string& kid) { - return std::vector(kid.begin(), kid.end()); - }; - REQUIRE( - classical.alg == - ccf::cose::algorithm_for_curve(service_kp->get_curve_id()).alg); - REQUIRE( - classical.kid == - kid_bytes(ccf::crypto::kid_from_key(service_kp->public_key_der()))); - REQUIRE(pq.alg == ccf::cose::alg::ML_DSA_65); - REQUIRE(pq.kid == kid_bytes(ccf::crypto::kid_from_key(pq_public_key_der))); - REQUIRE(pq.vds == classical.vds); - REQUIRE(pq.ccf.txid == classical.ccf.txid); - REQUIRE(pq.cwt.iat == classical.cwt.iat); - REQUIRE(pq.cwt.iss == classical.cwt.iss); - REQUIRE(pq.cwt.sub == classical.cwt.sub); -} - -TEST_CASE("Every COSE signature is verified with the identity of its type") -{ - SigningFixture f(ccf::crypto::make_mldsa_key_pair( - ccf::crypto::MLDSAParameterSet::ML_DSA_65)); - f.publish_service_keys(); - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::PASS_SIGNATURE); - - const auto sign_with = [&f]( - ccf::kv::Tx& tx, - const ccf::TxID& txid, - const ccf::crypto::Sha256Hash& root, - bool with_pq_signature, - bool tamper_pq_signature = false) { - auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); - signatures->put( - ccf::IdentityType::CLASSICAL, sign_root(*f.service_kp, txid, root)); - if (with_pq_signature) - { - auto pq_signature = sign_root(*f.pq_service_kp, txid, root); - if (tamper_pq_signature) - { - pq_signature.back() ^= 1; - } - signatures->put(ccf::IdentityType::PQ, pq_signature); - } - }; - - SUBCASE("Signatures by both published keys verify") - { - REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { - sign_with(tx, txid, root, true); - }) == ccf::kv::ApplyResult::PASS_SIGNATURE); - } - - SUBCASE("A tampered PQ signature fails verification") - { - REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { - sign_with(tx, txid, root, true, true); - }) == ccf::kv::ApplyResult::FAIL); - } - - SUBCASE("A PQ signature by another key fails verification") - { - const auto other_cert = ccf::crypto::make_mldsa_key_pair( - ccf::crypto::MLDSAParameterSet::ML_DSA_65) - ->self_sign("CN=Service", valid_from, valid_to); - f.commit([&](ccf::kv::Tx& tx) { - tx.wo(ccf::Tables::SERVICE) - ->put(ccf::ServiceInfo{.cert = f.service_cert, .pq_cert = other_cert}); - tx.wo(ccf::Tables::SIGNING_IDENTITIES) - ->put( - ccf::IdentityType::PQ, ccf::signing_identity_from_cert(other_cert)); - }); - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); - } - - SUBCASE("A PQ signature by a rotated key verifies") - { - // The fixture's first signature cached a verifier for the previous key - f.pq_service_kp = ccf::crypto::make_mldsa_key_pair( - ccf::crypto::MLDSAParameterSet::ML_DSA_65); - const auto rotated_cert = - f.pq_service_kp->self_sign("CN=Service", valid_from, valid_to); - f.commit([&](ccf::kv::Tx& tx) { - tx.wo(ccf::Tables::SERVICE) - ->put( - ccf::ServiceInfo{.cert = f.service_cert, .pq_cert = rotated_cert}); - tx.wo(ccf::Tables::SIGNING_IDENTITIES) - ->put( - ccf::IdentityType::PQ, ccf::signing_identity_from_cert(rotated_cert)); - }); - REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { - sign_with(tx, txid, root, true); - }) == ccf::kv::ApplyResult::PASS_SIGNATURE); - } - - SUBCASE("A published PQ identity requires a PQ signature") - { - // The table still holds the PQ signature of the previous signature - // transaction, and this transaction writes only a CLASSICAL one - REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { - sign_with(tx, txid, root, false); - }) == ccf::kv::ApplyResult::FAIL); - } - - SUBCASE("A PQ signature requires a published PQ identity") - { - f.commit([&](ccf::kv::Tx& tx) { - tx.wo(ccf::Tables::SERVICE) - ->put(ccf::ServiceInfo{.cert = f.service_cert}); - tx.wo(ccf::Tables::SIGNING_IDENTITIES) - ->remove(ccf::IdentityType::PQ); - }); - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); - } - - SUBCASE("A PQ certificate requires a published PQ identity") - { - f.commit([&](ccf::kv::Tx& tx) { - tx.wo(ccf::Tables::SIGNING_IDENTITIES) - ->remove(ccf::IdentityType::PQ); - }); - - SUBCASE("With both signatures") - { - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); - } - - SUBCASE("With a CLASSICAL signature alone") - { - REQUIRE( - f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { - sign_with(tx, txid, root, false); - }) == ccf::kv::ApplyResult::FAIL); - } - } -} - -TEST_CASE("An unknown identity type fails signature verification") -{ - SigningFixture f; - f.publish_service_keys(); - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::PASS_SIGNATURE); - - constexpr uint64_t unknown_identity_type = 2; - - SUBCASE("Among the signing identities") - { - f.commit([&](ccf::kv::Tx& tx) { - tx.wo>( - ccf::Tables::SIGNING_IDENTITIES) - ->put( - unknown_identity_type, - ccf::signing_identity_from_cert(f.service_cert)); - }); - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::FAIL); - } - - SUBCASE("Among the COSE signatures") - { - REQUIRE(f.emit_signature([&](auto& tx, const auto& txid, const auto& root) { - const auto signature = sign_root(*f.service_kp, txid, root); - tx.template wo(ccf::Tables::COSE_SIGNATURES) - ->put(ccf::IdentityType::CLASSICAL, signature); - tx.template wo>( - ccf::Tables::COSE_SIGNATURES) - ->put(unknown_identity_type, signature); - }) == ccf::kv::ApplyResult::FAIL); - } -} - -TEST_CASE("A published CLASSICAL identity requires a CLASSICAL COSE signature") -{ - SigningFixture f; - const auto node_signature_only = [&f]( - ccf::kv::Tx& tx, - const ccf::TxID& txid, - const ccf::crypto::Sha256Hash& root) { - tx.wo(ccf::Tables::SIGNATURES) - ->put(ccf::PrimarySignature( - ccf::kv::test::PrimaryNodeId, - txid.seqno, - txid.view, - root, - {}, - f.node_kp->sign_hash(root.h.data(), root.h.size()), - f.node_cert)); - }; - - SUBCASE("Without a published identity, a node signature suffices") - { - f.commit([&f](ccf::kv::Tx& tx) { - tx.wo(ccf::Tables::SERVICE) - ->put(ccf::ServiceInfo{.cert = f.service_cert}); - }); - REQUIRE( - f.emit_signature(node_signature_only) == - ccf::kv::ApplyResult::PASS_SIGNATURE); - } - - SUBCASE("With a published identity, a node signature alone fails") - { - f.publish_service_keys(); - REQUIRE(f.emit_signature() == ccf::kv::ApplyResult::PASS_SIGNATURE); - REQUIRE( - f.emit_signature(node_signature_only) == ccf::kv::ApplyResult::FAIL); - } + REQUIRE(cose_signatures->get(ccf::IdentityType::CLASSICAL).has_value()); } TEST_CASE("Check signing works across rollback") @@ -830,9 +447,9 @@ TEST_CASE("Check signing works across rollback") INFO("Check merkle roots are updating"); { auto primary_root = primary_history->get_replicated_state_root(); - auto pr_str = std::format("{}", primary_root); + auto pr_str = fmt::format("{}", primary_root); auto backup_root = backup_history->get_replicated_state_root(); - auto bk_str = std::format("{}", backup_root); + auto bk_str = fmt::format("{}", backup_root); REQUIRE(pr_str == bk_str); } @@ -887,18 +504,20 @@ class TestPendingTx : public ccf::kv::PendingTx { ccf::TxID txid; ccf::kv::Store& store; + MapT& other_table; public: - TestPendingTx(ccf::TxID txid_, ccf::kv::Store& store_) : + TestPendingTx(ccf::TxID txid_, ccf::kv::Store& store_, MapT& other_table_) : txid(txid_), - store(store_) + store(store_), + other_table(other_table_) {} ccf::kv::PendingTxInfo call() override { auto txr = store.create_reserved_tx(txid); - txr.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({}); + auto txrv = txr.rw(other_table); + txrv->put(0, 1); return txr.commit_reserved(); } }; @@ -930,6 +549,7 @@ TEST_CASE("Pending signatures retain their endorsed certificate") constexpr auto store_term = 2; store.initialise_term(store_term); + MapT table("public:table"); const auto gap_txid = store.next_txid().value(); history->emit_signature(); @@ -938,10 +558,11 @@ TEST_CASE("Pending signatures retain their endorsed certificate") history->set_endorsed_certificate(second_cert); REQUIRE( store.commit( - gap_txid, std::make_unique(gap_txid, store), false) == - ccf::kv::CommitResult::SUCCESS); + gap_txid, + std::make_unique(gap_txid, store, table), + false) == ccf::kv::CommitResult::SUCCESS); - auto tx = store.create_read_only_tx_at_replicated_state(); + auto tx = store.create_read_only_tx(); auto signatures = tx.ro(ccf::Tables::SIGNATURES); const auto signature = signatures->get(); REQUIRE(signature.has_value()); @@ -1007,7 +628,7 @@ TEST_CASE("Signatures are not emitted on demand until signing is enabled") MapT table("public:table"); auto get_signature = [&]() { - auto tx = store.create_read_only_tx_at_replicated_state(); + auto tx = store.create_read_only_tx(); return tx.ro(ccf::Tables::SIGNATURES)->get(); }; @@ -1064,8 +685,8 @@ class PausedReservedSignatureTx : public ccf::kv::PendingTx ccf::kv::PendingTxInfo call() override { auto tx = store.create_reserved_tx(txid); - auto sig = tx.wo(signatures); - auto tree = tx.wo(serialised_tree); + auto sig = tx.rw(signatures); + auto tree = tx.rw(serialised_tree); sig->put(ccf::PrimarySignature(ccf::kv::test::PrimaryNodeId, txid.seqno)); tree->put({}); @@ -1096,6 +717,7 @@ TEST_CASE( store.set_consensus(consensus); MapT table("public:table"); + MapT other_table("public:other_table"); INFO("Write first tx"); { @@ -1116,7 +738,8 @@ TEST_CASE( REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); REQUIRE(consensus->count == 1); - store.commit(rv, std::make_unique(rv, store), true); + store.commit( + rv, std::make_unique(rv, store, other_table), true); REQUIRE(consensus->count == 3); } @@ -1373,18 +996,15 @@ TEST_CASE("COSE signature table holds one entry per identity") INFO("A table carrying two identities round-trips both"); { - auto tx = store.create_reserved_tx(store.next_txid().value()); + auto tx = store.create_tx(); auto* handle = tx.wo(ccf::Tables::COSE_SIGNATURES); handle->put(ccf::IdentityType::CLASSICAL, ec384_sig); handle->put(ccf::IdentityType::PQ, mldsa65_sig); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({}); - REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); - store.compact(store.current_version()); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } { - auto tx = store.create_read_only_tx_at_replicated_state(); + auto tx = store.create_read_only_tx(); auto* handle = tx.ro(ccf::Tables::COSE_SIGNATURES); // A reader which only understands ECDSA still finds it, unaffected by @@ -1410,33 +1030,22 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") const ccf::CoseSignature keyed_signature{4, 5, 6}; { - auto tx = store.create_reserved_tx(store.next_txid().value()); + auto tx = store.create_tx(); tx.wo(ccf::Tables::COSE_SIGNATURES) ->put(legacy_signature); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({}); - REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); - store.compact(store.current_version()); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } { - auto tx = store.create_read_only_tx_at_replicated_state(); - auto* signatures = tx.ro(ccf::Tables::COSE_SIGNATURES); + auto tx = store.create_tx(); + auto* signatures = tx.rw(ccf::Tables::COSE_SIGNATURES); REQUIRE(signatures->get(ccf::IdentityType::CLASSICAL) == legacy_signature); - } - - { - auto tx = store.create_reserved_tx(store.next_txid().value()); - auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); signatures->put(ccf::IdentityType::CLASSICAL, keyed_signature); - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) - ->put({}); - REQUIRE(tx.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); - store.compact(store.current_version()); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } { - auto tx = store.create_read_only_tx_at_replicated_state(); + auto tx = store.create_read_only_tx(); REQUIRE( tx.ro(ccf::Tables::COSE_SIGNATURES)->get() == keyed_signature); diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index 7895b968d455..bc4ba50e3779 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -18,8 +18,6 @@ #include "node/snapshot_serdes.h" #include "snapshots/filenames.h" -#include - #define DOCTEST_CONFIG_IMPLEMENT #include #include @@ -49,7 +47,7 @@ struct ScopedSnapshotDir ScopedSnapshotDir() { - const auto unique_name = std::format( + const auto unique_name = fmt::format( "ccf-snapshotter-test-{}-{}", ::getpid(), std::chrono::steady_clock::now().time_since_epoch().count()); @@ -461,7 +459,7 @@ TEST_CASE("Recovery snapshot ledger scan filters directory contents") fixture.ledger_config.directory = path.string(); REQUIRE_THROWS_WITH_AS( ccf::find_recovery_snapshot_ledger_files(fixture.ledger_config), - std::format( + fmt::format( "Unable to iterate ledger directory {}: {}", path.string(), std::make_error_code(std::errc::not_a_directory).message()) @@ -476,7 +474,7 @@ TEST_CASE("Recovery snapshot ledger scan filters directory contents") fixture.ledger_config.directory = path.string(); REQUIRE_THROWS_WITH_AS( ccf::find_recovery_snapshot_ledger_files(fixture.ledger_config), - std::format( + fmt::format( "Unable to inspect ledger directory {}: {}", path.string(), std::make_error_code(std::errc::too_many_symbolic_link_levels) @@ -501,7 +499,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") REQUIRE(fs::remove(current_path)); REQUIRE_THROWS_WITH_AS( ccf::open_recovery_snapshot_ledger_file(files.front()), - std::format("Unable to open ledger file {}", current_path.string()) + fmt::format("Unable to open ledger file {}", current_path.string()) .c_str(), std::logic_error); } @@ -514,7 +512,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") fs::resize_file(current_path, size); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format("Ledger file {} is too small", current_path.string()) + fmt::format("Ledger file {} is too small", current_path.string()) .c_str(), std::logic_error); } @@ -527,7 +525,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") fs::rename(current_path, committed_path); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Committed ledger file {} has no positions table", committed_path.string()) .c_str(), @@ -551,7 +549,7 @@ TEST_CASE("Recovery snapshot ledger scan validates chunk headers") } REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Ledger file {} has invalid positions table offset {}", committed_path.string(), offset) @@ -590,7 +588,7 @@ TEST_CASE("Recovery snapshot ledger reader reports truncation after opening") REQUIRE(reader.file); REQUIRE_THROWS_WITH_AS( ccf::read_recovery_snapshot_ledger_entry(reader, ledger_file), - std::format("Unable to read {} from ledger file {}", error, path.string()) + fmt::format("Unable to read {} from ledger file {}", error, path.string()) .c_str(), std::logic_error); } @@ -648,7 +646,7 @@ TEST_CASE("Recovery snapshot ledger scan distinguishes incomplete chunk tails") write_ledger_file(committed_path, {first, tail}, true); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format("Committed ledger file {} {}", committed_path.string(), error) + fmt::format("Committed ledger file {} {}", committed_path.string(), error) .c_str(), std::logic_error); } @@ -690,7 +688,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {first, second}); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Ledger file {} does not start at its declared seqno 2", path.string()) .c_str(), std::logic_error); @@ -702,7 +700,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {first, second}, true); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Ledger file {} does not end at its declared seqno 3", path.string()) .c_str(), std::logic_error); @@ -714,7 +712,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {}, true); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Ledger file {} does not end at its declared seqno 1", path.string()) .c_str(), std::logic_error); @@ -728,7 +726,7 @@ TEST_CASE("Recovery snapshot ledger scan validates version ranges") write_ledger_file(path, {first, fixture.entry(next)}); REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Ledger file {} contains non-contiguous versions 1 and {}", path.string(), next) @@ -764,7 +762,7 @@ TEST_CASE("Recovery snapshot ledger scan rejects seqno overflow") SUBCASE("The last scanned entry must have a successor") { write_ledger_file( - fixture.ledger_dir.path / std::format("ledger_{}", max_seqno), + fixture.ledger_dir.path / fmt::format("ledger_{}", max_seqno), {fixture.entry(max_seqno)}); REQUIRE_THROWS_WITH_AS( fixture.scan(max_seqno - 1), @@ -884,7 +882,7 @@ TEST_CASE("Recovery snapshot ledger scan bounds individual endorsement sizes") { REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Ledger endorsement at 1 is too large ({} bytes; maximum {} bytes)", limit + extra, limit) @@ -927,7 +925,7 @@ TEST_CASE("Recovery snapshot ledger scan bounds individual endorsement sizes") { REQUIRE_THROWS_WITH_AS( fixture.scan(), - std::format( + fmt::format( "Serialised previous service identity endorsement is too large " "({} bytes; maximum {} bytes)", limit + 4 * extra, @@ -1570,25 +1568,14 @@ TEST_CASE("Rekey ledger while snapshot is in progress") { // It is necessary to record a signature for the snapshot to be // deserialisable by the backup store - const auto txid = network.tables->next_txid().value(); - auto tx = network.tables->create_reserved_tx(txid); - auto sigs = tx.wo(ccf::Tables::SIGNATURES); + auto tx = network.tables->create_tx(); + auto sigs = tx.rw(ccf::Tables::SIGNATURES); auto trees = - tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE); + tx.rw(ccf::Tables::SERIALISED_MERKLE_TREE); sigs->put({ccf::kv::test::PrimaryNodeId, 0, 0, {}, {}, {}, {}}); auto tree = history->serialise_tree(snapshot_idx - 1); trees->put(tree); - auto info = tx.commit_reserved(); - REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); - REQUIRE( - network.tables->commit( - txid, - std::make_unique( - std::move(info.data), - std::move(info.claims_digest), - std::move(info.commit_evidence_digest), - std::move(info.hooks)), - false) == ccf::kv::CommitResult::SUCCESS); + tx.commit(); REQUIRE(record_signature(history, snapshotter, snapshot_idx)); snapshotter->commit(snapshot_idx, true); @@ -1686,7 +1673,7 @@ TEST_CASE("Snapshot receipt") } else { - tree.append(ccf::crypto::Sha256Hash(std::format("tx {}", seqno))); + tree.append(ccf::crypto::Sha256Hash(fmt::format("tx {}", seqno))); } } const auto root = tree.get_root();