diff --git a/.github/workflows/ci-expanded.yml b/.github/workflows/ci-expanded.yml index 0dfbdadd..a3702508 100644 --- a/.github/workflows/ci-expanded.yml +++ b/.github/workflows/ci-expanded.yml @@ -2186,7 +2186,7 @@ jobs: warnings: needs: [ gnu, musl, cmake, presets, msvc ] - if: ${{ !cancelled() && (github.event_name != 'pull_request' || github.event.action != 'closed') }} + if: ${{ success() && github.event_name == 'push' }} continue-on-error: true runs-on: ubuntu-latest diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cfd18345..2362eb4f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1140,7 +1140,7 @@ jobs: warnings: needs: [ gnu, cmake, presets, msvc ] - if: ${{ !cancelled() && (github.event_name != 'pull_request' || github.event.action != 'closed') }} + if: ${{ success() && github.event_name == 'push' }} continue-on-error: true runs-on: ubuntu-latest diff --git a/builds/cmake/CMakeLists.txt b/builds/cmake/CMakeLists.txt index 69b8c6ca..6f473b8d 100644 --- a/builds/cmake/CMakeLists.txt +++ b/builds/cmake/CMakeLists.txt @@ -88,6 +88,7 @@ if ( MSVC ) add_compile_options( /W4 /permissive- + /Zc:inline /bigobj /Zc:__cplusplus /Zc:preprocessor diff --git a/builds/gnu/Makefile.am b/builds/gnu/Makefile.am index 7590e12e..5f6377ef 100644 --- a/builds/gnu/Makefile.am +++ b/builds/gnu/Makefile.am @@ -66,6 +66,7 @@ src_libbitcoin_node_la_SOURCES = \ ${srcdir}/../../src/chasers/chaser_template.cpp \ ${srcdir}/../../src/chasers/chaser_transaction.cpp \ ${srcdir}/../../src/chasers/chaser_transaction_compact.cpp \ + ${srcdir}/../../src/chasers/chaser_transaction_context.cpp \ ${srcdir}/../../src/chasers/chaser_transaction_query.cpp \ ${srcdir}/../../src/chasers/chaser_transaction_relay.cpp \ ${srcdir}/../../src/chasers/chaser_transaction_submit.cpp \ diff --git a/builds/msvc/properties/Common.props b/builds/msvc/properties/Common.props index b3efa3bb..b0f4f62d 100644 --- a/builds/msvc/properties/Common.props +++ b/builds/msvc/properties/Common.props @@ -25,6 +25,7 @@ Level4 Level4 true + true stdc11 true true diff --git a/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj b/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj index e1b32ddb..77879efa 100644 --- a/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj +++ b/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj @@ -123,6 +123,7 @@ + diff --git a/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj.filters b/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj.filters index 409de67e..33d419d2 100644 --- a/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj.filters +++ b/builds/msvc/vs2026/libbitcoin-node/libbitcoin-node.vcxproj.filters @@ -87,6 +87,9 @@ src\chasers + + src\chasers + src\chasers diff --git a/include/bitcoin/node/chasers/chaser_transaction.hpp b/include/bitcoin/node/chasers/chaser_transaction.hpp index 9fc2f7d8..bc890cd1 100644 --- a/include/bitcoin/node/chasers/chaser_transaction.hpp +++ b/include/bitcoin/node/chasers/chaser_transaction.hpp @@ -112,6 +112,14 @@ class BCN_API chaser_transaction protected: using chaser::broadcast; + /// Post a method in base or derived class in parallel (use PARALLEL). + template + inline auto parallel(Method&& method, Args&&... args) NOEXCEPT + { + return network::io::post(validation_threadpool_.service(), + BIND_TO(method, args)); + } + virtual bool handle_chase(const code& ec, event_value value) NOEXCEPT; virtual void do_submit(const system::chain::transactions_cptr& txs, @@ -190,7 +198,7 @@ class BCN_API chaser_transaction bool stranded() const NOEXCEPT override; private: - /// A set under submission, its running set and outcome. + // A set under submission, its running set and outcome. struct submission { system::chain::transactions_cptr txs; @@ -198,6 +206,12 @@ class BCN_API chaser_transaction uint32_t time; bool test; bool announced; + submit_handler handler{}; + system::chain::context ctx{}; + std::chrono::steady_clock::time_point begin{}; + std::vector reserved{}; + std::vector accepted{}; + code checked{}; std::vector stored{}; std::vector sigops_of{}; std::unordered_set held{}; @@ -211,15 +225,27 @@ class BCN_API chaser_transaction bool cleared{}; code failure{}; }; + using submission_ptr = std::shared_ptr; + using submission_ptrs = std::vector; + using hash_set = std::unordered_set; + using row_marks = std::vector; + using rate_slots = std::array; + using key_slots = std::array; static size_t to_rate(const system::chain::transaction& tx) NOEXCEPT; system::pool::algorithm::totals_t block_limit() const NOEXCEPT; - /// Chain state of top, the held state advanced by top, else from store. + // Chain state of top, the held state advanced by top, else from store. system::chain::chain_state::cptr top_state(const database::header_link& top, size_t height) NOEXCEPT; - /// Submission steps. + // Submission steps. + void enter(const submission_ptr& set) NOEXCEPT; + void do_validate(const submission_ptr& set) NOEXCEPT; + void do_validated(const submission_ptr& set) NOEXCEPT; + void complete(const submission_ptr& set, const code& ec, + size_t index) NOEXCEPT; + bool is_dependent(const submission& set) const NOEXCEPT; void hold(submission& set) NOEXCEPT; bool spends_held(const submission& set, const system::chain::transaction& tx) const NOEXCEPT; @@ -232,7 +258,8 @@ class BCN_API chaser_transaction code clear(size_t& at, submission& set, size_t index) NOEXCEPT; code check(const system::chain::transaction_cptrs& txs, - const std::vector& stored, bool announced) NOEXCEPT; + const std::vector& stored, bool announced, + const system::chain::context& ctx) NOEXCEPT; code accept(const system::chain::transaction& tx, const system::chain::context& ctx) NOEXCEPT; code admit(database::tx_link& out, const system::chain::transaction& tx, @@ -252,55 +279,99 @@ class BCN_API chaser_transaction void start_scan(bool remap) NOEXCEPT; void start_revalidation() NOEXCEPT; - /// Relay txs with their unconfirmed ancestry, marked held by origin, to - /// each slot whose rate the sum of rows it lacks clears. + // Relay txs with their unconfirmed ancestry, marked held by origin, to + // each slot whose rate the sum of rows it lacks clears. bool relay(const database::tx_links& links, size_t origin, uint64_t slots, object_key key={}) NOEXCEPT; - /// Relay confirmable txs in row order, each with ancestry slot lacks, where - /// that clears slot's rate. + // Relay confirmable txs in row order, each with ancestry slot lacks, where + // that clears slot's rate. bool sweep_relay(size_t slot) NOEXCEPT; - /// Owe slot a sweep, made now unless swept since last block. + // Owe slot a sweep, made now unless swept since last block. void owe_relay(size_t slot) NOEXCEPT; - /// Relaying slots owed a sweep and not swept since last block. + // Relaying slots owed a sweep and not swept since last block. uint64_t sweepable() const NOEXCEPT; - /// The marks of the pool row, grown with the table. + // The marks of the pool row, grown with the table. uint64_t& marks(size_t row) NOEXCEPT; - /// The pool index follows blocks (pooling store and relay enabled). + // The pool index follows blocks (pooling store and relay enabled). bool is_indexing() const NOEXCEPT; - /// A validation under the context holds at a later block. + // A validation under the context holds at a later block. bool reusable(const system::chain::context& ctx) const NOEXCEPT; - /// Set pooled spenders of block's txs not validated, parent pool top. + // Set pooled spenders of block's txs not validated, parent pool top. bool unvalidate(header_t link) NOEXCEPT; - /// Pool block's unpooled txs under its context, false if faulted. + // Pool block's unpooled txs under its context, false if faulted. bool repool(header_t link) NOEXCEPT; - /// A validation under the context holds under the pool context. + // A validation under the context holds under the pool context. bool is_sufficient(const system::chain::context& ctx) const NOEXCEPT; - /// Sweep the index by the pool context if due, false on store failure. + // Sweep the index by the pool context if due, false on store failure. bool sweep() NOEXCEPT; static uint64_t arriving(const query::pool_arrivals& arrivals, uint64_t rate, estimate_mode mode) NOEXCEPT; - /// Notify pool subscribers of scan, timed from its start, and fire its - /// event (other than for coverage, which fires only when it clears). + // Notify pool subscribers of scan, timed from its start, and fire its + // event (other than for coverage, which fires only when it clears). using time_point = std::chrono::steady_clock::time_point; static time_point now() NOEXCEPT; void report(pool_scan scan, const time_point& start) NOEXCEPT; - /// Fire the event with the microseconds since the start. + // Fire the event with the microseconds since the start. void fire_span(events event, const time_point& start) NOEXCEPT; - // This is not thread safe. + // Pool context, its chain position and the sweep that follows it. + struct context_state + { + system::chain::context pool{}; + system::chain::chain_state::cptr state{}; + system::hash_digest previous{}; + database::header_link top{}; + size_t floor{}; + bool due{ true }; + bool revalidating{}; + bool unvalidated{}; + system::chain::context retried{}; + }; + + // Projection held across estimates and the arrivals it draws on. + struct estimate_state + { + bool estimating{}; + bool arrived{}; + time_point estimated{}; + query::pool_projection projection{}; + query::pool_arrivals arrivals{}; + }; + + // Relay slots, their rates and keys, and the marks of the pool rows. + struct relay_state + { + row_marks marks{}; + rate_slots rates{}; + key_slots keys{}; + uint64_t relaying{}; + uint64_t owed{}; + uint64_t swept{}; + bool sweeping{}; + }; + + // Txs under validation, and sets waiting on them. + struct submit_state + { + hash_set validating{}; + submission_ptrs waiting{}; + }; + + // These are not thread safe. network::threadpool transaction_threadpool_; + network::threadpool validation_threadpool_; // These are thread safe. network::io::strand transaction_strand_; @@ -316,28 +387,11 @@ class BCN_API chaser_transaction // These are protected by strand. pool_subscriber subscriber_{}; - system::chain::context pool_{}; - system::chain::chain_state::cptr state_{}; - system::hash_digest previous_{}; - database::header_link top_{}; - size_t floor_{}; - bool due_{ true }; + context_state context_{}; + estimate_state estimate_{}; + relay_state relay_{}; + submit_state submit_{}; bool scanning_{}; - bool revalidating_{}; - bool unvalidated_{}; - bool estimating_{}; - bool arrived_{}; - time_point estimated_{}; - query::pool_projection projection_{}; - query::pool_arrivals arrivals_{}; - system::chain::context retried_{}; - std::vector marks_{}; - std::array rates_{}; - std::array keys_{}; - uint64_t relaying_{}; - uint64_t owed_{}; - uint64_t swept_{}; - bool sweeping_{}; }; } // namespace node diff --git a/include/bitcoin/node/protocols/protocol_transaction_out_70013.hpp b/include/bitcoin/node/protocols/protocol_transaction_out_70013.hpp index f23a3a39..5f76d215 100644 --- a/include/bitcoin/node/protocols/protocol_transaction_out_70013.hpp +++ b/include/bitcoin/node/protocols/protocol_transaction_out_70013.hpp @@ -35,28 +35,41 @@ class BCN_API protocol_transaction_out_70013 protocol_transaction_out_70013(const auto& session, const network::channel::ptr& channel) NOEXCEPT : protocol_transaction_out_70001(session, channel), - network::tracker(session->log) + network::tracker(session->log), + fee_timer_(to_bool(session->node_settings().fee_filter_minutes) ? + system::emplace_shared(session->log, + channel->strand(), + session->node_settings().fee_filter_period()) : nullptr) { } /// Start protocol (strand required). void start() NOEXCEPT override; + /// The channel is stopping (called on strand by stop subscription). + void stopping(const code& ec) NOEXCEPT override; + protected: /// Handle chaser events. bool handle_chase(const code& ec, event_value value) NOEXCEPT override; void subscribed(const code& ec, object_key key) NOEXCEPT override; - /// Capture the peer's minimum fee rate for announcements. + /// Capture the peer's minimum fee rate for announcements, a peer that + /// lowers it again within the fee filter period is dropped. virtual bool handle_receive_fee_filter(const code& ec, const network::messages::peer::fee_filter::cptr& message) NOEXCEPT; private: void do_send_fee_filter() NOEXCEPT; + void handle_fee_timer(const code& ec) NOEXCEPT; + + // This is thread safe. + const network::deadline::ptr fee_timer_; // This is protected by strand. uint64_t sent_fee_{ max_uint64 }; bool requested_{}; + bool lowered_{}; }; } // namespace node diff --git a/include/bitcoin/node/settings.hpp b/include/bitcoin/node/settings.hpp index fc1f5cd0..35031088 100644 --- a/include/bitcoin/node/settings.hpp +++ b/include/bitcoin/node/settings.hpp @@ -94,6 +94,7 @@ class BCN_API settings uint16_t compact_timeout_seconds; uint8_t compact_missing_percent; uint32_t currency_window_minutes; + uint16_t fee_filter_minutes; ////uint64_t snapshot_bytes; ////uint32_t snapshot_valid; ////uint32_t snapshot_confirm; @@ -112,6 +113,7 @@ class BCN_API settings virtual network::steady_clock::duration sample_period() const NOEXCEPT; virtual network::steady_clock::duration compact_timeout() const NOEXCEPT; virtual network::wall_clock::duration currency_window() const NOEXCEPT; + virtual network::steady_clock::duration fee_filter_period() const NOEXCEPT; virtual network::processing_priority thread_priority_() const NOEXCEPT; }; diff --git a/src/chasers/chaser_transaction.cpp b/src/chasers/chaser_transaction.cpp index c059ec6a..58b8519e 100644 --- a/src/chasers/chaser_transaction.cpp +++ b/src/chasers/chaser_transaction.cpp @@ -34,10 +34,12 @@ using namespace std::placeholders; BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT) BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR) -// Independent threadpool and strand (base class strand uses network pool). +// Independent threadpool and strand (base class strand uses network pool), +// with validation at network priority so that pool work precedes it. chaser_transaction::chaser_transaction(full_node& node) NOEXCEPT : chaser(node), transaction_threadpool_(one, node.node_settings().pool.thread_priority_()), + validation_threadpool_(node.node_settings().threads_()), transaction_strand_(transaction_threadpool_.service().get_executor()), scan_threadpool_(one, node.node_settings().thread_priority_()), revalidation_threadpool_(one, node.node_settings().thread_priority_()), @@ -99,6 +101,7 @@ void chaser_transaction::stopping(const code& ec) NOEXCEPT stopping_.store(true); scan_threadpool_.stop(); revalidation_threadpool_.stop(); + validation_threadpool_.stop(); transaction_threadpool_.stop(); chaser::stopping(ec); } @@ -107,7 +110,7 @@ void chaser_transaction::stopping(const code& ec) NOEXCEPT void chaser_transaction::stop() NOEXCEPT { if (!scan_threadpool_.join() || !revalidation_threadpool_.join() || - !transaction_threadpool_.join()) + !validation_threadpool_.join() || !transaction_threadpool_.join()) { BC_ASSERT_MSG(false, "failed to join threadpool"); std::abort(); @@ -174,320 +177,6 @@ bool chaser_transaction::handle_chase(const code&, event_value value) NOEXCEPT return true; } -// Pool is closed until confirmed chain is current, and closes again if -// currency is lost, though store latch is one way, since txs archived while -// it was open outlive it. -void chaser_transaction::do_bump() NOEXCEPT -{ - BC_ASSERT(stranded()); - estimating_ = false; - const auto opened = pooling_.load(); - pooling_ = false; - if (closed() || !is_current_chain(true)) - { - if (opened) - ++generation_; - - return; - } - - // Pooling is a permanent store property, so it requires relay. - auto& query = archive(); - if (network_settings().enable_relay) - { - // Context of block last applied to index (store top may be above). - size_t height{}; - const auto top = top_.is_terminal() ? query.to_top_confirmed() : top_; - if (!query.get_height(height, top)) - { - fault(error::transaction9); - return; - } - - const auto state = top_state(top, height); - if (!state) - { - fault(error::transaction1); - return; - } - - // The context of the next block, in which a pool tx would confirm. - const auto previous = pool_; - pool_ = chain_state{ *state, system_settings() }.context(); - previous_ = state->hash(); - - // Row holds unless a flag changes or height or median time past falls. - due_ = due_ || pool_.flags != previous.flags || - pool_.height < previous.height || - pool_.median_time_past < previous.median_time_past; - - if (!sweep()) - { - fault(error::transaction11); - return; - } - - if (reusable(pool_)) - { - query.set_pooling(); - pooling_ = true; - - // Rows that arrived while the pool was closed are not in it. - if (!opened) - floor_ = std::max(floor_, pool_.height); - - // Make sweeps deferred to block. - swept_ = {}; - if (!sweeping_) - do_sweep_relay(); - } - } - - // Opening or closing the pool changes its templates. - if (pooling_ != opened) - ++generation_; - - // Scan starts are mapped after the latch, as pooled rows are unordered. - if (!query.silent_enabled() || scanning_) - return; - - // Complete map reaches genesis, and keeps up with top until latched. - // Rows of a block archived before latch may precede mapped starts. - const auto top = query.to_top_confirmed(); - const auto unmapped = query.get_scan_start(top).is_terminal(); - if (query.get_scan_start(query.to_confirmed(zero)).is_terminal()) - start_scan(true); - else if (unmapped && !query.is_pooling()) - start_scan(false); - else if (unmapped && query.to_coinbase(top) < query.get_latch_tx()) - start_scan(true); -} - -// private -chain_state::cptr chaser_transaction::top_state( - const database::header_link& top, size_t height) NOEXCEPT -{ - BC_ASSERT(stranded()); - const auto& query = archive(); - if (state_ && height == state_->height() && - query.get_header_key(top) == state_->hash()) - return state_; - - if (state_ && height == add1(state_->height())) - { - const auto header = query.get_header(top); - if (header && header->previous_block_hash() == state_->hash()) - { - state_ = to_shared(*state_, *header, system_settings()); - return state_; - } - } - - state_ = query.get_confirmed_chain_state(system_settings(), top, height); - return state_; -} - -bool chaser_transaction::is_indexing() const NOEXCEPT -{ - return network_settings().enable_relay && archive().is_pooling(); -} - -bool chaser_transaction::reusable(const chain::context& ctx) const NOEXCEPT -{ - const auto evaluated = database::context::from(ctx); - return archive().is_sufficient(evaluated, evaluated); -} - -bool chaser_transaction::is_sufficient( - const chain::context& ctx) const NOEXCEPT -{ - return archive().is_sufficient(database::context::from(pool_), - database::context::from(ctx)); -} - -// Sweep remains due while it leaves any row unsatisfied, so row is restored -// once pool context satisfies it. -bool chaser_transaction::sweep() NOEXCEPT -{ - BC_ASSERT(stranded()); - auto& query = archive(); - if (!due_ || !query.is_pooling()) - return true; - - size_t count{}; - const auto start = now(); - const auto applied = query.set_pool_context(count, - database::context::from(pool_)); - - report(pool_scan::context, start); - due_ = !applied || is_nonzero(count); - if (applied && is_nonzero(count)) - start_revalidation(); - - return applied; -} - -// Rows left out by flags are revalidated once per change of flags, and rows -// not validated once per change of pool context, so failing row is retried -// only under another context. -void chaser_transaction::start_revalidation() NOEXCEPT -{ - BC_ASSERT(stranded()); - if (revalidating_) - return; - - const auto flagged = pool_.flags != retried_.flags; - const auto moved = unvalidated_ || pool_.height != retried_.height || - pool_.median_time_past != retried_.median_time_past; - - if (!flagged && !moved) - return; - - auto& query = archive(); - database::tx_links links{}; - database::tx_links unvalidated{}; - const auto ctx = database::context::from(pool_); - code ec{}; - if (flagged) - ec = query.get_pool_revalidation(links, ctx); - - if (!ec) - ec = query.get_pool_unvalidated(unvalidated); - - if (ec) - { - fault(ec); - return; - } - - links.insert(links.end(), unvalidated.begin(), unvalidated.end()); - - retried_ = pool_; - unvalidated_ = false; - if (links.empty()) - return; - - revalidating_ = true; - network::io::post(revalidation_threadpool_.service(), - BIND(do_revalidate, std::move(links), pool_)); -} - -// Revalidation is admission under context, as confirmation of what a row spends -// may differ from when it was pooled. Sigops are counted under flags of -// context, so a passing tx is counted again. -void chaser_transaction::do_revalidate(const database::tx_links& links, - const chain::context& ctx) NOEXCEPT -{ - const auto& query = archive(); - const auto bip16 = ctx.is_enabled(flags::bip16_rule); - const auto bip141 = ctx.is_enabled(flags::bip141_rule); - data_chunk passed(links.size()); - std::vector sigops(links.size()); - std::for_each(poolstl::execution::par, links.cbegin(), links.cend(), - [&](const auto& link) NOEXCEPT - { - if (stopping_) - return; - - const auto offset = std::distance(links.data(), &link); - const auto at = sign_cast(offset); - const auto tx = query.get_transaction(link, true); - if (!tx || accept(*tx, ctx) || !spends_held(*tx) || - tx->connect(ctx)) - return; - - sigops.at(at) = tx->signature_operations(bip16, bip141); - passed.at(at) = one; - }); - - POST(do_revalidated, links, std::move(passed), std::move(sigops), ctx); -} - -// Pool context may have moved under revalidation, and a reorganization under -// it may have unvalidated a row it passed. -void chaser_transaction::do_revalidated(const database::tx_links& links, - const data_chunk& passed, const std::vector& sigops, - const chain::context& ctx) NOEXCEPT -{ - BC_ASSERT(stranded()); - revalidating_ = false; - if (closed()) - return; - - if (unvalidated_ || !is_sufficient(ctx)) - { - retried_.flags = {}; - unvalidated_ = true; - due_ = true; - if (!sweep()) - fault(error::transaction11); - - return; - } - - database::tx_links valid{}; - std::vector counts{}; - for (size_t at{}; at < links.size(); ++at) - { - if (is_zero(passed.at(at))) - continue; - - valid.push_back(links.at(at)); - counts.push_back(sigops.at(at)); - } - - const auto count = valid.size(); - const auto revalidated = database::context::from(ctx); - if (!archive().set_pooled_contexts(valid, counts, revalidated)) - { - fault(error::transaction2); - return; - } - - LOGN("Revalidated (" << count << ") of (" << links.size() - << ") pooled txs."); - - due_ = true; - if (!sweep()) - fault(error::transaction11); -} - -void chaser_transaction::start_scan(bool remap) NOEXCEPT -{ - BC_ASSERT(stranded()); - scanning_ = true; - - const auto& query = archive(); - const auto bound = query.is_pooling() ? query.get_scan_frontier() : - max_size_t; - const auto top = query.to_top_confirmed(); - network::io::post(scan_threadpool_.service(), - BIND(do_scan, top, bound, remap)); -} - -void chaser_transaction::do_scan(const database::header_link& top, - size_t bound, bool remap) NOEXCEPT -{ - POST(do_scanned, archive().set_scan_starts(stopping_, top, bound, remap)); -} - -// Blocks organized during the map are mapped by the bump that follows. -void chaser_transaction::do_scanned(bool mapped) NOEXCEPT -{ - BC_ASSERT(stranded()); - scanning_ = false; - if (closed()) - return; - - if (!mapped) - { - fault(error::transaction8); - return; - } - - do_bump(); -} - // Index transitions are applied in order confirmed, once store is pooling // and while relay is enabled, whether or not pool is open. void chaser_transaction::do_organized(header_t link) NOEXCEPT @@ -511,7 +200,7 @@ void chaser_transaction::do_organized(header_t link) NOEXCEPT fire(events::pool_rows, query.pool_records()); } - top_ = link; + context_.top = link; ++generation_; do_bump(); } @@ -547,71 +236,12 @@ void chaser_transaction::do_reorganized(header_t link) NOEXCEPT } } - top_ = query.to_parent(link); + context_.top = query.to_parent(link); do_bump(); if (pooling_ && repool(link) && !sweep()) fault(error::transaction11); } -// Block's parent becomes pool top with spenders set. -bool chaser_transaction::unvalidate(header_t link) NOEXCEPT -{ - BC_ASSERT(stranded()); - size_t count{}; - if (!archive().set_pool_unvalidated(count, link)) - return false; - - unvalidated_ = unvalidated_ || is_nonzero(count); - due_ = due_ || is_nonzero(count); - return true; -} - -// Pooled in block order under block context, -// excluding any confirmed (by another block). -bool chaser_transaction::repool(header_t link) NOEXCEPT -{ - BC_ASSERT(stranded()); - auto& query = archive(); - chain::context ctx{}; - const auto txs = query.to_transactions(link); - if (txs.empty() || !query.get_context(ctx, link)) - { - fault(error::transaction7); - return false; - } - - if (!reusable(ctx)) - return true; - - // The coinbase is never pooled. - for (auto it = std::next(txs.cbegin()); it != txs.cend(); ++it) - { - const database::tx_link fk{ *it }; - if (query.is_pooled(fk) || query.is_confirmed_tx(fk)) - continue; - - const auto tx = query.get_transaction(fk, true); - if (!tx || !query.populate_with_metadata(*tx)) - { - fault(error::transaction7); - return false; - } - - // Block txs are already silent indexed. - if (!set_pooled(fk, *tx, ctx)) - { - fault(error::transaction2); - return false; - } - - ++generation_; - notify(error::success, chases::transaction{ fk }); - broadcast(*tx); - } - - return true; -} - // Rows confirmed by the pruned block are not retained by the prune. void chaser_transaction::do_pruned(header_t link) NOEXCEPT { @@ -626,8 +256,8 @@ void chaser_transaction::do_pruned(header_t link) NOEXCEPT return; } - floor_ = std::max(floor_, add1(height)); - estimating_ = false; + context_.floor = std::max(context_.floor, add1(height)); + estimate_.estimating = false; } // utility @@ -731,7 +361,7 @@ pool::algorithm::totals_t chaser_transaction::block_limit() const NOEXCEPT const auto& settings = node_settings().pool; const auto reserved = ceilinged_add(fixed, settings.coinbase_weight); const auto weight = floored_subtract(max_block_weight, reserved); - const auto bip141 = pool_.is_enabled(flags::bip141_rule); + const auto bip141 = context_.pool.is_enabled(flags::bip141_rule); const auto limit = bip141 ? max_fast_sigops : max_block_sigops; const auto sigops = floored_subtract(limit, settings.coinbase_sigops); return diff --git a/src/chasers/chaser_transaction_compact.cpp b/src/chasers/chaser_transaction_compact.cpp index 221ecbcf..ef6e8a85 100644 --- a/src/chasers/chaser_transaction_compact.cpp +++ b/src/chasers/chaser_transaction_compact.cpp @@ -267,7 +267,7 @@ bool chaser_transaction::set_pooled(const database::tx_link& link, const auto start = now(); const auto pooled = archive().set_pooled(link, tx, ctx, ctx.timestamp); report(pool_scan::admission, start); - due_ = due_ || (pooled && !is_sufficient(ctx)); + context_.due = context_.due || (pooled && !is_sufficient(ctx)); return pooled; } diff --git a/src/chasers/chaser_transaction_context.cpp b/src/chasers/chaser_transaction_context.cpp new file mode 100644 index 00000000..daa5e5b0 --- /dev/null +++ b/src/chasers/chaser_transaction_context.cpp @@ -0,0 +1,421 @@ +/** + * Copyright (c) 2011-2026 libbitcoin developers + * + * This file is part of libbitcoin. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include + +#include +#include +#include + +namespace libbitcoin { +namespace node { + +#define CLASS chaser_transaction + +using namespace system; +using namespace system::chain; +using namespace std::placeholders; + +BC_PUSH_WARNING(NO_THROW_IN_NOEXCEPT) +BC_PUSH_WARNING(NO_VALUE_OR_CONST_REF_SHARED_PTR) + +// context +// ---------------------------------------------------------------------------- + +// Pool is closed until confirmed chain is current, and closes again if +// currency is lost, though store latch is one way, since txs archived while +// it was open outlive it. +void chaser_transaction::do_bump() NOEXCEPT +{ + BC_ASSERT(stranded()); + estimate_.estimating = false; + const auto opened = pooling_.load(); + pooling_ = false; + if (closed() || !is_current_chain(true)) + { + if (opened) + ++generation_; + + return; + } + + // Pooling is a permanent store property, so it requires relay. + auto& query = archive(); + if (network_settings().enable_relay) + { + // Context of block last applied to index (store top may be above). + size_t height{}; + const auto top = context_.top.is_terminal() ? + query.to_top_confirmed() : context_.top; + if (!query.get_height(height, top)) + { + fault(error::transaction9); + return; + } + + const auto state = top_state(top, height); + if (!state) + { + fault(error::transaction1); + return; + } + + // The context of the next block, in which a pool tx would confirm. + const auto previous = context_.pool; + context_.pool = chain_state{ *state, system_settings() }.context(); + context_.previous = state->hash(); + + // Row holds unless a flag changes or height or median time past falls. + context_.due = context_.due || context_.pool.flags != previous.flags || + context_.pool.height < previous.height || + context_.pool.median_time_past < previous.median_time_past; + + if (!sweep()) + { + fault(error::transaction11); + return; + } + + if (reusable(context_.pool)) + { + query.set_pooling(); + pooling_ = true; + + // Rows that arrived while the pool was closed are not in it. + if (!opened) + context_.floor = std::max(context_.floor, context_.pool.height); + + // Make sweeps deferred to block. + relay_.swept = {}; + if (!relay_.sweeping) + do_sweep_relay(); + } + } + + // Opening or closing the pool changes its templates. + if (pooling_ != opened) + ++generation_; + + // Scan starts are mapped after the latch, as pooled rows are unordered. + if (!query.silent_enabled() || scanning_) + return; + + // Complete map reaches genesis, and keeps up with top until latched. + // Rows of a block archived before latch may precede mapped starts. + const auto top = query.to_top_confirmed(); + const auto unmapped = query.get_scan_start(top).is_terminal(); + if (query.get_scan_start(query.to_confirmed(zero)).is_terminal()) + start_scan(true); + else if (unmapped && !query.is_pooling()) + start_scan(false); + else if (unmapped && query.to_coinbase(top) < query.get_latch_tx()) + start_scan(true); +} + +// private +chain_state::cptr chaser_transaction::top_state( + const database::header_link& top, size_t height) NOEXCEPT +{ + BC_ASSERT(stranded()); + const auto& query = archive(); + if (context_.state && height == context_.state->height() && + query.get_header_key(top) == context_.state->hash()) + return context_.state; + + if (context_.state && height == add1(context_.state->height())) + { + const auto header = query.get_header(top); + if (header && header->previous_block_hash() == context_.state->hash()) + { + context_.state = to_shared(*context_.state, *header, + system_settings()); + return context_.state; + } + } + + context_.state = query.get_confirmed_chain_state(system_settings(), top, + height); + return context_.state; +} + +bool chaser_transaction::is_indexing() const NOEXCEPT +{ + return network_settings().enable_relay && archive().is_pooling(); +} + +bool chaser_transaction::reusable(const chain::context& ctx) const NOEXCEPT +{ + const auto evaluated = database::context::from(ctx); + return archive().is_sufficient(evaluated, evaluated); +} + +bool chaser_transaction::is_sufficient( + const chain::context& ctx) const NOEXCEPT +{ + return archive().is_sufficient(database::context::from(context_.pool), + database::context::from(ctx)); +} + +// Sweep remains due while it leaves any row unsatisfied, so row is restored +// once pool context satisfies it. +bool chaser_transaction::sweep() NOEXCEPT +{ + BC_ASSERT(stranded()); + auto& query = archive(); + if (!context_.due || !query.is_pooling()) + return true; + + size_t count{}; + const auto start = now(); + const auto applied = query.set_pool_context(count, + database::context::from(context_.pool)); + + report(pool_scan::context, start); + context_.due = !applied || is_nonzero(count); + if (applied && is_nonzero(count)) + start_revalidation(); + + return applied; +} + +// Rows left out by flags are revalidated once per change of flags, and rows +// not validated once per change of pool context, so failing row is retried +// only under another context. +void chaser_transaction::start_revalidation() NOEXCEPT +{ + BC_ASSERT(stranded()); + if (context_.revalidating) + return; + + const auto flagged = context_.pool.flags != context_.retried.flags; + const auto moved = context_.unvalidated || + context_.pool.height != context_.retried.height || + context_.pool.median_time_past != context_.retried.median_time_past; + + if (!flagged && !moved) + return; + + auto& query = archive(); + database::tx_links links{}; + database::tx_links unvalidated{}; + const auto ctx = database::context::from(context_.pool); + code ec{}; + if (flagged) + ec = query.get_pool_revalidation(links, ctx); + + if (!ec) + ec = query.get_pool_unvalidated(unvalidated); + + if (ec) + { + fault(ec); + return; + } + + links.insert(links.end(), unvalidated.begin(), unvalidated.end()); + + context_.retried = context_.pool; + context_.unvalidated = false; + if (links.empty()) + return; + + context_.revalidating = true; + network::io::post(revalidation_threadpool_.service(), + BIND(do_revalidate, std::move(links), context_.pool)); +} + +// Revalidation is admission under context, as confirmation of what a row spends +// may differ from when it was pooled. Sigops are counted under flags of +// context, so a passing tx is counted again. +void chaser_transaction::do_revalidate(const database::tx_links& links, + const chain::context& ctx) NOEXCEPT +{ + const auto& query = archive(); + const auto bip16 = ctx.is_enabled(flags::bip16_rule); + const auto bip141 = ctx.is_enabled(flags::bip141_rule); + data_chunk passed(links.size()); + std::vector sigops(links.size()); + std::for_each(poolstl::execution::par, links.cbegin(), links.cend(), + [&](const auto& link) NOEXCEPT + { + if (stopping_) + return; + + const auto offset = std::distance(links.data(), &link); + const auto at = sign_cast(offset); + const auto tx = query.get_transaction(link, true); + if (!tx || accept(*tx, ctx) || !spends_held(*tx) || + tx->connect(ctx)) + return; + + sigops.at(at) = tx->signature_operations(bip16, bip141); + passed.at(at) = one; + }); + + POST(do_revalidated, links, std::move(passed), std::move(sigops), ctx); +} + +// Pool context may have moved under revalidation, and a reorganization under +// it may have unvalidated a row it passed. +void chaser_transaction::do_revalidated(const database::tx_links& links, + const data_chunk& passed, const std::vector& sigops, + const chain::context& ctx) NOEXCEPT +{ + BC_ASSERT(stranded()); + context_.revalidating = false; + if (closed()) + return; + + if (context_.unvalidated || !is_sufficient(ctx)) + { + context_.retried.flags = {}; + context_.unvalidated = true; + context_.due = true; + if (!sweep()) + fault(error::transaction11); + + return; + } + + database::tx_links valid{}; + std::vector counts{}; + for (size_t at{}; at < links.size(); ++at) + { + if (is_zero(passed.at(at))) + continue; + + valid.push_back(links.at(at)); + counts.push_back(sigops.at(at)); + } + + const auto count = valid.size(); + const auto revalidated = database::context::from(ctx); + if (!archive().set_pooled_contexts(valid, counts, revalidated)) + { + fault(error::transaction2); + return; + } + + LOGN("Revalidated (" << count << ") of (" << links.size() + << ") pooled txs."); + + context_.due = true; + if (!sweep()) + fault(error::transaction11); +} + +void chaser_transaction::start_scan(bool remap) NOEXCEPT +{ + BC_ASSERT(stranded()); + scanning_ = true; + + const auto& query = archive(); + const auto bound = query.is_pooling() ? query.get_scan_frontier() : + max_size_t; + const auto top = query.to_top_confirmed(); + network::io::post(scan_threadpool_.service(), + BIND(do_scan, top, bound, remap)); +} + +void chaser_transaction::do_scan(const database::header_link& top, + size_t bound, bool remap) NOEXCEPT +{ + POST(do_scanned, archive().set_scan_starts(stopping_, top, bound, remap)); +} + +// Blocks organized during the map are mapped by the bump that follows. +void chaser_transaction::do_scanned(bool mapped) NOEXCEPT +{ + BC_ASSERT(stranded()); + scanning_ = false; + if (closed()) + return; + + if (!mapped) + { + fault(error::transaction8); + return; + } + + do_bump(); +} + +// Block's parent becomes pool top with spenders set. +bool chaser_transaction::unvalidate(header_t link) NOEXCEPT +{ + BC_ASSERT(stranded()); + size_t count{}; + if (!archive().set_pool_unvalidated(count, link)) + return false; + + context_.unvalidated = context_.unvalidated || is_nonzero(count); + context_.due = context_.due || is_nonzero(count); + return true; +} + +// Pooled in block order under block context, +// excluding any confirmed (by another block). +bool chaser_transaction::repool(header_t link) NOEXCEPT +{ + BC_ASSERT(stranded()); + auto& query = archive(); + chain::context ctx{}; + const auto txs = query.to_transactions(link); + if (txs.empty() || !query.get_context(ctx, link)) + { + fault(error::transaction7); + return false; + } + + if (!reusable(ctx)) + return true; + + // The coinbase is never pooled. + for (auto it = std::next(txs.cbegin()); it != txs.cend(); ++it) + { + const database::tx_link fk{ *it }; + if (query.is_pooled(fk) || query.is_confirmed_tx(fk)) + continue; + + const auto tx = query.get_transaction(fk, true); + if (!tx || !query.populate_with_metadata(*tx)) + { + fault(error::transaction7); + return false; + } + + // Block txs are already silent indexed. + if (!set_pooled(fk, *tx, ctx)) + { + fault(error::transaction2); + return false; + } + + ++generation_; + notify(error::success, chases::transaction{ fk }); + broadcast(*tx); + } + + return true; +} + +BC_POP_WARNING() +BC_POP_WARNING() + +} // namespace node +} // namespace libbitcoin diff --git a/src/chasers/chaser_transaction_query.cpp b/src/chasers/chaser_transaction_query.cpp index 9ce31e39..fa02c2d2 100644 --- a/src/chasers/chaser_transaction_query.cpp +++ b/src/chasers/chaser_transaction_query.cpp @@ -150,7 +150,7 @@ void chaser_transaction::do_build_template( settings.bytes_per_sigop, settings.maximum_outcomes); report(pool_scan::template_, start); - handler(ec, pool_, previous_, links); + handler(ec, context_.pool, context_.previous, links); } // private @@ -190,25 +190,25 @@ void chaser_transaction::do_estimate(size_t target, estimate_mode mode, const auto start = now(); // Targets estimated while the projection is held are of one pool. - const auto held = estimating_ && - (start - estimated_) < settings.estimate_cache(); + const auto held = estimate_.estimating && + (start - estimate_.estimated) < settings.estimate_cache(); if (!held) { - projection_ = {}; - arrived_ = false; - estimated_ = start; + estimate_.projection = {}; + estimate_.arrived = false; + estimate_.estimated = start; } const auto projected = held ? - query.get_pool_continuation(projection_, count, limit, + query.get_pool_continuation(estimate_.projection, count, limit, settings.maximum_chunk_depth, settings.bytes_per_sigop) : - query.get_pool_projection(projection_, count, limit, + query.get_pool_projection(estimate_.projection, count, limit, settings.maximum_chunk_depth, settings.cutoff_rate_(), settings.bytes_per_sigop, settings.maximum_outcomes); report(pool_scan::projection, start); - estimating_ = !projected; + estimate_.estimating = !projected; if (projected) { handler(fault(projected), {}); @@ -216,32 +216,33 @@ void chaser_transaction::do_estimate(size_t target, estimate_mode mode, } // Arrivals are whole from the floor to the height of the open interval. - if (mode != estimate_mode::basic && !arrived_) + if (mode != estimate_mode::basic && !estimate_.arrived) { - const auto whole = floored_subtract(pool_.height, floor_); + const auto whole = floored_subtract(context_.pool.height, + context_.floor); const auto heights = std::min(whole, conservative_estimate_window); - if (const auto ec = query.get_pool_arrivals(arrivals_, pool_.height, - heights, settings.bytes_per_sigop)) + if (const auto ec = query.get_pool_arrivals(estimate_.arrivals, + context_.pool.height, heights, settings.bytes_per_sigop)) { - estimating_ = false; + estimate_.estimating = false; handler(fault(ec), {}); return; } - arrived_ = true; + estimate_.arrived = true; } const auto arrive = [&](uint64_t rate) NOEXCEPT { - return arriving(arrivals_, rate, mode); + return arriving(estimate_.arrivals, rate, mode); }; using algorithm = pool::algorithm; const auto space = limit.weight; const auto room = ceilinged_multiply(settings.estimate_room, light_weight_factor); - const auto rate = algorithm::estimate(projection_, count, space, room, - arrive); + const auto rate = algorithm::estimate(estimate_.projection, count, space, + room, arrive); if (rate == max_uint64) { handler(error::estimate_false, {}); diff --git a/src/chasers/chaser_transaction_relay.cpp b/src/chasers/chaser_transaction_relay.cpp index ef52373b..9e593a35 100644 --- a/src/chasers/chaser_transaction_relay.cpp +++ b/src/chasers/chaser_transaction_relay.cpp @@ -107,23 +107,23 @@ void chaser_transaction::do_activate_relay(size_t slot, object_key key) NOEXCEPT { BC_ASSERT(stranded()); - keys_.at(slot) = key; - set_right_into(relaying_, slot); - if (!sweeping_) + relay_.keys.at(slot) = key; + set_right_into(relay_.relaying, slot); + if (!relay_.sweeping) do_sweep_relay(); } void chaser_transaction::do_release_relay(size_t slot) NOEXCEPT { BC_ASSERT(stranded()); - for (auto& mark: marks_) + for (auto& mark: relay_.marks) set_right_into(mark, slot, false); - rates_.at(slot) = zero; - keys_.at(slot) = {}; - set_right_into(relaying_, slot, false); - set_right_into(owed_, slot, false); - set_right_into(swept_, slot, false); + relay_.rates.at(slot) = zero; + relay_.keys.at(slot) = {}; + set_right_into(relay_.relaying, slot, false); + set_right_into(relay_.owed, slot, false); + set_right_into(relay_.swept, slot, false); reserved_.fetch_and(bit_not(bit_right(slot))); } @@ -131,8 +131,8 @@ void chaser_transaction::do_release_relay(size_t slot) NOEXCEPT void chaser_transaction::do_set_relay_rate(size_t slot, uint64_t rate) NOEXCEPT { BC_ASSERT(stranded()); - const auto prior = rates_.at(slot); - rates_.at(slot) = rate; + const auto prior = relay_.rates.at(slot); + relay_.rates.at(slot) = rate; if (rate < prior) owe_relay(slot); } @@ -148,28 +148,29 @@ void chaser_transaction::do_relay_pool(size_t slot) NOEXCEPT void chaser_transaction::owe_relay(size_t slot) NOEXCEPT { BC_ASSERT(stranded()); - set_right_into(owed_, slot); - if (!sweeping_) + set_right_into(relay_.owed, slot); + if (!relay_.sweeping) do_sweep_relay(); } // private uint64_t chaser_transaction::sweepable() const NOEXCEPT { - return bit_and(bit_and(owed_, relaying_), bit_not(swept_)); + return bit_and(bit_and(relay_.owed, relay_.relaying), + bit_not(relay_.swept)); } // One slot swept per strand turn, so sweeps do not hold up other work. void chaser_transaction::do_sweep_relay() NOEXCEPT { BC_ASSERT(stranded()); - sweeping_ = false; + relay_.sweeping = false; if (closed() || !pooling_ || is_zero(sweepable())) return; const auto slot = right_zeros(sweepable()); - set_right_into(owed_, slot, false); - set_right_into(swept_, slot); + set_right_into(relay_.owed, slot, false); + set_right_into(relay_.swept, slot); if (!sweep_relay(slot)) { fault(database::error::integrity); @@ -179,7 +180,7 @@ void chaser_transaction::do_sweep_relay() NOEXCEPT if (is_zero(sweepable())) return; - sweeping_ = true; + relay_.sweeping = true; POST(do_sweep_relay); } @@ -198,7 +199,7 @@ bool chaser_transaction::sweep_relay(size_t slot) NOEXCEPT if (row.is_terminal() || get_right(marks(row.value), slot)) continue; - if (!relay({ link }, relay_slots, word, keys_.at(slot))) + if (!relay({ link }, relay_slots, word, relay_.keys.at(slot))) return false; } @@ -256,7 +257,7 @@ bool chaser_transaction::relay(const database::tx_links& links, { const auto weight = weights.at(slot); if (!is_zero(weight) && weight <= limit && - algorithm::covered(fees.at(slot), weight, rates_.at(slot))) + algorithm::covered(fees.at(slot), weight, relay_.rates.at(slot))) set_right_into(clears, slot); } @@ -281,10 +282,10 @@ bool chaser_transaction::relay(const database::tx_links& links, // private uint64_t& chaser_transaction::marks(size_t row) NOEXCEPT { - if (row >= marks_.size()) - marks_.resize(add1(row)); + if (row >= relay_.marks.size()) + relay_.marks.resize(add1(row)); - return marks_.at(row); + return relay_.marks.at(row); } BC_POP_WARNING() diff --git a/src/chasers/chaser_transaction_submit.cpp b/src/chasers/chaser_transaction_submit.cpp index e5b09363..5c03f877 100644 --- a/src/chasers/chaser_transaction_submit.cpp +++ b/src/chasers/chaser_transaction_submit.cpp @@ -124,9 +124,10 @@ void chaser_transaction::submit_announced(const transactions_cptr& txs, } // private -// Set is tested prefix by prefix. Running set is its unstored txs since last -// prefix to clear, and clears when its coverage does. It is then connected -// and admitted, and next tx starts another. Announced set is a batch, not a +// Set is reserved on the strand, validated in parallel under the pool context, +// then admitted on the strand prefix by prefix. Running set is its unstored txs +// since last prefix to clear, and clears when its coverage does. It is then +// admitted, and next tx starts another. Announced set is a batch, not a // package, so a tx of it not accepted, or exceeding a pool limit, is passed // over as if stored. A tx is accepted only if each parent is confirmed, // pooled, or accepted before it in set. @@ -147,55 +148,152 @@ void chaser_transaction::do_submit(const transactions_cptr& txs, bool test, return; } - const auto begin = now(); - submission set{ txs, slot, network::unix_time(), test, announced }; - hold(set); - if (const auto ec = check(*txs, set.stored, announced)) + enter(std::make_shared(submission { - handler(ec, {}); + txs, slot, network::unix_time(), test, announced, handler, {}, now() + })); +} + +// private +// A set waits for the validation of another set that it includes or spends. +void chaser_transaction::enter(const submission_ptr& set) NOEXCEPT +{ + BC_ASSERT(stranded()); + hold(*set); + if (is_dependent(*set)) + { + submit_.waiting.push_back(set); return; } - for (size_t index{}; index < txs->size(); ++index) + const auto& txs = *set->txs; + if (txs.empty()) { - if (set.stored.at(index)) + set->handler(error::empty_package, {}); + return; + } + + if (std::ranges::all_of(set->stored, std::identity{})) + { + set->handler(error::duplicate_transaction, {}); + return; + } + + for (size_t index{}; index < txs.size(); ++index) + { + if (set->stored.at(index)) continue; - const auto& tx = *txs->at(index); - auto ec = accept(tx, pool_); - if (!ec && !spends_held(set, tx)) + submit_.validating.insert(txs.at(index)->get_hash(false)); + set->reserved.push_back(index); + } + + set->ctx = context_.pool; + PARALLEL(do_validate, set); +} + +// private +// Script validation is most costly, and runs here off the pool strand. +void chaser_transaction::do_validate(const submission_ptr& set) NOEXCEPT +{ + if (!closed()) + { + const auto& txs = *set->txs; + set->accepted.assign(txs.size(), error::success); + set->checked = check(txs, set->stored, set->announced, set->ctx); + if (!set->checked) + { + const auto connecting = now(); + for (size_t index{}; index < txs.size(); ++index) + { + if (set->stored.at(index)) + continue; + + const auto& tx = *txs.at(index); + auto ec = accept(tx, set->ctx); + if (!ec) ec = tx.connect(set->ctx); + set->accepted.at(index) = ec; + } + + fire_span(events::pool_connect_usecs, connecting); + } + } + + POST(do_validated, set); +} + +// private +// A set validated under a context that no longer holds is validated again. +void chaser_transaction::do_validated(const submission_ptr& set) NOEXCEPT +{ + BC_ASSERT(stranded()); + + if (closed()) + { + complete(set, network::error::service_stopped, {}); + return; + } + + if (!pooling_) + { + complete(set, error::pooling_disabled, {}); + return; + } + + if (!is_sufficient(set->ctx)) + { + set->ctx = context_.pool; + PARALLEL(do_validate, set); + return; + } + + if (set->checked) + { + complete(set, set->checked, {}); + return; + } + + const auto& txs = *set->txs; + for (size_t index{}; index < txs.size(); ++index) + { + if (set->stored.at(index)) + continue; + + const auto& tx = *txs.at(index); + auto ec = set->accepted.at(index); + if (!ec && !spends_held(*set, tx)) ec = system::error::missing_previous_output; if (ec) { - if (!announced) + if (!set->announced) { - handler(ec, index); + complete(set, ec, index); return; } - pass_over(set, index, ec); + pass_over(*set, index, ec); continue; } bool covered{}; - set.held.insert(tx.get_hash(false)); - ec = extend(covered, set, index); + set->held.insert(tx.get_hash(false)); + ec = extend(covered, *set, index); if (ec == database::error::pool_limit) { - if (!announced) + if (!set->announced) { - handler(ec, set.first); + complete(set, ec, set->first); return; } - pass_over(set, index, ec); - ec = restore(set, index); + pass_over(*set, index, ec); + ec = restore(*set, index); } if (ec) { - handler(ec, index); + complete(set, ec, index); return; } @@ -203,24 +301,72 @@ void chaser_transaction::do_submit(const transactions_cptr& txs, bool test, continue; size_t at{}; - ec = clear(at, set, index); + ec = clear(at, *set, index); if (ec) { - handler(ec, at); + complete(set, ec, at); return; } } - if (set.cleared) - fire_span(events::pool_submit_usecs, begin); + if (set->cleared) + fire_span(events::pool_submit_usecs, set->begin); // A set that ends uncleared fails at the first tx of the uncleared set. - if (set.failure) - handler(set.failure, set.passed); - else if (set.running) - handler(error::insufficient_fee, set.first); + if (set->failure) + complete(set, set->failure, set->passed); + else if (set->running) + complete(set, error::insufficient_fee, set->first); else - handler(error::success, {}); + complete(set, error::success, {}); +} + +// private +// Reservations are released before the handler, then waiting sets reenter. +void chaser_transaction::complete(const submission_ptr& set, const code& ec, + size_t index) NOEXCEPT +{ + BC_ASSERT(stranded()); + for (const auto at: set->reserved) + submit_.validating.erase(set->txs->at(at)->get_hash(false)); + + set->reserved.clear(); + set->handler(ec, index); + + auto waiting = std::move(submit_.waiting); + submit_.waiting.clear(); + for (const auto& next: waiting) + { + if (closed()) + next->handler(network::error::service_stopped, {}); + else + enter(next); + } +} + +// private +// An unstored tx of the set, or a tx that one spends, is under validation. +bool chaser_transaction::is_dependent(const submission& set) const NOEXCEPT +{ + BC_ASSERT(stranded()); + if (submit_.validating.empty()) + return false; + + for (size_t index{}; index < set.txs->size(); ++index) + { + if (set.stored.at(index)) + continue; + + const auto& tx = *set.txs->at(index); + if (submit_.validating.contains(tx.get_hash(false))) + return true; + + for (const auto& in: *tx.inputs_ptr()) + if (submit_.validating.contains(in->point().hash())) + return true; + } + + return false; } // private @@ -312,7 +458,7 @@ code chaser_transaction::extend(bool& covered, submission& set, covered = false; auto& query = archive(); const auto& tx = *set.txs->at(index); - const auto ctx = database::context::from(pool_); + const auto ctx = database::context::from(context_.pool); if (const auto ec = query.get_pool_candidate(set.graph, tx, ctx)) return fault(ec); @@ -359,7 +505,7 @@ code chaser_transaction::extend(bool& covered, submission& set, code chaser_transaction::restore(submission& set, size_t index) NOEXCEPT { auto& query = archive(); - const auto ctx = database::context::from(pool_); + const auto ctx = database::context::from(context_.pool); set.graph = {}; set.weight = set.sigops = zero; set.running = false; @@ -380,23 +526,10 @@ code chaser_transaction::restore(submission& set, size_t index) NOEXCEPT } // private -// Script validation is most costly, so it follows guards. In a test, cleared -// txs are not pooled, so remain given candidates. +// In a test, cleared txs are not pooled, so remain given candidates. code chaser_transaction::clear(size_t& at, submission& set, size_t index) NOEXCEPT { - const auto connecting = now(); - for (at = set.first; at <= index; ++at) - { - if (set.stored.at(at)) - continue; - - if (const auto ec = set.txs->at(at)->connect(pool_)) - return ec; - } - - fire_span(events::pool_connect_usecs, connecting); - // The graph holds accessors, released before the index is written. if (set.test) set.given = set.graph.candidates.size(); @@ -419,7 +552,7 @@ code chaser_transaction::clear(size_t& at, submission& set, set.cleared = true; } - if (!admitted.empty() && !relay(admitted, set.slot, relaying_)) + if (!admitted.empty() && !relay(admitted, set.slot, relay_.relaying)) { at = set.first; return fault(database::error::integrity); @@ -436,7 +569,8 @@ code chaser_transaction::clear(size_t& at, submission& set, // Tx of announced set preceding its parent is not accepted, and its txs that // spend one point are rivals. code chaser_transaction::check(const transaction_cptrs& txs, - const std::vector& stored, bool announced) NOEXCEPT + const std::vector& stored, bool announced, + const chain::context& ctx) NOEXCEPT { if (txs.empty()) return error::empty_package; @@ -450,7 +584,7 @@ code chaser_transaction::check(const transaction_cptrs& txs, if (!announced && block::is_internal_double_spend(txs, false)) return system::error::block_internal_double_spend; - return block::populate(txs, pool_, false); + return block::populate(txs, ctx, false); } code chaser_transaction::admit(database::tx_link& link, @@ -468,7 +602,7 @@ code chaser_transaction::admit(database::tx_link& link, size_t repooled{}; const auto start = now(); const auto admitted = query.set_pooled(repooled, link, tx, - database::context::from(pool_), time, sigops, archived); + database::context::from(context_.pool), time, sigops, archived); report(pool_scan::admission, start); if (!admitted) @@ -477,8 +611,8 @@ code chaser_transaction::admit(database::tx_link& link, // Spender pooled again keeps its context, and may now pass if failed. if (is_nonzero(repooled)) { - due_ = true; - unvalidated_ = true; + context_.due = true; + context_.unvalidated = true; if (!sweep()) return fault(error::transaction11); } diff --git a/src/protocols/protocol_transaction_out_70013.cpp b/src/protocols/protocol_transaction_out_70013.cpp index d8548a90..473c82a8 100644 --- a/src/protocols/protocol_transaction_out_70013.cpp +++ b/src/protocols/protocol_transaction_out_70013.cpp @@ -47,6 +47,14 @@ void protocol_transaction_out_70013::start() NOEXCEPT protocol_transaction_out_70001::start(); } +void protocol_transaction_out_70013::stopping(const code& ec) NOEXCEPT +{ + BC_ASSERT(stranded()); + + if (fee_timer_) fee_timer_->stop(); + protocol_transaction_out_70001::stopping(ec); +} + // Peer is told what to send once relay to it starts. void protocol_transaction_out_70013::subscribed(const code& ec, object_key key) NOEXCEPT @@ -122,11 +130,35 @@ bool protocol_transaction_out_70013::handle_receive_fee_filter(const code& ec, if (stopped(ec)) return false; + // A null fee timer implies no limit on lowering. + if (fee_timer_ && message->minimum_fee < minimum_fee()) + { + if (lowered_) + { + LOGR("Fee filter lowered again within period by [" << opposite() + << "]."); + stop(network::error::protocol_violation); + return false; + } + + lowered_ = true; + fee_timer_->start(BIND(handle_fee_timer, _1)); + } + set_minimum_fee(message->minimum_fee); set_relay_rate(message->minimum_fee); return true; } +// private +void protocol_transaction_out_70013::handle_fee_timer(const code& ec) NOEXCEPT +{ + BC_ASSERT(stranded()); + + if (!ec) + lowered_ = false; +} + BC_POP_WARNING() BC_POP_WARNING() diff --git a/src/settings.cpp b/src/settings.cpp index 934e0833..d5d752ee 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -108,7 +108,8 @@ settings::settings() NOEXCEPT sample_period_seconds{ 10 }, compact_timeout_seconds{ 10 }, compact_missing_percent{ 50 }, - currency_window_minutes{ 1440 } + currency_window_minutes{ 1440 }, + fee_filter_minutes{ 60 } { } @@ -230,6 +231,11 @@ network::wall_clock::duration settings::currency_window() const NOEXCEPT return network::minutes(currency_window_minutes); } +network::steady_clock::duration settings::fee_filter_period() const NOEXCEPT +{ + return network::minutes(fee_filter_minutes); +} + network::processing_priority settings::thread_priority_() const NOEXCEPT { // medium is "normal" (os default), so true is a behavior change. diff --git a/test/protocols/protocol_transaction.cpp b/test/protocols/protocol_transaction.cpp index c7000097..203c2b2b 100644 --- a/test/protocols/protocol_transaction.cpp +++ b/test/protocols/protocol_transaction.cpp @@ -573,6 +573,29 @@ BC_FIXTURE_TEST_CASE(protocol_transaction_out__fee_filter__rate_fall__swept_inve BC_REQUIRE_EQUAL(announced(1), expected); } +BC_FIXTURE_TEST_CASE(protocol_transaction_out__fee_filter__second_fall_within_period__dropped, chaser_transaction_pooling_setup_fixture) +{ + BC_REQUIRE(handshake(0, peer::level::maximum_protocol, true)); + send(peer::fee_filter{ 100'000 }, node_version->value); + send(peer::fee_filter{ 10'000 }, node_version->value); + BC_REQUIRE(!received_before_pong(peer::inventory::command)); + + send(peer::fee_filter{ 1'000 }, node_version->value); + send(peer::ping{ 42 }, node_version->value); + BC_REQUIRE(dropped(peer::pong::command)); +} + +BC_FIXTURE_TEST_CASE(protocol_transaction_out__fee_filter__rises_after_fall__kept, chaser_transaction_pooling_setup_fixture) +{ + BC_REQUIRE(handshake(0, peer::level::maximum_protocol, true)); + send(peer::fee_filter{ 100'000 }, node_version->value); + send(peer::fee_filter{ 10'000 }, node_version->value); + send(peer::fee_filter{ 20'000 }, node_version->value); + send(peer::fee_filter{ 30'000 }, node_version->value); + send(peer::ping{ 42 }, node_version->value); + BC_REQUIRE(!dropped(peer::pong::command)); +} + BC_FIXTURE_TEST_CASE(protocol_transaction_out__start__no_relay_slot__max_money_fee_filter, chaser_transaction_pooling_setup_fixture) { reserve_relays(); diff --git a/test/settings.cpp b/test/settings.cpp index c1ce916d..dd2b5224 100644 --- a/test/settings.cpp +++ b/test/settings.cpp @@ -59,6 +59,7 @@ BC_AUTO_TEST_CASE(settings__node__default_context__expected) BC_REQUIRE_EQUAL(node.compact_timeout_seconds, 10_u16); BC_REQUIRE_EQUAL(node.compact_missing_percent, 50_u8); BC_REQUIRE_EQUAL(node.currency_window_minutes, 1440_u32); + BC_REQUIRE_EQUAL(node.fee_filter_minutes, 60_u16); ////BC_REQUIRE_EQUAL(node.snapshot_bytes, 200'000'000'000_u64); ////BC_REQUIRE_EQUAL(node.snapshot_valid, 250'000_u32); ////BC_REQUIRE_EQUAL(node.snapshot_confirm, 500'000_u32); @@ -73,6 +74,7 @@ BC_AUTO_TEST_CASE(settings__node__default_context__expected) BC_REQUIRE_EQUAL(node.batch_silent_(), node.use_gpu_()); BC_REQUIRE(node.sample_period() == steady_clock::duration(seconds(10))); BC_REQUIRE(node.currency_window() == steady_clock::duration(minutes(1440))); + BC_REQUIRE(node.fee_filter_period() == steady_clock::duration(minutes(60))); BC_REQUIRE(node.thread_priority_() == network::processing_priority::high); }