Debian Codegraph @

monero/src/cryptonote_core/tx_pool.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include <algorithm>
32 #include <boost/filesystem.hpp>
33 #include <unordered_set>
34 #include <vector>
35
36 #include "tx_pool.h"
37 #include "cryptonote_tx_utils.h"
38 #include "cryptonote_basic/cryptonote_boost_serialization.h"
39 #include "cryptonote_basic/events.h"
40 #include "cryptonote_config.h"
41 #include "blockchain.h"
42 #include "blockchain_db/locked_txn.h"
43 #include "blockchain_db/blockchain_db.h"
44 #include "common/boost_serialization_helper.h"
45 #include "int-util.h"
46 #include "misc_language.h"
47 #include "misc_log_ex.h"
48 #include "tx_verification_utils.h"
49 #include "warnings.h"
50 #include "common/perf_timer.h"
51 #include "crypto/hash.h"
52 #include "crypto/duration.h"
53
54 #undef MONERO_DEFAULT_LOG_CATEGORY
55 #define MONERO_DEFAULT_LOG_CATEGORY "txpool"
56
57 DISABLE_VS_WARNINGS(4244 4345 4503) //'boost::foreach_detail_::or_' : decorated name length exceeded, name was truncated
58
59 using namespace crypto;
60
61 namespace cryptonote
62 {
63 namespace
64 {
65 /*! The Dandelion++ has formula for calculating the average embargo timeout:
66 (-k*(k-1)*hop)/(2*log(1-ep))
67 where k is the number of hops before this node and ep is the probability
68 that one of the k hops hits their embargo timer, and hop is the average
69 time taken between hops. So decreasing ep will make it more probable
70 that "this" node is the first to expire the embargo timer. Increasing k
71 will increase the number of nodes that will be "hidden" as a prior
72 recipient of the tx.
73
74 As example, k=5 and ep=0.1 means "this" embargo timer has a 90%
75 probability of being the first to expire amongst 5 nodes that saw the
76 tx before "this" one. These values are independent to the fluff
77 probability, but setting a low k with a low p (fluff probability) is
78 not ideal since a blackhole is more likely to reveal earlier nodes in
79 the chain.
80
81 This value was calculated with k=5, ep=0.10, and hop = 175 ms. A
82 testrun from a recent Intel laptop took ~80ms to
83 receive+parse+proces+send transaction. At least 50ms will be added to
84 the latency if crossing an ocean. So 175ms is the fudge factor for
85 a single hop with 39s being the embargo timer. */
86 constexpr const std::chrono::seconds dandelionpp_embargo_average{CRYPTONOTE_DANDELIONPP_EMBARGO_AVERAGE};
87
88 //TODO: constants such as these should at least be in the header,
89 // but probably somewhere more accessible to the rest of the
90 // codebase. As it stands, it is at best nontrivial to test
91 // whether or not changing these parameters (or adding new)
92 // will work correctly.
93 time_t const MIN_RELAY_TIME = (60 * 5); // only start re-relaying transactions after that many seconds
94 time_t const MAX_RELAY_TIME = (60 * 60 * 4); // at most that many seconds between resends
95 float const ACCEPT_THRESHOLD = 1.0f;
96
97 //! Max DB check interval for relayable txes
98 constexpr const std::chrono::minutes max_relayable_check{2};
99
100 constexpr const std::chrono::seconds forward_delay_average{CRYPTONOTE_FORWARD_DELAY_AVERAGE};
101
102 // a kind of increasing backoff within min/max bounds
103 uint64_t get_relay_delay(time_t last_relay, time_t received)
104 {
105 time_t d = (last_relay - received + MIN_RELAY_TIME) / MIN_RELAY_TIME * MIN_RELAY_TIME;
106 if (d > MAX_RELAY_TIME)
107 d = MAX_RELAY_TIME;
108 return d;
109 }
110
111 uint64_t template_accept_threshold(uint64_t amount)
112 {
113 return amount * ACCEPT_THRESHOLD;
114 }
115
116 // external lock must be held for the comparison+set to work properly
117 void set_if_less(std::atomic<time_t>& next_check, const time_t candidate) noexcept
118 {
119 if (candidate < next_check.load(std::memory_order_relaxed))
120 next_check = candidate;
121 }
122 }
123 //---------------------------------------------------------------------------------
124 //---------------------------------------------------------------------------------
125 tx_memory_pool::tx_memory_pool(Blockchain& bchs): m_blockchain(bchs), m_cookie(0), m_txpool_max_weight(DEFAULT_TXPOOL_MAX_WEIGHT), m_txpool_weight(0), m_mine_stem_txes(false), m_next_check(std::time(nullptr))
126 {
127 // class code expects unsigned values throughout
128 if (m_next_check < time_t(0))
129 throw std::runtime_error{"Unexpected time_t (system clock) value"};
130
131 m_added_txs_start_time = (time_t)0;
132 m_removed_txs_start_time = (time_t)0;
133 // We don't set these to "now" already here as we don't know how long it takes from construction
134 // of the pool until it "goes to work". It's safer to set when the first actual txs enter the
135 // corresponding lists.
136 }
137 //---------------------------------------------------------------------------------
138 bool tx_memory_pool::add_tx(transaction &tx, /*const crypto::hash& tx_prefix_hash,*/
139 const crypto::hash &id, const cryptonote::blobdata &blob, size_t tx_weight,
140 tx_verification_context& tvc, relay_method tx_relay, bool relayed,
141 uint8_t version, uint8_t nic_verified_hf_version)
142 {
143 const bool kept_by_block = (tx_relay == relay_method::block);
144
145 // this should already be called with that lock, but let's make it explicit for clarity
146 CRITICAL_REGION_LOCAL(m_transactions_lock);
147
148 PERF_TIMER(add_tx);
149
150 // we do not accept transactions that timed out before, unless they're
151 // kept_by_block
152 if (!kept_by_block && m_timed_out_transactions.find(id) != m_timed_out_transactions.end())
153 {
154 // not clear if we should set that, since verifivation (sic) did not fail before, since
155 // the tx was accepted before timing out.
156 tvc.m_verifivation_failed = true;
157 return false;
158 }
159
160 if (version != nic_verified_hf_version && !cryptonote::ver_non_input_consensus(tx, tvc, version))
161 {
162 LOG_PRINT_L1("transaction " << id << " failed non-input consensus rule checks");
163 tvc.m_verifivation_failed = true; // should already be set, but just in case
164 return false;
165 }
166
167 uint64_t fee;
168 bool fee_good = false;
169 try
170 {
171 // get_tx_fee() can throw. It shouldn't throw because we check preconditions in
172 // ver_non_input_consensus(), but let's put it in a try block just in case.
173 fee = get_tx_fee(tx);
174 fee_good = kept_by_block || m_blockchain.check_fee(tx_weight, fee);
175 }
176 catch(...) {}
177 if (!fee_good) // if fee calculation failed or fee in relayed tx is too low...
178 {
179 tvc.m_verifivation_failed = true;
180 tvc.m_fee_too_low = true;
181 tvc.m_no_drop_offense = true;
182 return false;
183 }
184
185 size_t tx_extra_size = tx.extra.size();
186 if (!kept_by_block && tx_extra_size > MAX_TX_EXTRA_SIZE)
187 {
188 LOG_PRINT_L1("transaction tx-extra is too big: " << tx_extra_size << " bytes, the limit is: " << MAX_TX_EXTRA_SIZE);
189 tvc.m_verifivation_failed = true;
190 tvc.m_tx_extra_too_big = true;
191 tvc.m_no_drop_offense = true;
192 return false;
193 }
194
195 if (!kept_by_block && tx.unlock_time)
196 {
197 LOG_PRINT_L1("transaction unlock time is not zero: " << tx.unlock_time);
198 tvc.m_verifivation_failed = true;
199 tvc.m_nonzero_unlock_time = true;
200 tvc.m_no_drop_offense = true;
201 return false;
202 }
203
204 // if the transaction came from a block popped from the chain,
205 // don't check if we have its key images as spent.
206 // TODO: Investigate why not?
207 if(!kept_by_block)
208 {
209 if(have_tx_keyimges_as_spent(tx, id))
210 {
211 mark_double_spend(tx);
212 LOG_PRINT_L1("Transaction with id= "<< id << " used already spent key images");
213 tvc.m_verifivation_failed = true;
214 tvc.m_double_spend = true;
215 tvc.m_no_drop_offense = true;
216 return false;
217 }
218 }
219
220 // assume failure during verification steps until success is certain
221 tvc.m_verifivation_failed = true;
222
223 time_t receive_time = time(nullptr);
224
225 crypto::hash max_used_block_id = null_hash;
226 uint64_t max_used_block_height = 0;
227 cryptonote::txpool_tx_meta_t meta{};
228 bool ch_inp_res = check_tx_inputs([&tx]()->cryptonote::transaction&{ return tx; }, id, max_used_block_height, max_used_block_id, tvc, kept_by_block);
229 if(!ch_inp_res)
230 {
231 // if the transaction was valid before (kept_by_block), then it
232 // may become valid again, so ignore the failed inputs check.
233 if(kept_by_block)
234 {
235 meta.weight = tx_weight;
236 meta.fee = fee;
237 meta.max_used_block_id = null_hash;
238 meta.max_used_block_height = 0;
239 meta.last_failed_height = 0;
240 meta.last_failed_id = null_hash;
241 meta.receive_time = receive_time;
242 meta.last_relayed_time = time(NULL);
243 meta.relayed = relayed;
244 meta.set_relay_method(tx_relay);
245 meta.double_spend_seen = have_tx_keyimges_as_spent(tx, id);
246 meta.pruned = tx.pruned;
247 meta.bf_padding = 0;
248 memset(meta.padding, 0, sizeof(meta.padding));
249 try
250 {
251 if (kept_by_block)
252 m_parsed_tx_cache.insert(std::make_pair(id, tx));
253 CRITICAL_REGION_LOCAL1(m_blockchain);
254 LockedTXN lock(m_blockchain.get_db());
255 if (!insert_key_images(tx, id, tx_relay))
256 return false;
257
258 m_blockchain.add_txpool_tx(id, blob, meta);
259 add_tx_to_transient_lists(id, fee / (double)(tx_weight ? tx_weight : 1), receive_time);
260 lock.commit();
261 }
262 catch (const std::exception &e)
263 {
264 MERROR("Error adding transaction to txpool: " << e.what());
265 return false;
266 }
267 tvc.m_verifivation_impossible = true;
268 tvc.m_added_to_pool = true;
269 }else
270 {
271 LOG_PRINT_L1("tx used wrong inputs, rejected");
272 tvc.m_verifivation_failed = true;
273 tvc.m_invalid_input = true;
274 return false;
275 }
276 }else
277 {
278 try
279 {
280 if (kept_by_block)
281 m_parsed_tx_cache.insert(std::make_pair(id, tx));
282 CRITICAL_REGION_LOCAL1(m_blockchain);
283 LockedTXN lock(m_blockchain.get_db());
284
285 const bool existing_tx = m_blockchain.get_txpool_tx_meta(id, meta);
286 if (existing_tx)
287 {
288 /* If Dandelion++ loop. Do not use txes in the `local` state in the
289 loop detection - txes in that state should be outgoing over i2p/tor
290 then routed back via public dandelion++ stem. Pretend to be
291 another stem node in that situation, a loop over the public
292 network hasn't been hit yet. */
293 if (tx_relay == relay_method::stem && meta.dandelionpp_stem)
294 tx_relay = relay_method::fluff;
295 }
296 else
297 meta.set_relay_method(relay_method::none);
298
299 if (meta.upgrade_relay_method(tx_relay) || !existing_tx) // synchronize with embargo timer or stem/fluff out-of-order messages
300 {
301 using clock = std::chrono::system_clock;
302 auto last_relayed_time = std::numeric_limits<decltype(meta.last_relayed_time)>::max();
303 if (tx_relay == relay_method::forward)
304 {
305 last_relayed_time = clock::to_time_t(clock::now() + crypto::random_poisson_seconds{forward_delay_average}());
306 set_if_less(m_next_check, time_t(last_relayed_time));
307 }
308 // else the `set_relayed` function will adjust the time accordingly later
309
310 //update transactions container
311 meta.last_relayed_time = last_relayed_time;
312 meta.receive_time = receive_time;
313 meta.weight = tx_weight;
314 meta.fee = fee;
315 meta.max_used_block_id = max_used_block_id;
316 meta.max_used_block_height = max_used_block_height;
317 meta.last_failed_height = 0;
318 meta.last_failed_id = null_hash;
319 meta.relayed = relayed;
320 meta.double_spend_seen = false;
321 meta.pruned = tx.pruned;
322 meta.bf_padding = 0;
323 memset(meta.padding, 0, sizeof(meta.padding));
324
325 if (!insert_key_images(tx, id, tx_relay))
326 return false;
327
328 m_blockchain.remove_txpool_tx(id);
329 m_blockchain.add_txpool_tx(id, blob, meta);
330 add_tx_to_transient_lists(id, meta.fee / (double)(tx_weight ? tx_weight : 1), receive_time);
331 }
332 lock.commit();
333 tvc.m_added_to_pool = !existing_tx;
334 }
335 catch (const std::exception &e)
336 {
337 MERROR("internal error: error adding transaction to txpool: " << e.what());
338 return false;
339 }
340
341 static_assert(unsigned(relay_method::none) == 0, "expected relay_method::none value to be zero");
342 if(meta.fee > 0 && tx_relay != relay_method::forward)
343 tvc.m_relay = tx_relay;
344 }
345
346 tvc.m_verifivation_failed = false;
347 m_txpool_weight += tx_weight;
348
349 ++m_cookie;
350
351 MINFO("Transaction added to pool: txid " << id << " weight: " << tx_weight << " fee/byte: " << (fee / (double)(tx_weight ? tx_weight : 1)) << ", count: " << m_added_txs_by_id.size());
352
353 prune(m_txpool_max_weight);
354
355 return true;
356 }
357 //---------------------------------------------------------------------------------
358 bool tx_memory_pool::add_tx(transaction &tx, tx_verification_context& tvc, relay_method tx_relay,
359 bool relayed, uint8_t version, uint8_t nic_verified_hf_version)
360 {
361 crypto::hash h = null_hash;
362 cryptonote::blobdata bl;
363 t_serializable_object_to_blob(tx, bl);
364 if (bl.size() == 0 || !get_transaction_hash(tx, h))
365 return false;
366 return add_tx(tx, h, bl, get_transaction_weight(tx, bl.size()), tvc, tx_relay, relayed, version,
367 nic_verified_hf_version);
368 }
369 //---------------------------------------------------------------------------------
370 size_t tx_memory_pool::get_txpool_weight() const
371 {
372 CRITICAL_REGION_LOCAL(m_transactions_lock);
373 return m_txpool_weight;
374 }
375 //---------------------------------------------------------------------------------
376 void tx_memory_pool::set_txpool_max_weight(size_t bytes)
377 {
378 CRITICAL_REGION_LOCAL(m_transactions_lock);
379 m_txpool_max_weight = bytes;
380 }
381 //---------------------------------------------------------------------------------
382 void tx_memory_pool::reduce_txpool_weight(size_t weight)
383 {
384 if (weight > m_txpool_weight)
385 {
386 MERROR("Underflow in txpool weight");
387 m_txpool_weight = 0;
388 }
389 else
390 {
391 m_txpool_weight -= weight;
392 }
393 }
394 //---------------------------------------------------------------------------------
395 void tx_memory_pool::prune(size_t bytes)
396 {
397 CRITICAL_REGION_LOCAL(m_transactions_lock);
398
399 // Nothing to do if already empty
400 if (m_txs_by_fee_and_receive_time.empty())
401 return;
402
403 if (bytes == 0)
404 bytes = m_txpool_max_weight;
405
406 CRITICAL_REGION_LOCAL1(m_blockchain);
407 LockedTXN lock(m_blockchain.get_db());
408 bool changed = false;
409
410 // this will never remove the first one, but we don't care
411 auto it = --m_txs_by_fee_and_receive_time.end();
412 while (it != m_txs_by_fee_and_receive_time.begin())
413 {
414 if (m_txpool_weight <= bytes)
415 break;
416 try
417 {
418 const crypto::hash &txid = it->second;
419 txpool_tx_meta_t meta;
420 if (!m_blockchain.get_txpool_tx_meta(txid, meta))
421 {
422 static bool warned = false;
423 if (!warned)
424 {
425 MERROR("Failed to find tx_meta in txpool (will only print once)");
426 warned = true;
427 }
428 --it;
429 continue;
430 }
431 // don't prune the kept_by_block ones, they're likely added because we're adding a block with those
432 if (meta.kept_by_block)
433 {
434 --it;
435 continue;
436 }
437 cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(txid, relay_category::all);
438 cryptonote::transaction_prefix tx;
439 if (!parse_and_validate_tx_prefix_from_blob(txblob, tx))
440 {
441 MERROR("Failed to parse tx from txpool");
442 return;
443 }
444 // remove first, in case this throws, so key images aren't removed
445 MINFO("Pruning tx " << txid << " from txpool: weight: " << meta.weight << ", fee/byte: " << it->first.first);
446 m_blockchain.remove_txpool_tx(txid);
447 reduce_txpool_weight(meta.weight);
448 remove_transaction_keyimages(tx, txid);
449 MINFO("Pruned tx " << txid << " from txpool: weight: " << meta.weight << ", fee/byte: " << it->first.first);
450
451 auto it_prev = it;
452 --it_prev;
453
454 remove_tx_from_transient_lists(it, txid, !meta.matches(relay_category::broadcasted));
455 it = it_prev;
456
457 changed = true;
458 }
459 catch (const std::exception &e)
460 {
461 MERROR("Error while pruning txpool: " << e.what());
462 return;
463 }
464 }
465 lock.commit();
466 if (changed)
467 ++m_cookie;
468 if (m_txpool_weight > bytes)
469 MINFO("Pool weight after pruning is larger than limit: " << m_txpool_weight << "/" << bytes);
470 }
471 //---------------------------------------------------------------------------------
472 bool tx_memory_pool::insert_key_images(const transaction_prefix &tx, const crypto::hash &id, relay_method tx_relay)
473 {
474 for(const auto& in: tx.vin)
475 {
476 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, txin, false);
477 std::unordered_set<crypto::hash>& kei_image_set = m_spent_key_images[txin.k_image];
478
479 // Only allow multiple txes per key-image if kept-by-block. Only allow
480 // the same txid if going from local/stem->fluff.
481
482 if (tx_relay != relay_method::block)
483 {
484 const bool one_txid =
485 (kei_image_set.empty() || (kei_image_set.size() == 1 && *(kei_image_set.cbegin()) == id));
486 CHECK_AND_ASSERT_MES(one_txid, false, "internal error: tx_relay=" << unsigned(tx_relay)
487 << ", kei_image_set.size()=" << kei_image_set.size() << ENDL << "txin.k_image=" << txin.k_image << ENDL
488 << "tx_id=" << id);
489 }
490
491 const bool new_or_previously_private =
492 kei_image_set.insert(id).second ||
493 !m_blockchain.txpool_tx_matches_category(id, relay_category::legacy);
494 CHECK_AND_ASSERT_MES(new_or_previously_private, false, "internal error: try to insert duplicate iterator in key_image set");
495 }
496 ++m_cookie;
497 return true;
498 }
499 //---------------------------------------------------------------------------------
500 //FIXME: Can return early before removal of all of the key images.
501 // At the least, need to make sure that a false return here
502 // is treated properly. Should probably not return early, however.
503 bool tx_memory_pool::remove_transaction_keyimages(const transaction_prefix& tx, const crypto::hash &actual_hash)
504 {
505 CRITICAL_REGION_LOCAL(m_transactions_lock);
506 CRITICAL_REGION_LOCAL1(m_blockchain);
507 // ND: Speedup
508 for(const txin_v& vi: tx.vin)
509 {
510 CHECKED_GET_SPECIFIC_VARIANT(vi, const txin_to_key, txin, false);
511 auto it = m_spent_key_images.find(txin.k_image);
512 CHECK_AND_ASSERT_MES(it != m_spent_key_images.end(), false, "failed to find transaction input in key images. img=" << txin.k_image << ENDL
513 << "transaction id = " << actual_hash);
514 std::unordered_set<crypto::hash>& key_image_set = it->second;
515 CHECK_AND_ASSERT_MES(key_image_set.size(), false, "empty key_image set, img=" << txin.k_image << ENDL
516 << "transaction id = " << actual_hash);
517
518 auto it_in_set = key_image_set.find(actual_hash);
519 CHECK_AND_ASSERT_MES(it_in_set != key_image_set.end(), false, "transaction id not found in key_image set, img=" << txin.k_image << ENDL
520 << "transaction id = " << actual_hash);
521 key_image_set.erase(it_in_set);
522 if(!key_image_set.size())
523 {
524 //it is now empty hash container for this key_image
525 m_spent_key_images.erase(it);
526 }
527
528 }
529 ++m_cookie;
530 return true;
531 }
532 //---------------------------------------------------------------------------------
533 bool tx_memory_pool::take_tx(const crypto::hash &id, transaction &tx, cryptonote::blobdata &txblob, size_t& tx_weight, uint64_t& fee, bool &relayed, bool &do_not_relay, bool &double_spend_seen, bool &pruned, const bool suppress_missing_msgs)
534 {
535 CRITICAL_REGION_LOCAL(m_transactions_lock);
536 CRITICAL_REGION_LOCAL1(m_blockchain);
537
538 bool sensitive = false;
539 try
540 {
541 LockedTXN lock(m_blockchain.get_db());
542 txpool_tx_meta_t meta;
543 if (!m_blockchain.get_txpool_tx_meta(id, meta))
544 {
545 if (!suppress_missing_msgs)
546 {
547 MERROR("Failed to find tx_meta in txpool");
548 }
549 return false;
550 }
551 txblob = m_blockchain.get_txpool_tx_blob(id, relay_category::all);
552 auto ci = m_parsed_tx_cache.find(id);
553 if (ci != m_parsed_tx_cache.end())
554 {
555 tx = ci->second;
556 }
557 else if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(txblob, tx) : parse_and_validate_tx_from_blob(txblob, tx)))
558 {
559 MERROR("Failed to parse tx from txpool");
560 return false;
561 }
562 else
563 {
564 tx.set_hash(id);
565 }
566 tx_weight = meta.weight;
567 fee = meta.fee;
568 relayed = meta.relayed;
569 do_not_relay = meta.do_not_relay;
570 double_spend_seen = meta.double_spend_seen;
571 pruned = meta.pruned;
572 sensitive = !meta.matches(relay_category::broadcasted);
573
574 // remove first, in case this throws, so key images aren't removed
575 m_blockchain.remove_txpool_tx(id);
576 reduce_txpool_weight(tx_weight);
577 remove_transaction_keyimages(tx, id);
578 lock.commit();
579 }
580 catch (const std::exception &e)
581 {
582 MERROR("Failed to remove tx from txpool: " << e.what());
583 return false;
584 }
585
586 remove_tx_from_transient_lists(find_tx_in_sorted_container(id), id, sensitive);
587 ++m_cookie;
588 return true;
589 }
590 //---------------------------------------------------------------------------------
591 bool tx_memory_pool::get_transaction_info(const crypto::hash &txid, tx_details &td, bool include_sensitive_data, bool include_blob) const
592 {
593 PERF_TIMER(get_transaction_info);
594 CRITICAL_REGION_LOCAL(m_transactions_lock);
595 CRITICAL_REGION_LOCAL1(m_blockchain);
596
597 try
598 {
599 LockedTXN lock(m_blockchain.get_db());
600 txpool_tx_meta_t meta;
601 if (!m_blockchain.get_txpool_tx_meta(txid, meta))
602 {
603 LOG_PRINT_L2("Failed to find tx in txpool: " << txid);
604 return false;
605 }
606 if (!include_sensitive_data && !meta.matches(relay_category::broadcasted))
607 {
608 // We don't want sensitive data && the tx is sensitive, so no need to return it
609 return false;
610 }
611 cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(txid, relay_category::all);
612 auto ci = m_parsed_tx_cache.find(txid);
613 if (ci != m_parsed_tx_cache.end())
614 {
615 td.tx = ci->second;
616 }
617 else if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(txblob, td.tx) : parse_and_validate_tx_from_blob(txblob, td.tx)))
618 {
619 MERROR("Failed to parse tx from txpool");
620 return false;
621 }
622 else
623 {
624 td.tx.set_hash(txid);
625 }
626 td.blob_size = txblob.size();
627 td.weight = meta.weight;
628 td.fee = meta.fee;
629 td.max_used_block_id = meta.max_used_block_id;
630 td.max_used_block_height = meta.max_used_block_height;
631 td.kept_by_block = meta.kept_by_block;
632 td.last_failed_height = meta.last_failed_height;
633 td.last_failed_id = meta.last_failed_id;
634 td.receive_time = include_sensitive_data ? meta.receive_time : 0;
635 td.last_relayed_time = (include_sensitive_data && !meta.dandelionpp_stem) ? meta.last_relayed_time : 0;
636 td.relayed = meta.relayed;
637 td.do_not_relay = meta.do_not_relay;
638 td.double_spend_seen = meta.double_spend_seen;
639 if (include_blob)
640 td.tx_blob = std::move(txblob);
641 }
642 catch (const std::exception &e)
643 {
644 MERROR("Failed to get tx from txpool: " << e.what());
645 return false;
646 }
647
648 return true;
649 }
650 //------------------------------------------------------------------
651 bool tx_memory_pool::get_transactions_info(const std::vector<crypto::hash>& txids, std::vector<std::pair<crypto::hash, tx_details>>& txs, bool include_sensitive) const
652 {
653 CRITICAL_REGION_LOCAL(m_transactions_lock);
654 CRITICAL_REGION_LOCAL1(m_blockchain);
655
656 txs.clear();
657
658 for (const auto &it: txids)
659 {
660 tx_details details;
661 bool success = get_transaction_info(it, details, include_sensitive, true/*include_blob*/);
662 if (success)
663 {
664 txs.push_back(std::make_pair(it, std::move(details)));
665 }
666 }
667 return true;
668 }
669 //---------------------------------------------------------------------------------
670 bool tx_memory_pool::get_complement(const std::vector<crypto::hash> &hashes, std::vector<cryptonote::blobdata> &txes) const
671 {
672 CRITICAL_REGION_LOCAL(m_transactions_lock);
673 CRITICAL_REGION_LOCAL1(m_blockchain);
674
675 m_blockchain.for_all_txpool_txes([this, &hashes, &txes](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref*) {
676 const auto tx_relay_method = meta.get_relay_method();
677 if (tx_relay_method != relay_method::block && tx_relay_method != relay_method::fluff)
678 return true;
679 const auto i = std::find(hashes.begin(), hashes.end(), txid);
680 if (i == hashes.end())
681 {
682 cryptonote::blobdata bd;
683 try
684 {
685 if (!m_blockchain.get_txpool_tx_blob(txid, bd, cryptonote::relay_category::broadcasted))
686 {
687 MERROR("Failed to get blob for txpool transaction " << txid);
688 return true;
689 }
690 txes.emplace_back(std::move(bd));
691 }
692 catch (const std::exception &e)
693 {
694 MERROR("Failed to get blob for txpool transaction " << txid << ": " << e.what());
695 return true;
696 }
697 }
698 return true;
699 }, false);
700 return true;
701 }
702 //---------------------------------------------------------------------------------
703 void tx_memory_pool::on_idle()
704 {
705 m_remove_stuck_tx_interval.do_call([this](){return remove_stuck_transactions();});
706 }
707 //---------------------------------------------------------------------------------
708 sorted_tx_container::iterator tx_memory_pool::find_tx_in_sorted_container(const crypto::hash& id) const
709 {
710 return std::find_if( m_txs_by_fee_and_receive_time.begin(), m_txs_by_fee_and_receive_time.end()
711 , [&](const sorted_tx_container::value_type& a){
712 return a.second == id;
713 }
714 );
715 }
716 //---------------------------------------------------------------------------------
717 //TODO: investigate whether boolean return is appropriate
718 bool tx_memory_pool::remove_stuck_transactions()
719 {
720 CRITICAL_REGION_LOCAL(m_transactions_lock);
721 CRITICAL_REGION_LOCAL1(m_blockchain);
722 std::list<std::pair<crypto::hash, uint64_t>> remove;
723 m_blockchain.for_all_txpool_txes([this, &remove](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref*) {
724 uint64_t tx_age = time(nullptr) - meta.receive_time;
725
726 if((tx_age > CRYPTONOTE_MEMPOOL_TX_LIVETIME && !meta.kept_by_block) ||
727 (tx_age > CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME && meta.kept_by_block) )
728 {
729 LOG_PRINT_L1("Tx " << txid << " removed from tx pool due to outdated, age: " << tx_age );
730 remove_tx_from_transient_lists(find_tx_in_sorted_container(txid), txid, !meta.matches(relay_category::broadcasted));
731 m_timed_out_transactions.insert(txid);
732 remove.push_back(std::make_pair(txid, meta.weight));
733 }
734 return true;
735 }, false, relay_category::all);
736
737 if (!remove.empty())
738 {
739 LockedTXN lock(m_blockchain.get_db());
740 for (const std::pair<crypto::hash, uint64_t> &entry: remove)
741 {
742 const crypto::hash &txid = entry.first;
743 try
744 {
745 cryptonote::blobdata bd = m_blockchain.get_txpool_tx_blob(txid, relay_category::all);
746 cryptonote::transaction_prefix tx;
747 if (!parse_and_validate_tx_prefix_from_blob(bd, tx))
748 {
749 MERROR("Failed to parse tx from txpool");
750 // continue
751 }
752 else
753 {
754 // remove first, so we only remove key images if the tx removal succeeds
755 m_blockchain.remove_txpool_tx(txid);
756 reduce_txpool_weight(entry.second);
757 remove_transaction_keyimages(tx, txid);
758 }
759 }
760 catch (const std::exception &e)
761 {
762 MWARNING("Failed to remove stuck transaction: " << txid);
763 // ignore error
764 }
765 }
766 lock.commit();
767 ++m_cookie;
768 }
769 return true;
770 }
771 //---------------------------------------------------------------------------------
772 //TODO: investigate whether boolean return is appropriate
773 bool tx_memory_pool::get_relayable_transactions(std::vector<std::tuple<crypto::hash, cryptonote::blobdata, relay_method>> &txs)
774 {
775 using clock = std::chrono::system_clock;
776
777 const uint64_t now = time(NULL);
778 if (uint64_t{std::numeric_limits<time_t>::max()} < now || time_t(now) < m_next_check)
779 return false;
780
781 uint64_t next_check = clock::to_time_t(clock::from_time_t(time_t(now)) + max_relayable_check);
782 std::vector<std::pair<crypto::hash, txpool_tx_meta_t>> change_timestamps;
783
784 CRITICAL_REGION_LOCAL(m_transactions_lock);
785 CRITICAL_REGION_LOCAL1(m_blockchain);
786 LockedTXN lock(m_blockchain.get_db());
787 txs.reserve(m_blockchain.get_txpool_tx_count());
788 m_blockchain.for_all_txpool_txes([this, now, &txs, &change_timestamps, &next_check](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *){
789 // 0 fee transactions are never relayed
790 if(!meta.pruned && meta.fee > 0 && !meta.do_not_relay)
791 {
792 const relay_method tx_relay = meta.get_relay_method();
793 switch (tx_relay)
794 {
795 case relay_method::stem:
796 case relay_method::forward:
797 if (meta.last_relayed_time > now)
798 {
799 next_check = std::min(next_check, meta.last_relayed_time);
800 return true; // continue to next tx
801 }
802 change_timestamps.emplace_back(txid, meta);
803 break;
804 default:
805 case relay_method::none:
806 return true;
807 case relay_method::local:
808 case relay_method::fluff:
809 case relay_method::block:
810 if (now - meta.last_relayed_time <= get_relay_delay(meta.last_relayed_time, meta.receive_time))
811 return true; // continue to next tx
812 break;
813 }
814
815 // if the tx is older than half the max lifetime, we don't re-relay it, to avoid a problem
816 // mentioned by smooth where nodes would flush txes at slightly different times, causing
817 // flushed txes to be re-added when received from a node which was just about to flush it
818 uint64_t max_age = (tx_relay == relay_method::block) ? CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME : CRYPTONOTE_MEMPOOL_TX_LIVETIME;
819 if (now - meta.receive_time <= max_age / 2)
820 {
821 try
822 {
823 txs.emplace_back(txid, m_blockchain.get_txpool_tx_blob(txid, relay_category::all), tx_relay);
824 }
825 catch (const std::exception &e)
826 {
827 MERROR("Failed to get transaction blob from db");
828 // ignore error
829 }
830 }
831 }
832 return true;
833 }, false, relay_category::relayable);
834
835 for (auto& elem : change_timestamps)
836 {
837 /* These transactions are still in forward or stem state, so the field
838 represents the next time a relay should be attempted. Will be
839 overwritten when the state is upgraded to stem, fluff or block. This
840 function is only called every ~2 minutes, so this resetting should be
841 unnecessary, but is primarily a precaution against potential changes
842 to the callback routines. */
843 elem.second.last_relayed_time = now + get_relay_delay(elem.second.last_relayed_time, elem.second.receive_time);
844 m_blockchain.update_txpool_tx(elem.first, elem.second);
845 }
846
847 m_next_check = time_t(next_check);
848 return true;
849 }
850 //---------------------------------------------------------------------------------
851 void tx_memory_pool::set_relayed(const epee::span<const crypto::hash> hashes, const relay_method method, std::vector<bool> &just_broadcasted)
852 {
853 just_broadcasted.clear();
854
855 crypto::random_poisson_seconds embargo_duration{dandelionpp_embargo_average};
856 const auto now = std::chrono::system_clock::now();
857 uint64_t next_relay = uint64_t{std::numeric_limits<time_t>::max()};
858
859 CRITICAL_REGION_LOCAL(m_transactions_lock);
860 CRITICAL_REGION_LOCAL1(m_blockchain);
861 LockedTXN lock(m_blockchain.get_db());
862 for (const auto& hash : hashes)
863 {
864 bool was_just_broadcasted = false;
865 try
866 {
867 txpool_tx_meta_t meta;
868 if (m_blockchain.get_txpool_tx_meta(hash, meta))
869 {
870 // txes can be received as "stem" or "fluff" in either order
871 const bool already_broadcasted = meta.matches(relay_category::broadcasted);
872 meta.upgrade_relay_method(method);
873 meta.relayed = true;
874
875 if (meta.dandelionpp_stem)
876 {
877 meta.last_relayed_time = std::chrono::system_clock::to_time_t(now + embargo_duration());
878 next_relay = std::min(next_relay, meta.last_relayed_time);
879 }
880 else
881 meta.last_relayed_time = std::chrono::system_clock::to_time_t(now);
882
883 m_blockchain.update_txpool_tx(hash, meta);
884 // wait until db update succeeds to ensure tx is visible in the pool
885 was_just_broadcasted = !already_broadcasted && meta.matches(relay_category::broadcasted);
886
887 if (was_just_broadcasted)
888 // Make sure the tx gets re-added with an updated time
889 add_tx_to_transient_lists(hash, meta.fee / (double)meta.weight, std::chrono::system_clock::to_time_t(now));
890 }
891 }
892 catch (const std::exception &e)
893 {
894 MERROR("Failed to update txpool transaction metadata: " << e.what());
895 // continue
896 }
897 just_broadcasted.emplace_back(was_just_broadcasted);
898 }
899 lock.commit();
900 set_if_less(m_next_check, time_t(next_relay));
901 }
902 //---------------------------------------------------------------------------------
903 size_t tx_memory_pool::get_transactions_count(bool include_sensitive) const
904 {
905 CRITICAL_REGION_LOCAL(m_transactions_lock);
906 CRITICAL_REGION_LOCAL1(m_blockchain);
907 return m_blockchain.get_txpool_tx_count(include_sensitive);
908 }
909 //---------------------------------------------------------------------------------
910 void tx_memory_pool::get_transactions(std::vector<transaction>& txs, bool include_sensitive) const
911 {
912 CRITICAL_REGION_LOCAL(m_transactions_lock);
913 CRITICAL_REGION_LOCAL1(m_blockchain);
914 const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted;
915 txs.reserve(m_blockchain.get_txpool_tx_count(include_sensitive));
916 m_blockchain.for_all_txpool_txes([&txs](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd){
917 transaction tx;
918 if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*bd, tx) : parse_and_validate_tx_from_blob(*bd, tx)))
919 {
920 MERROR("Failed to parse tx from txpool");
921 // continue
922 return true;
923 }
924 tx.set_hash(txid);
925 txs.push_back(std::move(tx));
926 return true;
927 }, true, category);
928 }
929 //------------------------------------------------------------------
930 void tx_memory_pool::get_transaction_hashes(std::vector<crypto::hash>& txs, bool include_sensitive) const
931 {
932 CRITICAL_REGION_LOCAL(m_transactions_lock);
933 CRITICAL_REGION_LOCAL1(m_blockchain);
934 const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted;
935 txs.reserve(m_blockchain.get_txpool_tx_count(include_sensitive));
936 m_blockchain.for_all_txpool_txes([&txs](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd){
937 txs.push_back(txid);
938 return true;
939 }, false, category);
940 }
941 //------------------------------------------------------------------
942 bool tx_memory_pool::get_pool_info(time_t start_time, bool include_sensitive, size_t max_tx_count, std::vector<std::pair<crypto::hash, tx_details>>& added_txs, std::vector<crypto::hash>& remaining_added_txids, std::vector<crypto::hash>& removed_txs, bool& incremental) const
943 {
944 CRITICAL_REGION_LOCAL(m_transactions_lock);
945 CRITICAL_REGION_LOCAL1(m_blockchain);
946
947 incremental = true;
948 if (start_time == (time_t)0)
949 {
950 // Giving no start time means give back whole pool
951 incremental = false;
952 }
953 else if ((m_added_txs_start_time != (time_t)0) && (m_removed_txs_start_time != (time_t)0))
954 {
955 if ((start_time <= m_added_txs_start_time) || (start_time <= m_removed_txs_start_time))
956 {
957 // If either of the two lists do not go back far enough it's not possible to
958 // deliver incremental pool info
959 incremental = false;
960 }
961 // The check uses "<=": We cannot be sure to have ALL txs exactly at start_time, only AFTER that time
962 }
963 else
964 {
965 // Some incremental info still missing completely
966 incremental = false;
967 }
968
969 added_txs.clear();
970 remaining_added_txids.clear();
971 removed_txs.clear();
972
973 std::vector<crypto::hash> txids;
974 if (!incremental)
975 {
976 LOG_PRINT_L2("Giving back the whole pool");
977 // Give back the whole pool in 'added_txs'; because calling 'get_transaction_info' right inside the
978 // anonymous method somehow results in an LMDB error with transactions we have to build a list of
979 // ids first and get the full info afterwards
980 get_transaction_hashes(txids, include_sensitive);
981 if (txids.size() > max_tx_count)
982 {
983 remaining_added_txids = std::vector<crypto::hash>(txids.begin() + max_tx_count, txids.end());
984 txids.erase(txids.begin() + max_tx_count, txids.end());
985 }
986 get_transactions_info(txids, added_txs, include_sensitive);
987 return true;
988 }
989
990 // Give back incrementally, based on time of entry into the map
991 for (const auto &pit : m_added_txs_by_id)
992 {
993 if (pit.second >= start_time)
994 txids.push_back(pit.first);
995 }
996 get_transactions_info(txids, added_txs, include_sensitive);
997 if (added_txs.size() > max_tx_count)
998 {
999 remaining_added_txids.reserve(added_txs.size() - max_tx_count);
1000 for (size_t i = max_tx_count; i < added_txs.size(); ++i)
1001 remaining_added_txids.push_back(added_txs[i].first);
1002 added_txs.erase(added_txs.begin() + max_tx_count, added_txs.end());
1003 }
1004
1005 std::multimap<time_t, removed_tx_info>::const_iterator rit = m_removed_txs_by_time.lower_bound(start_time);
1006 while (rit != m_removed_txs_by_time.end())
1007 {
1008 if (include_sensitive || !rit->second.sensitive)
1009 {
1010 removed_txs.push_back(rit->second.txid);
1011 }
1012 ++rit;
1013 }
1014 return true;
1015 }
1016 //------------------------------------------------------------------
1017 void tx_memory_pool::get_transaction_backlog(std::vector<tx_backlog_entry>& backlog, bool include_sensitive) const
1018 {
1019 CRITICAL_REGION_LOCAL(m_transactions_lock);
1020 CRITICAL_REGION_LOCAL1(m_blockchain);
1021 const uint64_t now = time(NULL);
1022 const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted;
1023 backlog.reserve(m_blockchain.get_txpool_tx_count(include_sensitive));
1024 m_blockchain.for_all_txpool_txes([&backlog, now](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd){
1025 backlog.push_back({meta.weight, meta.fee, meta.receive_time - now});
1026 return true;
1027 }, false, category);
1028 }
1029 //------------------------------------------------------------------
1030 void tx_memory_pool::get_block_template_backlog(std::vector<tx_block_template_backlog_entry>& backlog, bool include_sensitive) const
1031 {
1032 CRITICAL_REGION_LOCAL(m_transactions_lock);
1033 CRITICAL_REGION_LOCAL1(m_blockchain);
1034
1035 std::vector<tx_block_template_backlog_entry> tmp;
1036 uint64_t total_weight = 0;
1037
1038 // First get everything from the mempool, filter it later
1039 m_blockchain.for_all_txpool_txes([&tmp, &total_weight](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref*){
1040 tmp.emplace_back(tx_block_template_backlog_entry{txid, meta.weight, meta.fee});
1041 total_weight += meta.weight;
1042 return true;
1043 }, false, include_sensitive ? relay_category::all : relay_category::broadcasted);
1044
1045 // Limit backlog to 112.5% of current median weight. This is enough to mine a full block with the optimal block reward
1046 const uint64_t median_weight = m_blockchain.get_current_cumulative_block_weight_median();
1047 const uint64_t max_backlog_weight = median_weight + (median_weight / 8);
1048
1049 // If the total weight is too high, choose the best paying transactions
1050 if (total_weight > max_backlog_weight)
1051 std::stable_sort(tmp.begin(), tmp.end(), [](const auto& a, const auto& b){ return a.fee * b.weight > b.fee * a.weight; });
1052
1053 backlog.clear();
1054 uint64_t w = 0;
1055
1056 std::unordered_set<crypto::key_image> k_images;
1057
1058 for (const tx_block_template_backlog_entry& e : tmp)
1059 {
1060 try
1061 {
1062 txpool_tx_meta_t meta;
1063 if (!m_blockchain.get_txpool_tx_meta(e.id, meta))
1064 continue;
1065
1066 cryptonote::blobdata txblob;
1067 if (!m_blockchain.get_txpool_tx_blob(e.id, txblob, relay_category::all))
1068 continue;
1069
1070 cryptonote::transaction tx;
1071 if (is_transaction_ready_to_go(meta, e.id, txblob, tx))
1072 {
1073 if (have_key_images(k_images, tx))
1074 continue;
1075 append_key_images(k_images, tx);
1076
1077 backlog.push_back(e);
1078 w += e.weight;
1079 if (w > max_backlog_weight)
1080 break;
1081 }
1082 }
1083 catch (const std::exception &e)
1084 {
1085 MERROR("Failed to check transaction readiness: " << e.what());
1086 // continue, not fatal
1087 }
1088 }
1089 }
1090 //------------------------------------------------------------------
1091 void tx_memory_pool::get_transaction_stats(struct txpool_stats& stats, bool include_sensitive) const
1092 {
1093 CRITICAL_REGION_LOCAL(m_transactions_lock);
1094 CRITICAL_REGION_LOCAL1(m_blockchain);
1095 const uint64_t now = time(NULL);
1096 const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted;
1097 std::map<uint64_t, txpool_histo> agebytes;
1098 stats.txs_total = m_blockchain.get_txpool_tx_count(include_sensitive);
1099 std::vector<uint32_t> weights;
1100 weights.reserve(stats.txs_total);
1101 m_blockchain.for_all_txpool_txes([&stats, &weights, now, &agebytes](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd){
1102 weights.push_back(meta.weight);
1103 stats.bytes_total += meta.weight;
1104 if (!stats.bytes_min || meta.weight < stats.bytes_min)
1105 stats.bytes_min = meta.weight;
1106 if (meta.weight > stats.bytes_max)
1107 stats.bytes_max = meta.weight;
1108 if (!meta.relayed)
1109 stats.num_not_relayed++;
1110 stats.fee_total += meta.fee;
1111 if (!stats.oldest || meta.receive_time < stats.oldest)
1112 stats.oldest = meta.receive_time;
1113 if (meta.receive_time < now - 600)
1114 stats.num_10m++;
1115 if (meta.last_failed_height)
1116 stats.num_failing++;
1117 uint64_t age = now - meta.receive_time + (now == meta.receive_time);
1118 agebytes[age].txs++;
1119 agebytes[age].bytes += meta.weight;
1120 if (meta.double_spend_seen)
1121 ++stats.num_double_spends;
1122 return true;
1123 }, false, category);
1124
1125 stats.bytes_med = epee::misc_utils::median(weights);
1126 if (stats.txs_total > 1)
1127 {
1128 /* looking for 98th percentile */
1129 size_t end = stats.txs_total * 0.02;
1130 uint64_t delta, factor;
1131 std::map<uint64_t, txpool_histo>::iterator it, i2;
1132 if (end)
1133 {
1134 /* If enough txs, spread the first 98% of results across
1135 * the first 9 bins, drop final 2% in last bin.
1136 */
1137 it = agebytes.end();
1138 size_t cumulative_num = 0;
1139 /* Since agebytes is not empty and end is nonzero, the
1140 * below loop can always run at least once.
1141 */
1142 do {
1143 --it;
1144 cumulative_num += it->second.txs;
1145 } while (it != agebytes.begin() && cumulative_num < end);
1146 stats.histo_98pc = it->first;
1147 factor = 9;
1148 delta = it->first;
1149 stats.histo.resize(10);
1150 } else
1151 {
1152 /* If not enough txs, don't reserve the last slot;
1153 * spread evenly across all 10 bins.
1154 */
1155 stats.histo_98pc = 0;
1156 it = agebytes.end();
1157 factor = stats.txs_total > 9 ? 10 : stats.txs_total;
1158 delta = now - stats.oldest;
1159 stats.histo.resize(factor);
1160 }
1161 if (!delta)
1162 delta = 1;
1163 for (i2 = agebytes.begin(); i2 != it; i2++)
1164 {
1165 size_t i = (i2->first * factor - 1) / delta;
1166 stats.histo[i].txs += i2->second.txs;
1167 stats.histo[i].bytes += i2->second.bytes;
1168 }
1169 for (; i2 != agebytes.end(); i2++)
1170 {
1171 stats.histo[factor].txs += i2->second.txs;
1172 stats.histo[factor].bytes += i2->second.bytes;
1173 }
1174 }
1175 }
1176 //------------------------------------------------------------------
1177 //TODO: investigate whether boolean return is appropriate
1178 bool tx_memory_pool::get_transactions_and_spent_keys_info(std::vector<tx_info>& tx_infos, std::vector<spent_key_image_info>& key_image_infos, bool include_sensitive_data) const
1179 {
1180 CRITICAL_REGION_LOCAL(m_transactions_lock);
1181 CRITICAL_REGION_LOCAL1(m_blockchain);
1182 const relay_category category = include_sensitive_data ? relay_category::all : relay_category::broadcasted;
1183 const size_t count = m_blockchain.get_txpool_tx_count(include_sensitive_data);
1184 tx_infos.reserve(count);
1185 key_image_infos.reserve(count);
1186 m_blockchain.for_all_txpool_txes([&tx_infos, key_image_infos, include_sensitive_data](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd){
1187 tx_info txi;
1188 txi.id_hash = epee::string_tools::pod_to_hex(txid);
1189 txi.tx_blob = blobdata(bd->data(), bd->size());
1190 transaction tx;
1191 if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*bd, tx) : parse_and_validate_tx_from_blob(*bd, tx)))
1192 {
1193 MERROR("Failed to parse tx from txpool");
1194 // continue
1195 return true;
1196 }
1197 tx.set_hash(txid);
1198 txi.tx_json = obj_to_json_str(tx);
1199 txi.blob_size = bd->size();
1200 txi.weight = meta.weight;
1201 txi.fee = meta.fee;
1202 txi.kept_by_block = meta.kept_by_block;
1203 txi.max_used_block_height = meta.max_used_block_height;
1204 txi.max_used_block_id_hash = epee::string_tools::pod_to_hex(meta.max_used_block_id);
1205 txi.last_failed_height = meta.last_failed_height;
1206 txi.last_failed_id_hash = epee::string_tools::pod_to_hex(meta.last_failed_id);
1207 // In restricted mode we do not include this data:
1208 txi.receive_time = include_sensitive_data ? meta.receive_time : 0;
1209 txi.relayed = meta.relayed;
1210 // In restricted mode we do not include this data:
1211 txi.last_relayed_time = (include_sensitive_data && !meta.dandelionpp_stem) ? meta.last_relayed_time : 0;
1212 txi.do_not_relay = meta.do_not_relay;
1213 txi.double_spend_seen = meta.double_spend_seen;
1214 tx_infos.push_back(std::move(txi));
1215 return true;
1216 }, true, category);
1217
1218 for (const key_images_container::value_type& kee : m_spent_key_images) {
1219 const crypto::key_image& k_image = kee.first;
1220 const std::unordered_set<crypto::hash>& kei_image_set = kee.second;
1221 spent_key_image_info ki;
1222 ki.id_hash = epee::string_tools::pod_to_hex(k_image);
1223 for (const crypto::hash& tx_id_hash : kei_image_set)
1224 {
1225 if (m_blockchain.txpool_tx_matches_category(tx_id_hash, category))
1226 ki.txs_hashes.push_back(epee::string_tools::pod_to_hex(tx_id_hash));
1227 }
1228
1229 // Only return key images for which we have at least one tx that we can show for them
1230 if (!ki.txs_hashes.empty())
1231 key_image_infos.push_back(std::move(ki));
1232 }
1233 return true;
1234 }
1235 //---------------------------------------------------------------------------------
1236 bool tx_memory_pool::get_pool_for_rpc(std::vector<cryptonote::rpc::tx_in_pool>& tx_infos, cryptonote::rpc::key_images_with_tx_hashes& key_image_infos) const
1237 {
1238 CRITICAL_REGION_LOCAL(m_transactions_lock);
1239 CRITICAL_REGION_LOCAL1(m_blockchain);
1240 tx_infos.reserve(m_blockchain.get_txpool_tx_count());
1241 key_image_infos.reserve(m_blockchain.get_txpool_tx_count());
1242 m_blockchain.for_all_txpool_txes([&tx_infos, key_image_infos](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd){
1243 cryptonote::rpc::tx_in_pool txi;
1244 txi.tx_hash = txid;
1245 if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*bd, txi.tx) : parse_and_validate_tx_from_blob(*bd, txi.tx)))
1246 {
1247 MERROR("Failed to parse tx from txpool");
1248 // continue
1249 return true;
1250 }
1251 txi.tx.set_hash(txid);
1252 txi.blob_size = bd->size();
1253 txi.weight = meta.weight;
1254 txi.fee = meta.fee;
1255 txi.kept_by_block = meta.kept_by_block;
1256 txi.max_used_block_height = meta.max_used_block_height;
1257 txi.max_used_block_hash = meta.max_used_block_id;
1258 txi.last_failed_block_height = meta.last_failed_height;
1259 txi.last_failed_block_hash = meta.last_failed_id;
1260 txi.receive_time = meta.receive_time;
1261 txi.relayed = meta.relayed;
1262 txi.last_relayed_time = meta.dandelionpp_stem ? 0 : meta.last_relayed_time;
1263 txi.do_not_relay = meta.do_not_relay;
1264 txi.double_spend_seen = meta.double_spend_seen;
1265 tx_infos.push_back(txi);
1266 return true;
1267 }, true, relay_category::broadcasted);
1268
1269 for (const key_images_container::value_type& kee : m_spent_key_images) {
1270 std::vector<crypto::hash> tx_hashes;
1271 const std::unordered_set<crypto::hash>& kei_image_set = kee.second;
1272 for (const crypto::hash& tx_id_hash : kei_image_set)
1273 {
1274 if (m_blockchain.txpool_tx_matches_category(tx_id_hash, relay_category::broadcasted))
1275 tx_hashes.push_back(tx_id_hash);
1276 }
1277
1278 if (!tx_hashes.empty())
1279 key_image_infos[kee.first] = std::move(tx_hashes);
1280 }
1281 return true;
1282 }
1283 //---------------------------------------------------------------------------------
1284 bool tx_memory_pool::check_for_key_images(const std::vector<crypto::key_image>& key_images, std::vector<bool>& spent) const
1285 {
1286 CRITICAL_REGION_LOCAL(m_transactions_lock);
1287 CRITICAL_REGION_LOCAL1(m_blockchain);
1288
1289 spent.clear();
1290
1291 for (const auto& image : key_images)
1292 {
1293 bool is_spent = false;
1294 const auto found = m_spent_key_images.find(image);
1295 if (found != m_spent_key_images.end())
1296 {
1297 for (const crypto::hash& tx_hash : found->second)
1298 is_spent |= m_blockchain.txpool_tx_matches_category(tx_hash, relay_category::broadcasted);
1299 }
1300 spent.push_back(is_spent);
1301 }
1302
1303 return true;
1304 }
1305 //---------------------------------------------------------------------------------
1306 bool tx_memory_pool::get_transaction(const crypto::hash& id, cryptonote::blobdata& txblob, relay_category tx_category) const
1307 {
1308 CRITICAL_REGION_LOCAL(m_transactions_lock);
1309 CRITICAL_REGION_LOCAL1(m_blockchain);
1310 try
1311 {
1312 return m_blockchain.get_txpool_tx_blob(id, txblob, tx_category);
1313 }
1314 catch (const std::exception &e)
1315 {
1316 return false;
1317 }
1318 }
1319 //---------------------------------------------------------------------------------
1320 bool tx_memory_pool::on_blockchain_inc(uint64_t new_block_height, const crypto::hash& top_block_id)
1321 {
1322 CRITICAL_REGION_LOCAL(m_transactions_lock);
1323 m_input_cache.clear();
1324 m_parsed_tx_cache.clear();
1325 return true;
1326 }
1327 //---------------------------------------------------------------------------------
1328 bool tx_memory_pool::on_blockchain_dec(uint64_t new_block_height, const crypto::hash& top_block_id)
1329 {
1330 CRITICAL_REGION_LOCAL(m_transactions_lock);
1331 m_input_cache.clear();
1332 m_parsed_tx_cache.clear();
1333 return true;
1334 }
1335 //---------------------------------------------------------------------------------
1336 bool tx_memory_pool::have_tx(const crypto::hash &id, relay_category tx_category) const
1337 {
1338 CRITICAL_REGION_LOCAL(m_transactions_lock);
1339 CRITICAL_REGION_LOCAL1(m_blockchain);
1340 return m_blockchain.get_db().txpool_has_tx(id, tx_category);
1341 }
1342 //---------------------------------------------------------------------------------
1343 bool tx_memory_pool::have_tx_keyimges_as_spent(const transaction& tx, const crypto::hash& txid) const
1344 {
1345 CRITICAL_REGION_LOCAL(m_transactions_lock);
1346 CRITICAL_REGION_LOCAL1(m_blockchain);
1347 for(const auto& in: tx.vin)
1348 {
1349 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, true);//should never fail
1350 if(have_tx_keyimg_as_spent(tokey_in.k_image, txid))
1351 return true;
1352 }
1353 return false;
1354 }
1355 //---------------------------------------------------------------------------------
1356 bool tx_memory_pool::have_tx_keyimg_as_spent(const crypto::key_image& key_im, const crypto::hash& txid) const
1357 {
1358 CRITICAL_REGION_LOCAL(m_transactions_lock);
1359 const auto found = m_spent_key_images.find(key_im);
1360 if (found != m_spent_key_images.end() && !found->second.empty())
1361 {
1362 // If another tx is using the key image, always return as spent.
1363 // See `insert_key_images`.
1364 if (1 < found->second.size() || *(found->second.cbegin()) != txid)
1365 return true;
1366 return m_blockchain.txpool_tx_matches_category(txid, relay_category::legacy);
1367 }
1368 return false;
1369 }
1370 //---------------------------------------------------------------------------------
1371 void tx_memory_pool::lock() const
1372 {
1373 m_transactions_lock.lock();
1374 }
1375 //---------------------------------------------------------------------------------
1376 void tx_memory_pool::unlock() const
1377 {
1378 m_transactions_lock.unlock();
1379 }
1380 //---------------------------------------------------------------------------------
1381 bool tx_memory_pool::check_tx_inputs(const std::function<cryptonote::transaction&(void)> &get_tx, const crypto::hash &txid, uint64_t &max_used_block_height, crypto::hash &max_used_block_id, tx_verification_context &tvc, bool kept_by_block) const
1382 {
1383 if (!kept_by_block)
1384 {
1385 const std::unordered_map<crypto::hash, std::tuple<bool, tx_verification_context, uint64_t, crypto::hash>>::const_iterator i = m_input_cache.find(txid);
1386 if (i != m_input_cache.end())
1387 {
1388 max_used_block_height = std::get<2>(i->second);
1389 max_used_block_id = std::get<3>(i->second);
1390 tvc = std::get<1>(i->second);
1391 return std::get<0>(i->second);
1392 }
1393 }
1394 bool ret = m_blockchain.check_tx_inputs(get_tx(), max_used_block_height, max_used_block_id, tvc, kept_by_block);
1395 if (!kept_by_block)
1396 m_input_cache.insert(std::make_pair(txid, std::make_tuple(ret, tvc, max_used_block_height, max_used_block_id)));
1397 return ret;
1398 }
1399 //---------------------------------------------------------------------------------
1400 bool tx_memory_pool::is_transaction_ready_to_go(txpool_tx_meta_t& txd, const crypto::hash &txid, const cryptonote::blobdata_ref& txblob, transaction &tx) const
1401 {
1402 struct transaction_parser
1403 {
1404 transaction_parser(const cryptonote::blobdata_ref &txblob, const crypto::hash &txid, transaction &tx): txblob(txblob), txid(txid), tx(tx), parsed(false) {}
1405 cryptonote::transaction &operator()()
1406 {
1407 if (!parsed)
1408 {
1409 if (!parse_and_validate_tx_from_blob(txblob, tx))
1410 throw std::runtime_error("failed to parse transaction blob");
1411 tx.set_hash(txid);
1412 parsed = true;
1413 }
1414 return tx;
1415 }
1416 const cryptonote::blobdata_ref &txblob;
1417 const crypto::hash &txid;
1418 transaction &tx;
1419 bool parsed;
1420 } lazy_tx(txblob, txid, tx);
1421
1422 const std::uint64_t top_block_height{m_blockchain.get_current_blockchain_height() - 1};
1423 const crypto::hash top_block_hash{m_blockchain.get_block_id_by_height(top_block_height)};
1424
1425 if (txd.last_failed_id == top_block_hash)
1426 return false; // we are already sure that this tx isn't passing for this exact chain
1427
1428 tx_verification_context tvc{};
1429 if (!check_tx_inputs([&lazy_tx]()->cryptonote::transaction&{ return lazy_tx(); },
1430 txid,
1431 txd.max_used_block_height,
1432 txd.max_used_block_id,
1433 tvc))
1434 {
1435 txd.last_failed_height = top_block_height;
1436 txd.last_failed_id = top_block_hash;
1437 return false;
1438 }
1439
1440 //transaction is ok.
1441 return true;
1442 }
1443 //---------------------------------------------------------------------------------
1444 bool tx_memory_pool::is_transaction_ready_to_go(txpool_tx_meta_t& txd, const crypto::hash &txid, const cryptonote::blobdata& txblob, transaction &tx) const
1445 {
1446 return is_transaction_ready_to_go(txd, txid, cryptonote::blobdata_ref{txblob.data(), txblob.size()}, tx);
1447 }
1448 //---------------------------------------------------------------------------------
1449 bool tx_memory_pool::have_key_images(const std::unordered_set<crypto::key_image>& k_images, const transaction_prefix& tx)
1450 {
1451 for(size_t i = 0; i!= tx.vin.size(); i++)
1452 {
1453 CHECKED_GET_SPECIFIC_VARIANT(tx.vin[i], const txin_to_key, itk, false);
1454 if(k_images.count(itk.k_image))
1455 return true;
1456 }
1457 return false;
1458 }
1459 //---------------------------------------------------------------------------------
1460 bool tx_memory_pool::append_key_images(std::unordered_set<crypto::key_image>& k_images, const transaction_prefix& tx)
1461 {
1462 for(size_t i = 0; i!= tx.vin.size(); i++)
1463 {
1464 CHECKED_GET_SPECIFIC_VARIANT(tx.vin[i], const txin_to_key, itk, false);
1465 auto i_res = k_images.insert(itk.k_image);
1466 CHECK_AND_ASSERT_MES(i_res.second, false, "internal error: key images pool cache - inserted duplicate image in set: " << itk.k_image);
1467 }
1468 return true;
1469 }
1470 //---------------------------------------------------------------------------------
1471 void tx_memory_pool::mark_double_spend(const transaction &tx)
1472 {
1473 CRITICAL_REGION_LOCAL(m_transactions_lock);
1474 CRITICAL_REGION_LOCAL1(m_blockchain);
1475 bool changed = false;
1476 LockedTXN lock(m_blockchain.get_db());
1477 for(size_t i = 0; i!= tx.vin.size(); i++)
1478 {
1479 CHECKED_GET_SPECIFIC_VARIANT(tx.vin[i], const txin_to_key, itk, void());
1480 const key_images_container::const_iterator it = m_spent_key_images.find(itk.k_image);
1481 if (it != m_spent_key_images.end())
1482 {
1483 for (const crypto::hash &txid: it->second)
1484 {
1485 txpool_tx_meta_t meta;
1486 if (!m_blockchain.get_txpool_tx_meta(txid, meta))
1487 {
1488 MERROR("Failed to find tx meta in txpool");
1489 // continue, not fatal
1490 continue;
1491 }
1492 if (!meta.double_spend_seen)
1493 {
1494 MDEBUG("Marking " << txid << " as double spending " << itk.k_image);
1495 meta.double_spend_seen = true;
1496 changed = true;
1497 try
1498 {
1499 m_blockchain.update_txpool_tx(txid, meta);
1500 }
1501 catch (const std::exception &e)
1502 {
1503 MERROR("Failed to update tx meta: " << e.what());
1504 // continue, not fatal
1505 }
1506 }
1507 }
1508 }
1509 }
1510 lock.commit();
1511 if (changed)
1512 ++m_cookie;
1513 }
1514 //---------------------------------------------------------------------------------
1515 std::string tx_memory_pool::print_pool(bool short_format) const
1516 {
1517 std::stringstream ss;
1518 CRITICAL_REGION_LOCAL(m_transactions_lock);
1519 CRITICAL_REGION_LOCAL1(m_blockchain);
1520 m_blockchain.for_all_txpool_txes([&ss, short_format](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *txblob) {
1521 ss << "id: " << txid << std::endl;
1522 if (!short_format) {
1523 cryptonote::transaction tx;
1524 if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*txblob, tx) : parse_and_validate_tx_from_blob(*txblob, tx)))
1525 {
1526 MERROR("Failed to parse tx from txpool");
1527 return true; // continue
1528 }
1529 ss << obj_to_json_str(tx) << std::endl;
1530 }
1531 ss << "blob_size: " << (short_format ? "-" : std::to_string(txblob->size())) << std::endl
1532 << "weight: " << meta.weight << std::endl
1533 << "fee: " << print_money(meta.fee) << std::endl
1534 << "kept_by_block: " << (meta.kept_by_block ? 'T' : 'F') << std::endl
1535 << "is_local" << (meta.is_local ? 'T' : 'F') << std::endl
1536 << "double_spend_seen: " << (meta.double_spend_seen ? 'T' : 'F') << std::endl
1537 << "max_used_block_height: " << meta.max_used_block_height << std::endl
1538 << "max_used_block_id: " << meta.max_used_block_id << std::endl
1539 << "last_failed_height: " << meta.last_failed_height << std::endl
1540 << "last_failed_id: " << meta.last_failed_id << std::endl;
1541 return true;
1542 }, !short_format, relay_category::all);
1543
1544 return ss.str();
1545 }
1546 //---------------------------------------------------------------------------------
1547 //TODO: investigate whether boolean return is appropriate
1548 bool tx_memory_pool::fill_block_template(block &bl, size_t median_weight, uint64_t already_generated_coins, size_t &total_weight, uint64_t &fee, uint64_t &expected_reward, uint8_t version)
1549 {
1550 CRITICAL_REGION_LOCAL(m_transactions_lock);
1551 CRITICAL_REGION_LOCAL1(m_blockchain);
1552
1553 uint64_t best_coinbase = 0, coinbase = 0;
1554 total_weight = 0;
1555 fee = 0;
1556
1557 //baseline empty block
1558 if (!get_block_reward(median_weight, total_weight, already_generated_coins, best_coinbase, version))
1559 {
1560 MERROR("Failed to get block reward for empty block");
1561 return false;
1562 }
1563
1564
1565 size_t max_total_weight_pre_v5 = (130 * median_weight) / 100 - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE;
1566 size_t max_total_weight_v5 = 2 * median_weight - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE;
1567 size_t max_total_weight = version >= 5 ? max_total_weight_v5 : max_total_weight_pre_v5;
1568 std::unordered_set<crypto::key_image> k_images;
1569
1570 LOG_PRINT_L2("Filling block template, median weight " << median_weight << ", " << m_txs_by_fee_and_receive_time.size() << " txes in the pool");
1571
1572 LockedTXN lock(m_blockchain.get_db());
1573
1574 auto sorted_it = m_txs_by_fee_and_receive_time.begin();
1575 for (; sorted_it != m_txs_by_fee_and_receive_time.end(); ++sorted_it)
1576 {
1577 txpool_tx_meta_t meta;
1578 if (!m_blockchain.get_txpool_tx_meta(sorted_it->second, meta))
1579 {
1580 static bool warned = false;
1581 if (!warned)
1582 MERROR(" failed to find tx meta: " << sorted_it->second << " (will only print once)");
1583 warned = true;
1584 continue;
1585 }
1586 LOG_PRINT_L2("Considering " << sorted_it->second << ", weight " << meta.weight << ", current block weight " << total_weight << "/" << max_total_weight << ", current coinbase " << print_money(best_coinbase) << ", relay method " << (unsigned)meta.get_relay_method());
1587
1588 if (!meta.matches(relay_category::legacy) && !(m_mine_stem_txes && meta.get_relay_method() == relay_method::stem))
1589 {
1590 LOG_PRINT_L2(" tx relay method is " << (unsigned)meta.get_relay_method());
1591 continue;
1592 }
1593 if (meta.pruned)
1594 {
1595 LOG_PRINT_L2(" tx is pruned");
1596 continue;
1597 }
1598
1599 // Can not exceed maximum block weight
1600 if (max_total_weight < total_weight + meta.weight)
1601 {
1602 LOG_PRINT_L2(" would exceed maximum block weight");
1603 continue;
1604 }
1605
1606 // start using the optimal filling algorithm from v5
1607 if (version >= 5)
1608 {
1609 // If we're getting lower coinbase tx,
1610 // stop including more tx
1611 uint64_t block_reward;
1612 if(!get_block_reward(median_weight, total_weight + meta.weight, already_generated_coins, block_reward, version))
1613 {
1614 LOG_PRINT_L2(" would exceed maximum block weight");
1615 continue;
1616 }
1617 coinbase = block_reward + fee + meta.fee;
1618 if (coinbase < template_accept_threshold(best_coinbase))
1619 {
1620 LOG_PRINT_L2(" would decrease coinbase to " << print_money(coinbase));
1621 continue;
1622 }
1623 }
1624 else
1625 {
1626 // If we've exceeded the penalty free weight,
1627 // stop including more tx
1628 if (total_weight > median_weight)
1629 {
1630 LOG_PRINT_L2(" would exceed median block weight");
1631 break;
1632 }
1633 }
1634
1635 // "local" and "stem" txes are filtered above
1636 cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(sorted_it->second, relay_category::all);
1637
1638 cryptonote::transaction tx;
1639
1640 // Skip transactions that are not ready to be
1641 // included into the blockchain or that are
1642 // missing key images
1643 const cryptonote::txpool_tx_meta_t original_meta = meta;
1644 bool ready = false;
1645 try
1646 {
1647 ready = is_transaction_ready_to_go(meta, sorted_it->second, txblob, tx);
1648 }
1649 catch (const std::exception &e)
1650 {
1651 MERROR("Failed to check transaction readiness: " << e.what());
1652 // continue, not fatal
1653 }
1654 if (memcmp(&original_meta, &meta, sizeof(meta)))
1655 {
1656 try
1657 {
1658 m_blockchain.update_txpool_tx(sorted_it->second, meta);
1659 }
1660 catch (const std::exception &e)
1661 {
1662 MERROR("Failed to update tx meta: " << e.what());
1663 // continue, not fatal
1664 }
1665 }
1666 if (!ready)
1667 {
1668 LOG_PRINT_L2(" not ready to go");
1669 continue;
1670 }
1671 if (have_key_images(k_images, tx))
1672 {
1673 LOG_PRINT_L2(" key images already seen");
1674 continue;
1675 }
1676
1677 bl.tx_hashes.push_back(sorted_it->second);
1678 total_weight += meta.weight;
1679 fee += meta.fee;
1680 best_coinbase = coinbase;
1681 append_key_images(k_images, tx);
1682 LOG_PRINT_L2(" added, new block weight " << total_weight << "/" << max_total_weight << ", coinbase " << print_money(best_coinbase));
1683 }
1684 lock.commit();
1685
1686 expected_reward = best_coinbase;
1687 LOG_PRINT_L2("Block template filled with " << bl.tx_hashes.size() << " txes, weight "
1688 << total_weight << "/" << max_total_weight << ", coinbase " << print_money(best_coinbase)
1689 << " (including " << print_money(fee) << " in fees)");
1690 return true;
1691 }
1692 //---------------------------------------------------------------------------------
1693 size_t tx_memory_pool::validate(uint8_t version)
1694 {
1695 CRITICAL_REGION_LOCAL(m_transactions_lock);
1696 CRITICAL_REGION_LOCAL1(m_blockchain);
1697
1698 // Simply throw away incremental info, too difficult to update
1699 m_added_txs_by_id.clear();
1700 m_added_txs_start_time = (time_t)0;
1701 m_removed_txs_by_time.clear();
1702 m_removed_txs_start_time = (time_t)0;
1703
1704 MINFO("Validating txpool contents for v" << (unsigned)version);
1705
1706 LockedTXN lock(m_blockchain.get_db());
1707
1708 struct tx_entry_t
1709 {
1710 crypto::hash txid;
1711 txpool_tx_meta_t meta;
1712 };
1713
1714 // get all txids
1715 std::vector<tx_entry_t> txes;
1716 m_blockchain.for_all_txpool_txes([&txes](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref*) {
1717 if (!meta.pruned) // skip pruned txes
1718 txes.push_back({txid, meta});
1719 return true;
1720 }, false, relay_category::all);
1721
1722 // take them all out and add them back in, some might fail
1723 size_t added = 0;
1724 for (auto &e: txes)
1725 {
1726 try
1727 {
1728 size_t weight;
1729 uint64_t fee;
1730 cryptonote::transaction tx;
1731 cryptonote::blobdata blob;
1732 bool relayed, do_not_relay, double_spend_seen, pruned;
1733 if (!take_tx(e.txid, tx, blob, weight, fee, relayed, do_not_relay, double_spend_seen, pruned))
1734 MERROR("Failed to get tx " << e.txid << " from txpool for re-validation");
1735
1736 cryptonote::tx_verification_context tvc{};
1737 relay_method tx_relay = e.meta.get_relay_method();
1738 if (!add_tx(tx, e.txid, blob, e.meta.weight, tvc, tx_relay, relayed, version))
1739 {
1740 MINFO("Failed to re-validate tx " << e.txid << " for v" << (unsigned)version << ", dropped");
1741 continue;
1742 }
1743 m_blockchain.update_txpool_tx(e.txid, e.meta);
1744 ++added;
1745 }
1746 catch (const std::exception &e)
1747 {
1748 MERROR("Failed to re-validate tx from pool");
1749 continue;
1750 }
1751 }
1752
1753 lock.commit();
1754
1755 const size_t n_removed = txes.size() - added;
1756 if (n_removed > 0)
1757 ++m_cookie;
1758 return n_removed;
1759 }
1760 //---------------------------------------------------------------------------------
1761 void tx_memory_pool::add_tx_to_transient_lists(const crypto::hash& txid, double fee, time_t receive_time)
1762 {
1763
1764 time_t now = time(NULL);
1765 const std::unordered_map<crypto::hash, time_t>::iterator it = m_added_txs_by_id.find(txid);
1766 if (it == m_added_txs_by_id.end())
1767 {
1768 m_added_txs_by_id.insert(std::make_pair(txid, now));
1769 }
1770 else
1771 {
1772 // This tx was already added to the map earlier, probably because then it was in the "stem"
1773 // phase of Dandelion++ and now is in the "fluff" phase i.e. got broadcasted: We have to set
1774 // a new time for clients that are not allowed to see sensitive txs to make sure they will
1775 // see it now if they query incrementally
1776 it->second = now;
1777
1778 auto sorted_it = find_tx_in_sorted_container(txid);
1779 if (sorted_it == m_txs_by_fee_and_receive_time.end())
1780 {
1781 MDEBUG("Re-adding tx " << txid << " to tx pool, but it was not found in the sorted txs container");
1782 }
1783 else
1784 {
1785 m_txs_by_fee_and_receive_time.erase(sorted_it);
1786 }
1787 }
1788 m_txs_by_fee_and_receive_time.emplace(std::pair<double, time_t>(fee, receive_time), txid);
1789
1790 // Don't check for "resurrected" txs in case of reorgs i.e. don't check in 'm_removed_txs_by_time'
1791 // whether we have that txid there and if yes remove it; this results in possible duplicates
1792 // where we return certain txids as deleted AND in the pool at the same time which requires
1793 // clients to process deleted ones BEFORE processing pool txs
1794 if (m_added_txs_start_time == (time_t)0)
1795 {
1796 m_added_txs_start_time = now;
1797 }
1798 }
1799 //---------------------------------------------------------------------------------
1800 void tx_memory_pool::remove_tx_from_transient_lists(const cryptonote::sorted_tx_container::iterator& sorted_it, const crypto::hash& txid, bool sensitive)
1801 {
1802 if (sorted_it == m_txs_by_fee_and_receive_time.end())
1803 {
1804 LOG_PRINT_L1("Removing tx " << txid << " from tx pool, but it was not found in the sorted txs container!");
1805 }
1806 else
1807 {
1808 m_txs_by_fee_and_receive_time.erase(sorted_it);
1809 }
1810
1811 const std::unordered_map<crypto::hash, time_t>::iterator it = m_added_txs_by_id.find(txid);
1812 if (it != m_added_txs_by_id.end())
1813 {
1814 m_added_txs_by_id.erase(it);
1815 }
1816 else
1817 {
1818 MDEBUG("Removing tx " << txid << " from tx pool, but it was not found in the map of added txs");
1819 }
1820 track_removed_tx(txid, sensitive);
1821 }
1822 //---------------------------------------------------------------------------------
1823 void tx_memory_pool::track_removed_tx(const crypto::hash& txid, bool sensitive)
1824 {
1825 time_t now = time(NULL);
1826 m_removed_txs_by_time.insert(std::make_pair(now, removed_tx_info{txid, sensitive}));
1827 MDEBUG("Transaction removed from pool: txid " << txid << ", total entries in removed list now " << m_removed_txs_by_time.size());
1828 if (m_removed_txs_start_time == (time_t)0)
1829 {
1830 m_removed_txs_start_time = now;
1831 }
1832
1833 // Simple system to make sure the list of removed ids does not swell to an unmanageable size: Set
1834 // an absolute size limit plus delete entries that are x minutes old (which is ok because clients
1835 // will sync with sensible time intervalls and should not ask for incremental info e.g. 1 hour back)
1836 const int MAX_REMOVED = 20000;
1837 if (m_removed_txs_by_time.size() > MAX_REMOVED)
1838 {
1839 auto erase_it = m_removed_txs_by_time.begin();
1840 std::advance(erase_it, MAX_REMOVED / 4 + 1);
1841 m_removed_txs_by_time.erase(m_removed_txs_by_time.begin(), erase_it);
1842 m_removed_txs_start_time = m_removed_txs_by_time.begin()->first;
1843 MDEBUG("Erased old transactions from big removed list, leaving " << m_removed_txs_by_time.size());
1844 }
1845 else
1846 {
1847 time_t earliest = now - (30 * 60); // 30 minutes
1848 std::map<time_t, removed_tx_info>::iterator from, to;
1849 from = m_removed_txs_by_time.begin();
1850 to = m_removed_txs_by_time.lower_bound(earliest);
1851 int distance = std::distance(from, to);
1852 if (distance > 0)
1853 {
1854 m_removed_txs_by_time.erase(from, to);
1855 m_removed_txs_start_time = earliest;
1856 MDEBUG("Erased " << distance << " old transactions from removed list, leaving " << m_removed_txs_by_time.size());
1857 }
1858 }
1859 }
1860 //---------------------------------------------------------------------------------
1861 bool tx_memory_pool::init(size_t max_txpool_weight, bool mine_stem_txes)
1862 {
1863 CRITICAL_REGION_LOCAL(m_transactions_lock);
1864 CRITICAL_REGION_LOCAL1(m_blockchain);
1865
1866 m_txpool_max_weight = max_txpool_weight ? max_txpool_weight : DEFAULT_TXPOOL_MAX_WEIGHT;
1867 m_txs_by_fee_and_receive_time.clear();
1868 m_added_txs_by_id.clear();
1869 m_added_txs_start_time = (time_t)0;
1870 m_removed_txs_by_time.clear();
1871 m_removed_txs_start_time = (time_t)0;
1872 m_spent_key_images.clear();
1873 m_txpool_weight = 0;
1874 std::vector<crypto::hash> remove;
1875
1876 // first add the not kept by block, then the kept by block,
1877 // to avoid rejection due to key image collision
1878 for (int pass = 0; pass < 2; ++pass)
1879 {
1880 const bool kept = pass == 1;
1881 bool r = m_blockchain.for_all_txpool_txes([this, &remove, kept](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata_ref *bd) {
1882 if (!!kept != !!meta.kept_by_block)
1883 return true;
1884 cryptonote::transaction_prefix tx;
1885 if (!parse_and_validate_tx_prefix_from_blob(*bd, tx))
1886 {
1887 MWARNING("Failed to parse tx from txpool, removing");
1888 remove.push_back(txid);
1889 return true;
1890 }
1891 if (!insert_key_images(tx, txid, meta.get_relay_method()))
1892 {
1893 MFATAL("Failed to insert key images from txpool tx");
1894 return false;
1895 }
1896 add_tx_to_transient_lists(txid, meta.fee / (double)meta.weight, meta.receive_time);
1897 m_txpool_weight += meta.weight;
1898 return true;
1899 }, true, relay_category::all);
1900 if (!r)
1901 return false;
1902 }
1903 if (!remove.empty())
1904 {
1905 LockedTXN lock(m_blockchain.get_db());
1906 for (const auto &txid: remove)
1907 {
1908 try
1909 {
1910 m_blockchain.remove_txpool_tx(txid);
1911 }
1912 catch (const std::exception &e)
1913 {
1914 MWARNING("Failed to remove corrupt transaction: " << txid);
1915 // ignore error
1916 }
1917 }
1918 lock.commit();
1919 }
1920
1921 m_mine_stem_txes = mine_stem_txes;
1922 m_cookie = 0;
1923
1924 // Ignore deserialization error
1925 return true;
1926 }
1927
1928 //---------------------------------------------------------------------------------
1929 bool tx_memory_pool::deinit()
1930 {
1931 return true;
1932 }
1933 }