Debian Codegraph @

tests/core_tests/chaingen.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 <vector>
32 #include <iostream>
33 #include <sstream>
34 #include <algorithm>
35 #include <array>
36 #include <random>
37 #include <sstream>
38 #include <fstream>
39
40 #include "include_base_utils.h"
41
42 #include "console_handler.h"
43
44 #include "p2p/net_node.h"
45 #include "cryptonote_basic/cryptonote_basic.h"
46 #include "cryptonote_basic/cryptonote_basic_impl.h"
47 #include "cryptonote_basic/cryptonote_format_utils.h"
48 #include "cryptonote_basic/miner.h"
49
50 #include "blockchain_db/blockchain_db.h"
51 #include "cryptonote_core/cryptonote_core.h"
52 #include "cryptonote_core/tx_pool.h"
53 #include "cryptonote_core/blockchain.h"
54 #include "blockchain_db/testdb.h"
55
56 #include "chaingen.h"
57 #include "device/device.hpp"
58 using namespace std;
59
60 using namespace epee;
61 using namespace crypto;
62 using namespace cryptonote;
63
64 namespace
65 {
66 /**
67 * Dummy TestDB to store height -> (block, hash) information
68 * for the use only in the test_generator::fill_nonce() function,
69 * which requires blockchain object to correctly compute PoW on HF12+ blocks
70 * as the mining function requires it to obtain a valid seedhash.
71 */
72 class TestDB: public cryptonote::BaseTestDB
73 {
74 private:
75 struct block_t
76 {
77 cryptonote::block bl;
78 crypto::hash hash;
79 };
80
81 public:
82 TestDB() { m_open = true; }
83
84 virtual void add_block( const cryptonote::block& blk
85 , size_t block_weight
86 , uint64_t long_term_block_weight
87 , const cryptonote::difficulty_type& cumulative_difficulty
88 , const uint64_t& coins_generated
89 , uint64_t num_rct_outs
90 , const crypto::hash& blk_hash
91 ) override
92 {
93 blocks.push_back({blk, blk_hash});
94 }
95
96 virtual uint64_t height() const override { return blocks.empty() ? 0 : blocks.size() - 1; }
97
98 // Required for randomx
99 virtual crypto::hash get_block_hash_from_height(const uint64_t &height) const override
100 {
101 if (height < blocks.size())
102 {
103 MDEBUG("Get hash for block height: " << height << " hash: " << blocks[height].hash);
104 return blocks[height].hash;
105 }
106
107 MDEBUG("Get hash for block height: " << height << " zero-hash");
108 crypto::hash hash = crypto::null_hash;
109 *(uint64_t*)&hash = height;
110 return hash;
111 }
112
113 virtual crypto::hash top_block_hash(uint64_t *block_height = NULL) const override
114 {
115 const uint64_t h = height();
116 if (block_height != nullptr)
117 {
118 *block_height = h;
119 }
120
121 return get_block_hash_from_height(h);
122 }
123
124 virtual cryptonote::block get_top_block() const override
125 {
126 if (blocks.empty())
127 {
128 cryptonote::block b;
129 return b;
130 }
131
132 return blocks[blocks.size()-1].bl;
133 }
134
135 virtual void pop_block(cryptonote::block &blk, std::vector<cryptonote::transaction> &txs) override { if (!blocks.empty()) blocks.pop_back(); }
136 virtual void set_hard_fork_version(uint64_t height, uint8_t version) override { if (height >= hf.size()) hf.resize(height + 1); hf[height] = version; }
137 virtual uint8_t get_hard_fork_version(uint64_t height) const override { if (height >= hf.size()) return 255; return hf[height]; }
138
139 private:
140 std::vector<block_t> blocks;
141 std::vector<uint8_t> hf;
142 };
143
144 }
145
146 static std::unique_ptr<cryptonote::Blockchain> init_blockchain(const std::vector<test_event_entry> & events, cryptonote::network_type nettype)
147 {
148 std::unique_ptr<cryptonote::Blockchain> bc;
149 v_hardforks_t hardforks;
150 cryptonote::test_options test_options_tmp{nullptr, 0};
151 const cryptonote::test_options * test_options = &test_options_tmp;
152 if (!extract_hard_forks(events, hardforks))
153 {
154 MDEBUG("Extracting hard-forks from blocks");
155 extract_hard_forks_from_blocks(events, hardforks);
156 }
157
158 hardforks.push_back(std::make_pair((uint8_t)0, (uint64_t)0)); // terminator
159 test_options_tmp.hard_forks = hardforks.data();
160 test_options = &test_options_tmp;
161
162 cryptonote::tx_memory_pool txpool(*bc);
163 bc.reset(new cryptonote::Blockchain(txpool));
164
165 cryptonote::Blockchain *blockchain = bc.get();
166 auto bdb = new TestDB();
167
168 BOOST_FOREACH(const test_event_entry &ev, events)
169 {
170 if (typeid(block) != ev.type())
171 {
172 continue;
173 }
174
175 const block *blk = &boost::get<block>(ev);
176 auto blk_hash = get_block_hash(*blk);
177 bdb->add_block(*blk, 1, 1, 1, 0, 0, blk_hash);
178 }
179
180 bool r = blockchain->init(bdb, nettype, true, test_options, 2, nullptr);
181 CHECK_AND_ASSERT_THROW_MES(r, "could not init blockchain from events");
182 return bc;
183 }
184
185 void test_generator::get_block_chain(std::vector<block_info>& blockchain, const crypto::hash& head, size_t n) const
186 {
187 crypto::hash curr = head;
188 while (null_hash != curr && blockchain.size() < n)
189 {
190 auto it = m_blocks_info.find(curr);
191 if (m_blocks_info.end() == it)
192 {
193 throw std::runtime_error("block hash wasn't found");
194 }
195
196 blockchain.push_back(it->second);
197 curr = it->second.prev_id;
198 }
199
200 std::reverse(blockchain.begin(), blockchain.end());
201 }
202
203 void test_generator::get_last_n_block_weights(std::vector<size_t>& block_weights, const crypto::hash& head, size_t n) const
204 {
205 std::vector<block_info> blockchain;
206 get_block_chain(blockchain, head, n);
207 BOOST_FOREACH(auto& bi, blockchain)
208 {
209 block_weights.push_back(bi.block_weight);
210 }
211 }
212
213 uint64_t test_generator::get_already_generated_coins(const crypto::hash& blk_id) const
214 {
215 auto it = m_blocks_info.find(blk_id);
216 if (it == m_blocks_info.end())
217 throw std::runtime_error("block hash wasn't found");
218
219 return it->second.already_generated_coins;
220 }
221
222 uint64_t test_generator::get_already_generated_coins(const cryptonote::block& blk) const
223 {
224 crypto::hash blk_hash;
225 get_block_hash(blk, blk_hash);
226 return get_already_generated_coins(blk_hash);
227 }
228
229 void test_generator::add_block(const cryptonote::block& blk, size_t txs_weight, std::vector<size_t>& block_weights, uint64_t already_generated_coins, uint64_t block_reward, uint8_t hf_version)
230 {
231 const size_t block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
232 m_blocks_info[get_block_hash(blk)] = block_info(blk.prev_id, already_generated_coins + block_reward, block_weight);
233 }
234
235 bool test_generator::construct_block(cryptonote::block& blk, uint64_t height, const crypto::hash& prev_id,
236 const cryptonote::account_base& miner_acc, uint64_t timestamp, uint64_t already_generated_coins,
237 std::vector<size_t>& block_weights, const std::list<cryptonote::transaction>& tx_list,
238 const boost::optional<uint8_t>& hf_ver)
239 {
240 blk.major_version = hf_ver ? hf_ver.get() : CURRENT_BLOCK_MAJOR_VERSION;
241 blk.minor_version = hf_ver ? hf_ver.get() : CURRENT_BLOCK_MINOR_VERSION;
242 blk.timestamp = timestamp;
243 blk.prev_id = prev_id;
244
245 blk.tx_hashes.reserve(tx_list.size());
246 BOOST_FOREACH(const transaction &tx, tx_list)
247 {
248 crypto::hash tx_hash;
249 get_transaction_hash(tx, tx_hash);
250 blk.tx_hashes.push_back(tx_hash);
251 }
252
253 uint64_t total_fee = 0;
254 size_t txs_weight = 0;
255 BOOST_FOREACH(auto& tx, tx_list)
256 {
257 uint64_t fee = 0;
258 bool r = get_tx_fee(tx, fee);
259 CHECK_AND_ASSERT_MES(r, false, "wrong transaction passed to construct_block");
260 total_fee += fee;
261 txs_weight += get_transaction_weight(tx);
262 }
263
264 blk.miner_tx = AUTO_VAL_INIT(blk.miner_tx);
265 size_t target_block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
266 while (true)
267 {
268 if (!construct_miner_tx(height, misc_utils::median(block_weights), already_generated_coins, target_block_weight, total_fee, miner_acc.get_keys().m_account_address, blk.miner_tx, blobdata(), 10, hf_ver ? hf_ver.get() : 1))
269 return false;
270
271 size_t actual_block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
272 if (target_block_weight < actual_block_weight)
273 {
274 target_block_weight = actual_block_weight;
275 }
276 else if (actual_block_weight < target_block_weight)
277 {
278 size_t delta = target_block_weight - actual_block_weight;
279 blk.miner_tx.extra.resize(blk.miner_tx.extra.size() + delta, 0);
280 actual_block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
281 if (actual_block_weight == target_block_weight)
282 {
283 break;
284 }
285 else
286 {
287 CHECK_AND_ASSERT_MES(target_block_weight < actual_block_weight, false, "Unexpected block size");
288 delta = actual_block_weight - target_block_weight;
289 blk.miner_tx.extra.resize(blk.miner_tx.extra.size() - delta);
290 actual_block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
291 if (actual_block_weight == target_block_weight)
292 {
293 break;
294 }
295 else
296 {
297 CHECK_AND_ASSERT_MES(actual_block_weight < target_block_weight, false, "Unexpected block size");
298 blk.miner_tx.extra.resize(blk.miner_tx.extra.size() + delta, 0);
299 target_block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
300 }
301 }
302 }
303 else
304 {
305 break;
306 }
307 }
308
309 //blk.tree_root_hash = get_tx_tree_hash(blk);
310
311 fill_nonce(blk, get_test_difficulty(hf_ver), height);
312 const uint64_t block_reward = get_outs_money_amount(blk.miner_tx) - total_fee;
313 add_block(blk, txs_weight, block_weights, already_generated_coins, block_reward, hf_ver ? hf_ver.get() : 1);
314
315 return true;
316 }
317
318 bool test_generator::construct_block(cryptonote::block& blk, const cryptonote::account_base& miner_acc, uint64_t timestamp)
319 {
320 std::vector<size_t> block_weights;
321 std::list<cryptonote::transaction> tx_list;
322 return construct_block(blk, 0, null_hash, miner_acc, timestamp, 0, block_weights, tx_list);
323 }
324
325 bool test_generator::construct_block(cryptonote::block& blk, const cryptonote::block& blk_prev,
326 const cryptonote::account_base& miner_acc,
327 const std::list<cryptonote::transaction>& tx_list/* = std::list<cryptonote::transaction>()*/,
328 const boost::optional<uint8_t>& hf_ver)
329 {
330 uint64_t height = boost::get<txin_gen>(blk_prev.miner_tx.vin.front()).height + 1;
331 crypto::hash prev_id = get_block_hash(blk_prev);
332 // Keep difficulty unchanged
333 uint64_t timestamp = blk_prev.timestamp + current_difficulty_window(hf_ver); // DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN;
334 uint64_t already_generated_coins = get_already_generated_coins(prev_id);
335 std::vector<size_t> block_weights;
336 get_last_n_block_weights(block_weights, prev_id, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
337
338 return construct_block(blk, height, prev_id, miner_acc, timestamp, already_generated_coins, block_weights, tx_list, hf_ver);
339 }
340
341 bool test_generator::construct_block_manually(block& blk, const block& prev_block, const account_base& miner_acc,
342 int actual_params/* = bf_none*/, uint8_t major_ver/* = 0*/,
343 uint8_t minor_ver/* = 0*/, uint64_t timestamp/* = 0*/,
344 const crypto::hash& prev_id/* = crypto::hash()*/, const difficulty_type& diffic/* = 1*/,
345 const transaction& miner_tx/* = transaction()*/,
346 const std::vector<crypto::hash>& tx_hashes/* = std::vector<crypto::hash>()*/,
347 size_t txs_weight/* = 0*/, size_t max_outs/* = 0*/, uint8_t hf_version/* = 1*/,
348 uint64_t fees/* = 0*/)
349 {
350 blk.major_version = actual_params & bf_major_ver ? major_ver : CURRENT_BLOCK_MAJOR_VERSION;
351 blk.minor_version = actual_params & bf_minor_ver ? minor_ver : CURRENT_BLOCK_MINOR_VERSION;
352 blk.timestamp = actual_params & bf_timestamp ? timestamp : prev_block.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN; // Keep difficulty unchanged
353 blk.prev_id = actual_params & bf_prev_id ? prev_id : get_block_hash(prev_block);
354 blk.tx_hashes = actual_params & bf_tx_hashes ? tx_hashes : std::vector<crypto::hash>();
355 max_outs = actual_params & bf_max_outs ? max_outs : 9999;
356 hf_version = actual_params & bf_hf_version ? hf_version : 1;
357 fees = actual_params & bf_tx_fees ? fees : 0;
358
359 size_t height = get_block_height(prev_block) + 1;
360 uint64_t already_generated_coins = get_already_generated_coins(prev_block);
361 std::vector<size_t> block_weights;
362 get_last_n_block_weights(block_weights, get_block_hash(prev_block), CRYPTONOTE_REWARD_BLOCKS_WINDOW);
363 if (actual_params & bf_miner_tx)
364 {
365 blk.miner_tx = miner_tx;
366 }
367 else
368 {
369 size_t current_block_weight = txs_weight + get_transaction_weight(blk.miner_tx);
370 // TODO: This will work, until size of constructed block is less then CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE
371 if (!construct_miner_tx(height, misc_utils::median(block_weights), already_generated_coins, current_block_weight, fees, miner_acc.get_keys().m_account_address, blk.miner_tx, blobdata(), max_outs, hf_version))
372 return false;
373 }
374
375 //blk.tree_root_hash = get_tx_tree_hash(blk);
376
377 difficulty_type a_diffic = actual_params & bf_diffic ? diffic : get_test_difficulty(hf_version);
378 fill_nonce(blk, a_diffic, height);
379
380 const uint64_t block_reward = get_outs_money_amount(blk.miner_tx) - fees;
381 add_block(blk, txs_weight, block_weights, already_generated_coins, block_reward, hf_version);
382
383 return true;
384 }
385
386 bool test_generator::construct_block_manually_tx(cryptonote::block& blk, const cryptonote::block& prev_block,
387 const cryptonote::account_base& miner_acc,
388 const std::vector<crypto::hash>& tx_hashes, size_t txs_weight)
389 {
390 return construct_block_manually(blk, prev_block, miner_acc, bf_tx_hashes, 0, 0, 0, crypto::hash(), 0, transaction(), tx_hashes, txs_weight);
391 }
392
393 void test_generator::fill_nonce(cryptonote::block& blk, const difficulty_type& diffic, uint64_t height)
394 {
395 const cryptonote::Blockchain *blockchain = nullptr;
396 std::unique_ptr<cryptonote::Blockchain> bc;
397
398 if (blk.major_version >= RX_BLOCK_VERSION && diffic > 1)
399 {
400 if (m_events == nullptr)
401 {
402 MDEBUG("events not set, RandomX PoW can fail due to zero seed hash");
403 }
404 else
405 {
406 bc = init_blockchain(*m_events, m_nettype);
407 blockchain = bc.get();
408 }
409 }
410
411 blk.nonce = 0;
412 while (!miner::find_nonce_for_given_block([blockchain](const cryptonote::block &b, uint64_t height, const crypto::hash *seed_hash, unsigned int threads, crypto::hash &hash){
413 return cryptonote::get_block_longhash(blockchain, b, hash, height, seed_hash, threads);
414 }, blk, diffic, height, NULL)) {
415 blk.timestamp++;
416 }
417 }
418
419 namespace
420 {
421 uint64_t get_inputs_amount(const vector<tx_source_entry> &s)
422 {
423 uint64_t r = 0;
424 BOOST_FOREACH(const tx_source_entry &e, s)
425 {
426 r += e.amount;
427 }
428
429 return r;
430 }
431 }
432
433 bool init_output_indices(map_output_idx_t& outs, std::map<uint64_t, std::vector<size_t> >& outs_mine, const std::vector<cryptonote::block>& blockchain, const map_hash2tx_t& mtx, const cryptonote::account_base& from) {
434
435 BOOST_FOREACH (const block& blk, blockchain) {
436 vector<const transaction*> vtx;
437 vtx.push_back(&blk.miner_tx);
438
439 BOOST_FOREACH(const crypto::hash &h, blk.tx_hashes) {
440 const map_hash2tx_t::const_iterator cit = mtx.find(h);
441 if (mtx.end() == cit)
442 throw std::runtime_error("block contains an unknown tx hash");
443
444 vtx.push_back(cit->second);
445 }
446
447 //vtx.insert(vtx.end(), blk.);
448 // TODO: add all other txes
449 for (size_t i = 0; i < vtx.size(); i++) {
450 const transaction &tx = *vtx[i];
451
452 for (size_t j = 0; j < tx.vout.size(); ++j) {
453 const tx_out &out = tx.vout[j];
454
455 output_index oi(out.target, out.amount, boost::get<txin_gen>(*blk.miner_tx.vin.begin()).height, i, j, &blk, vtx[i]);
456 oi.set_rct(tx.version == 2);
457 oi.unlock_time = tx.unlock_time;
458 oi.is_coin_base = i == 0;
459
460 if (2 == out.target.which()) { // out_to_key
461 outs[out.amount].push_back(oi);
462 size_t tx_global_idx = outs[out.amount].size() - 1;
463 outs[out.amount][tx_global_idx].idx = tx_global_idx;
464 // Is out to me?
465 crypto::public_key output_public_key;
466 cryptonote::get_output_public_key(out, output_public_key);
467 if (is_out_to_acc(from.get_keys(), output_public_key, get_tx_pub_key_from_extra(tx), get_additional_tx_pub_keys_from_extra(tx), j)) {
468 outs_mine[out.amount].push_back(tx_global_idx);
469 }
470 }
471 }
472 }
473 }
474
475 return true;
476 }
477
478 bool init_spent_output_indices(map_output_idx_t& outs, map_output_t& outs_mine, const std::vector<cryptonote::block>& blockchain, const map_hash2tx_t& mtx, const cryptonote::account_base& from) {
479
480 BOOST_FOREACH (const map_output_t::value_type &o, outs_mine) {
481 for (size_t i = 0; i < o.second.size(); ++i) {
482 output_index &oi = outs[o.first][o.second[i]];
483
484 // construct key image for this output
485 crypto::key_image img;
486 keypair in_ephemeral;
487 crypto::public_key out_key = boost::get<txout_to_key>(oi.out).key;
488 std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses;
489 subaddresses[from.get_keys().m_account_address.m_spend_public_key] = {0,0};
490 generate_key_image_helper(from.get_keys(), subaddresses, out_key, get_tx_pub_key_from_extra(*oi.p_tx), get_additional_tx_pub_keys_from_extra(*oi.p_tx), oi.out_no, in_ephemeral, img, hw::get_device(("default")));
491
492 // lookup for this key image in the events vector
493 BOOST_FOREACH(auto& tx_pair, mtx) {
494 const transaction& tx = *tx_pair.second;
495 BOOST_FOREACH(const txin_v &in, tx.vin) {
496 if (typeid(txin_to_key) == in.type()) {
497 const txin_to_key &itk = boost::get<txin_to_key>(in);
498 if (itk.k_image == img) {
499 oi.spent = true;
500 }
501 }
502 }
503 }
504 }
505 }
506
507 return true;
508 }
509
510 bool fill_output_entries(std::vector<output_index>& out_indices, size_t sender_out, size_t nmix, size_t& real_entry_idx, std::vector<tx_source_entry::output_entry>& output_entries)
511 {
512 if (out_indices.size() <= nmix)
513 return false;
514
515 bool sender_out_found = false;
516 size_t rest = nmix;
517 for (size_t i = 0; i < out_indices.size() && (0 < rest || !sender_out_found); ++i)
518 {
519 const output_index& oi = out_indices[i];
520 if (oi.spent)
521 continue;
522
523 bool append = false;
524 if (i == sender_out)
525 {
526 append = true;
527 sender_out_found = true;
528 real_entry_idx = output_entries.size();
529 }
530 else if (0 < rest)
531 {
532 --rest;
533 append = true;
534 }
535
536 if (append)
537 {
538 rct::key comm = oi.commitment();
539 const txout_to_key& otk = boost::get<txout_to_key>(oi.out);
540 output_entries.push_back(tx_source_entry::output_entry(oi.idx, rct::ctkey({rct::pk2rct(otk.key), comm})));
541 }
542 }
543
544 return 0 == rest && sender_out_found;
545 }
546
547 bool fill_tx_sources(std::vector<tx_source_entry>& sources, const std::vector<test_event_entry>& events,
548 const block& blk_head, const cryptonote::account_base& from, uint64_t amount, size_t nmix)
549 {
550 map_output_idx_t outs;
551 map_output_t outs_mine;
552
553 std::vector<cryptonote::block> blockchain;
554 map_hash2tx_t mtx;
555 if (!find_block_chain(events, blockchain, mtx, get_block_hash(blk_head)))
556 return false;
557
558 if (!init_output_indices(outs, outs_mine, blockchain, mtx, from))
559 return false;
560
561 if (!init_spent_output_indices(outs, outs_mine, blockchain, mtx, from))
562 return false;
563
564 // Iterate in reverse is more efficiency
565 uint64_t sources_amount = 0;
566 bool sources_found = false;
567 BOOST_REVERSE_FOREACH(const map_output_t::value_type o, outs_mine)
568 {
569 for (size_t i = 0; i < o.second.size() && !sources_found; ++i)
570 {
571 size_t sender_out = o.second[i];
572 const output_index& oi = outs[o.first][sender_out];
573 if (oi.spent)
574 continue;
575 if (oi.rct)
576 continue;
577
578 cryptonote::tx_source_entry ts;
579 ts.amount = oi.amount;
580 ts.real_output_in_tx_index = oi.out_no;
581 ts.real_out_tx_key = get_tx_pub_key_from_extra(*oi.p_tx); // incoming tx public key
582 size_t realOutput;
583 if (!fill_output_entries(outs[o.first], sender_out, nmix, realOutput, ts.outputs))
584 continue;
585
586 ts.real_output = realOutput;
587 ts.rct = false;
588 ts.mask = rct::identity(); // non-rct has identity mask by definition
589
590 rct::key comm = rct::zeroCommit(ts.amount);
591 for(auto & ot : ts.outputs)
592 ot.second.mask = comm;
593
594 sources.push_back(ts);
595
596 sources_amount += ts.amount;
597 sources_found = amount <= sources_amount;
598 }
599
600 if (sources_found)
601 break;
602 }
603
604 return sources_found;
605 }
606
607 bool fill_tx_destination(tx_destination_entry &de, const cryptonote::account_public_address &to, uint64_t amount) {
608 de.addr = to;
609 de.amount = amount;
610 return true;
611 }
612
613 map_txid_output_t::iterator block_tracker::find_out(const crypto::hash &txid, size_t out)
614 {
615 return find_out(std::make_pair(txid, out));
616 }
617
618 map_txid_output_t::iterator block_tracker::find_out(const output_hasher &id)
619 {
620 return m_map_outs.find(id);
621 }
622
623 void block_tracker::process(const std::vector<cryptonote::block>& blockchain, const map_hash2tx_t& mtx)
624 {
625 std::vector<const cryptonote::block*> blks;
626 blks.reserve(blockchain.size());
627
628 BOOST_FOREACH (const block& blk, blockchain) {
629 auto hsh = get_block_hash(blk);
630 auto it = m_blocks.find(hsh);
631 if (it == m_blocks.end()){
632 m_blocks[hsh] = blk;
633 }
634
635 blks.push_back(&m_blocks[hsh]);
636 }
637
638 process(blks, mtx);
639 }
640
641 void block_tracker::process(const std::vector<const cryptonote::block*>& blockchain, const map_hash2tx_t& mtx)
642 {
643 BOOST_FOREACH (const block* blk, blockchain) {
644 vector<const transaction*> vtx;
645 vtx.push_back(&(blk->miner_tx));
646
647 BOOST_FOREACH(const crypto::hash &h, blk->tx_hashes) {
648 const map_hash2tx_t::const_iterator cit = mtx.find(h);
649 CHECK_AND_ASSERT_THROW_MES(mtx.end() != cit, "block contains an unknown tx hash");
650 vtx.push_back(cit->second);
651 }
652
653 for (size_t i = 0; i < vtx.size(); i++) {
654 process(blk, vtx[i], i);
655 }
656 }
657 }
658
659 void block_tracker::process(const block* blk, const transaction * tx, size_t i)
660 {
661 for (size_t j = 0; j < tx->vout.size(); ++j) {
662 const tx_out &out = tx->vout[j];
663
664 if (typeid(cryptonote::txout_to_key) != out.target.type() && typeid(cryptonote::txout_to_tagged_key) != out.target.type()) {
665 continue;
666 }
667
668 const uint64_t rct_amount = tx->version == 2 ? 0 : out.amount;
669 const output_hasher hid = std::make_pair(tx->hash, j);
670 auto it = find_out(hid);
671 if (it != m_map_outs.end()){
672 continue;
673 }
674
675 output_index oi(out.target, out.amount, boost::get<txin_gen>(blk->miner_tx.vin.front()).height, i, j, blk, tx);
676 oi.set_rct(tx->version == 2);
677 oi.idx = m_outs[rct_amount].size();
678 oi.unlock_time = tx->unlock_time;
679 oi.is_coin_base = tx->vin.size() == 1 && tx->vin.back().type() == typeid(cryptonote::txin_gen);
680
681 m_outs[rct_amount].push_back(oi);
682 m_map_outs.insert({hid, oi});
683 }
684 }
685
686 void block_tracker::global_indices(const cryptonote::transaction *tx, std::vector<uint64_t> &indices)
687 {
688 indices.clear();
689
690 for(size_t j=0; j < tx->vout.size(); ++j){
691 auto it = find_out(tx->hash, j);
692 if (it != m_map_outs.end()){
693 indices.push_back(it->second.idx);
694 }
695 }
696 }
697
698 void block_tracker::get_fake_outs(size_t num_outs, uint64_t amount, uint64_t global_index, uint64_t cur_height, std::vector<get_outs_entry> &outs){
699 auto & vct = m_outs[amount];
700 const size_t n_outs = vct.size();
701 CHECK_AND_ASSERT_THROW_MES(n_outs > 0, "n_outs is 0");
702
703 std::set<size_t> used;
704 std::vector<size_t> choices;
705 choices.resize(n_outs);
706 for(size_t i=0; i < n_outs; ++i) choices[i] = i;
707 shuffle(choices.begin(), choices.end(), std::default_random_engine(crypto::rand<unsigned>()));
708
709 size_t n_iters = 0;
710 ssize_t idx = -1;
711 outs.reserve(num_outs);
712 while(outs.size() < num_outs){
713 n_iters += 1;
714 idx = (idx + 1) % n_outs;
715 size_t oi_idx = choices[(size_t)idx];
716 CHECK_AND_ASSERT_THROW_MES((n_iters / n_outs) <= outs.size(), "Fake out pick selection problem");
717
718 auto & oi = vct[oi_idx];
719 if (oi.idx == global_index)
720 continue;
721 if (oi.out.type() != typeid(cryptonote::txout_to_key))
722 continue;
723 if (oi.unlock_time > cur_height)
724 continue;
725 if (used.find(oi_idx) != used.end())
726 continue;
727
728 rct::key comm = oi.commitment();
729 auto out = boost::get<txout_to_key>(oi.out);
730 auto item = std::make_tuple(oi.idx, out.key, comm);
731 outs.push_back(item);
732 used.insert(oi_idx);
733 }
734 }
735
736 std::string block_tracker::dump_data()
737 {
738 ostringstream ss;
739 for (auto &m_out : m_outs)
740 {
741 auto & vct = m_out.second;
742 ss << m_out.first << " => |vector| = " << vct.size() << '\n';
743
744 for (const auto & oi : vct)
745 {
746 auto out = boost::get<txout_to_key>(oi.out);
747
748 ss << " idx: " << oi.idx
749 << ", rct: " << oi.rct
750 << ", xmr: " << oi.amount
751 << ", key: " << dump_keys(out.key.data)
752 << ", msk: " << dump_keys(oi.comm.bytes)
753 << ", txid: " << dump_keys(oi.p_tx->hash.data)
754 << '\n';
755 }
756 }
757
758 return ss.str();
759 }
760
761 void block_tracker::dump_data(const std::string & fname)
762 {
763 ofstream myfile;
764 myfile.open (fname);
765 myfile << dump_data();
766 myfile.close();
767 }
768
769 std::string dump_data(const cryptonote::transaction &tx)
770 {
771 ostringstream ss;
772 ss << "msg: " << dump_keys(tx.rct_signatures.message.bytes)
773 << ", vin: ";
774
775 for(auto & in : tx.vin){
776 if (typeid(txin_to_key) == in.type()){
777 auto tk = boost::get<txin_to_key>(in);
778 std::vector<uint64_t> full_off;
779 int64_t last = -1;
780
781 ss << " i: " << tk.amount << " [";
782 for(auto ix : tk.key_offsets){
783 ss << ix << ", ";
784 if (last == -1){
785 last = ix;
786 full_off.push_back(ix);
787 } else {
788 last += ix;
789 full_off.push_back((uint64_t)last);
790 }
791 }
792
793 ss << "], full: [";
794 for(auto ix : full_off){
795 ss << ix << ", ";
796 }
797 ss << "]; ";
798
799 } else if (typeid(txin_gen) == in.type()){
800 ss << " h: " << boost::get<txin_gen>(in).height << ", ";
801 } else {
802 ss << " ?, ";
803 }
804 }
805
806 ss << ", mixring: \n";
807 for (const auto & row : tx.rct_signatures.mixRing){
808 for(auto cur : row){
809 ss << " (" << dump_keys(cur.dest.bytes) << ", " << dump_keys(cur.mask.bytes) << ")\n ";
810 }
811 ss << "; ";
812 }
813
814 return ss.str();
815 }
816
817 cryptonote::account_public_address get_address(const var_addr_t& inp)
818 {
819 if (typeid(cryptonote::account_public_address) == inp.type()){
820 return boost::get<cryptonote::account_public_address>(inp);
821 } else if(typeid(cryptonote::account_keys) == inp.type()){
822 return boost::get<cryptonote::account_keys>(inp).m_account_address;
823 } else if (typeid(cryptonote::account_base) == inp.type()){
824 return boost::get<cryptonote::account_base>(inp).get_keys().m_account_address;
825 } else if (typeid(cryptonote::tx_destination_entry) == inp.type()){
826 return boost::get<cryptonote::tx_destination_entry>(inp).addr;
827 } else {
828 throw std::runtime_error("Unexpected type");
829 }
830 }
831
832 cryptonote::account_public_address get_address(const cryptonote::account_public_address& inp)
833 {
834 return inp;
835 }
836
837 cryptonote::account_public_address get_address(const cryptonote::account_keys& inp)
838 {
839 return inp.m_account_address;
840 }
841
842 cryptonote::account_public_address get_address(const cryptonote::account_base& inp)
843 {
844 return inp.get_keys().m_account_address;
845 }
846
847 cryptonote::account_public_address get_address(const cryptonote::tx_destination_entry& inp)
848 {
849 return inp.addr;
850 }
851
852 uint64_t sum_amount(const std::vector<tx_destination_entry>& destinations)
853 {
854 uint64_t amount = 0;
855 for(auto & cur : destinations){
856 amount += cur.amount;
857 }
858
859 return amount;
860 }
861
862 uint64_t sum_amount(const std::vector<cryptonote::tx_source_entry>& sources)
863 {
864 uint64_t amount = 0;
865 for(auto & cur : sources){
866 amount += cur.amount;
867 }
868
869 return amount;
870 }
871
872 void fill_tx_destinations(const var_addr_t& from, const std::vector<tx_destination_entry>& dests,
873 uint64_t fee,
874 const std::vector<tx_source_entry> &sources,
875 std::vector<tx_destination_entry>& destinations,
876 bool always_change)
877
878 {
879 destinations.clear();
880 uint64_t amount = sum_amount(dests);
881 std::copy(dests.begin(), dests.end(), std::back_inserter(destinations));
882
883 tx_destination_entry de_change;
884 uint64_t cache_back = get_inputs_amount(sources) - (amount + fee);
885
886 if (cache_back > 0 || always_change) {
887 if (!fill_tx_destination(de_change, get_address(from), cache_back <= 0 ? 0 : cache_back))
888 throw std::runtime_error("couldn't fill transaction cache back destination");
889 destinations.push_back(de_change);
890 }
891 }
892
893 void fill_tx_destinations(const var_addr_t& from, const cryptonote::account_public_address& to,
894 uint64_t amount, uint64_t fee,
895 const std::vector<tx_source_entry> &sources,
896 std::vector<tx_destination_entry>& destinations,
897 std::vector<tx_destination_entry>& destinations_pure,
898 bool always_change)
899 {
900 destinations.clear();
901
902 tx_destination_entry de;
903 if (!fill_tx_destination(de, to, amount))
904 throw std::runtime_error("couldn't fill transaction destination");
905 destinations.push_back(de);
906 destinations_pure.push_back(de);
907
908 tx_destination_entry de_change;
909 uint64_t cache_back = get_inputs_amount(sources) - (amount + fee);
910
911 if (cache_back > 0 || always_change) {
912 if (!fill_tx_destination(de_change, get_address(from), cache_back <= 0 ? 0 : cache_back))
913 throw std::runtime_error("couldn't fill transaction cache back destination");
914 destinations.push_back(de_change);
915 }
916 }
917
918 void fill_tx_destinations(const var_addr_t& from, const cryptonote::account_public_address& to,
919 uint64_t amount, uint64_t fee,
920 const std::vector<tx_source_entry> &sources,
921 std::vector<tx_destination_entry>& destinations, bool always_change)
922 {
923 std::vector<tx_destination_entry> destinations_pure;
924 fill_tx_destinations(from, to, amount, fee, sources, destinations, destinations_pure, always_change);
925 }
926
927 void fill_tx_sources_and_destinations(const std::vector<test_event_entry>& events, const block& blk_head,
928 const cryptonote::account_base& from, const cryptonote::account_public_address& to,
929 uint64_t amount, uint64_t fee, size_t nmix, std::vector<tx_source_entry>& sources,
930 std::vector<tx_destination_entry>& destinations)
931 {
932 sources.clear();
933 destinations.clear();
934
935 if (!fill_tx_sources(sources, events, blk_head, from, amount + fee, nmix))
936 throw std::runtime_error("couldn't fill transaction sources");
937
938 fill_tx_destinations(from, to, amount, fee, sources, destinations, false);
939 }
940
941 void fill_tx_sources_and_destinations(const std::vector<test_event_entry>& events, const block& blk_head,
942 const cryptonote::account_base& from, const cryptonote::account_base& to,
943 uint64_t amount, uint64_t fee, size_t nmix, std::vector<tx_source_entry>& sources,
944 std::vector<tx_destination_entry>& destinations)
945 {
946 fill_tx_sources_and_destinations(events, blk_head, from, to.get_keys().m_account_address, amount, fee, nmix, sources, destinations);
947 }
948
949 cryptonote::tx_destination_entry build_dst(const var_addr_t& to, bool is_subaddr, uint64_t amount)
950 {
951 tx_destination_entry de;
952 de.amount = amount;
953 de.addr = get_address(to);
954 de.is_subaddress = is_subaddr;
955 return de;
956 }
957
958 std::vector<cryptonote::tx_destination_entry> build_dsts(const var_addr_t& to1, bool sub1, uint64_t am1)
959 {
960 std::vector<cryptonote::tx_destination_entry> res;
961 res.push_back(build_dst(to1, sub1, am1));
962 return res;
963 }
964
965 std::vector<cryptonote::tx_destination_entry> build_dsts(std::initializer_list<dest_wrapper_t> inps)
966 {
967 std::vector<cryptonote::tx_destination_entry> res;
968 res.reserve(inps.size());
969 for(auto & c : inps){
970 res.push_back(build_dst(c.addr, c.is_subaddr, c.amount));
971 }
972 return res;
973 }
974
975 bool construct_miner_tx_manually(size_t height, uint64_t already_generated_coins,
976 const account_public_address& miner_address, transaction& tx, uint64_t fee,
977 uint8_t hf_version/* = 1*/, keypair* p_txkey/* = 0*/)
978 {
979 keypair txkey;
980 txkey = keypair::generate(hw::get_device("default"));
981 add_tx_pub_key_to_extra(tx, txkey.pub);
982
983 if (0 != p_txkey)
984 *p_txkey = txkey;
985
986 txin_gen in;
987 in.height = height;
988 tx.vin.push_back(in);
989
990 // This will work, until size of constructed block is less then CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE
991 uint64_t block_reward;
992 if (!get_block_reward(0, 0, already_generated_coins, block_reward, hf_version))
993 {
994 LOG_PRINT_L0("Block is too big");
995 return false;
996 }
997 block_reward += fee;
998
999 crypto::key_derivation derivation;
1000 crypto::public_key out_eph_public_key;
1001 crypto::generate_key_derivation(miner_address.m_view_public_key, txkey.sec, derivation);
1002 crypto::derive_public_key(derivation, 0, miner_address.m_spend_public_key, out_eph_public_key);
1003
1004 bool use_view_tags = hf_version >= HF_VERSION_VIEW_TAGS;
1005 crypto::view_tag view_tag;
1006 if (use_view_tags)
1007 crypto::derive_view_tag(derivation, 0, view_tag);
1008
1009 tx_out out;
1010 cryptonote::set_tx_out(block_reward, out_eph_public_key, use_view_tags, view_tag, out);
1011
1012 tx.vout.push_back(out);
1013
1014 if (hf_version >= HF_VERSION_DYNAMIC_FEE)
1015 tx.version = 2;
1016 else
1017 tx.version = 1;
1018 tx.unlock_time = height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW;
1019
1020 return true;
1021 }
1022
1023 bool construct_tx_to_key(const std::vector<test_event_entry>& events, cryptonote::transaction& tx, const cryptonote::block& blk_head,
1024 const cryptonote::account_base& from, const var_addr_t& to, uint64_t amount,
1025 uint64_t fee, size_t nmix, bool rct, rct::RangeProofType range_proof_type, int bp_version)
1026 {
1027 vector<tx_source_entry> sources;
1028 vector<tx_destination_entry> destinations;
1029 fill_tx_sources_and_destinations(events, blk_head, from, get_address(to), amount, fee, nmix, sources, destinations);
1030
1031 return construct_tx_rct(from.get_keys(), sources, destinations, from.get_keys().m_account_address, std::vector<uint8_t>(), tx, rct, range_proof_type, bp_version);
1032 }
1033
1034 bool construct_tx_to_key(const std::vector<test_event_entry>& events, cryptonote::transaction& tx, const cryptonote::block& blk_head,
1035 const cryptonote::account_base& from, std::vector<cryptonote::tx_destination_entry> destinations,
1036 uint64_t fee, size_t nmix, bool rct, rct::RangeProofType range_proof_type, int bp_version)
1037 {
1038 vector<tx_source_entry> sources;
1039 vector<tx_destination_entry> destinations_all;
1040 uint64_t amount = sum_amount(destinations);
1041
1042 if (!fill_tx_sources(sources, events, blk_head, from, amount + fee, nmix))
1043 throw std::runtime_error("couldn't fill transaction sources");
1044
1045 fill_tx_destinations(from, destinations, fee, sources, destinations_all, false);
1046
1047 return construct_tx_rct(from.get_keys(), sources, destinations_all, get_address(from), std::vector<uint8_t>(), tx, rct, range_proof_type, bp_version);
1048 }
1049
1050 bool construct_tx_to_key(cryptonote::transaction& tx,
1051 const cryptonote::account_base& from, const var_addr_t& to, uint64_t amount,
1052 std::vector<cryptonote::tx_source_entry> &sources,
1053 uint64_t fee, bool rct, rct::RangeProofType range_proof_type, int bp_version)
1054 {
1055 vector<tx_destination_entry> destinations;
1056 fill_tx_destinations(from, get_address(to), amount, fee, sources, destinations, rct);
1057 return construct_tx_rct(from.get_keys(), sources, destinations, get_address(from), std::vector<uint8_t>(), tx, rct, range_proof_type, bp_version);
1058 }
1059
1060 bool construct_tx_to_key(cryptonote::transaction& tx,
1061 const cryptonote::account_base& from,
1062 const std::vector<cryptonote::tx_destination_entry>& destinations,
1063 std::vector<cryptonote::tx_source_entry> &sources,
1064 uint64_t fee, bool rct, rct::RangeProofType range_proof_type, int bp_version)
1065 {
1066 vector<tx_destination_entry> all_destinations;
1067 fill_tx_destinations(from, destinations, fee, sources, all_destinations, rct);
1068 return construct_tx_rct(from.get_keys(), sources, all_destinations, get_address(from), std::vector<uint8_t>(), tx, rct, range_proof_type, bp_version);
1069 }
1070
1071 bool construct_tx_rct(const cryptonote::account_keys& sender_account_keys, std::vector<cryptonote::tx_source_entry>& sources, const std::vector<cryptonote::tx_destination_entry>& destinations, const boost::optional<cryptonote::account_public_address>& change_addr, std::vector<uint8_t> extra, cryptonote::transaction& tx, bool rct, rct::RangeProofType range_proof_type, int bp_version)
1072 {
1073 std::unordered_map<crypto::public_key, cryptonote::subaddress_index> subaddresses;
1074 subaddresses[sender_account_keys.m_account_address.m_spend_public_key] = {0, 0};
1075 crypto::secret_key tx_key;
1076 std::vector<crypto::secret_key> additional_tx_keys;
1077 std::vector<tx_destination_entry> destinations_copy = destinations;
1078 rct::RCTConfig rct_config = {range_proof_type, bp_version};
1079 return construct_tx_and_get_tx_key(sender_account_keys, subaddresses, sources, destinations_copy, change_addr, extra, tx, tx_key, additional_tx_keys, rct, rct_config);
1080 }
1081
1082 transaction construct_tx_with_fee(std::vector<test_event_entry>& events, const block& blk_head,
1083 const account_base& acc_from, const var_addr_t& to, uint64_t amount, uint64_t fee)
1084 {
1085 transaction tx;
1086 construct_tx_to_key(events, tx, blk_head, acc_from, to, amount, fee, 0);
1087 events.push_back(tx);
1088 return tx;
1089 }
1090
1091 uint64_t get_balance(const cryptonote::account_base& addr, const std::vector<cryptonote::block>& blockchain, const map_hash2tx_t& mtx) {
1092 uint64_t res = 0;
1093 std::map<uint64_t, std::vector<output_index> > outs;
1094 std::map<uint64_t, std::vector<size_t> > outs_mine;
1095
1096 map_hash2tx_t confirmed_txs;
1097 get_confirmed_txs(blockchain, mtx, confirmed_txs);
1098
1099 if (!init_output_indices(outs, outs_mine, blockchain, confirmed_txs, addr))
1100 return false;
1101
1102 if (!init_spent_output_indices(outs, outs_mine, blockchain, confirmed_txs, addr))
1103 return false;
1104
1105 BOOST_FOREACH (const map_output_t::value_type &o, outs_mine) {
1106 for (size_t i = 0; i < o.second.size(); ++i) {
1107 if (outs[o.first][o.second[i]].spent)
1108 continue;
1109
1110 res += outs[o.first][o.second[i]].amount;
1111 }
1112 }
1113
1114 return res;
1115 }
1116
1117 bool extract_hard_forks(const std::vector<test_event_entry>& events, v_hardforks_t& hard_forks)
1118 {
1119 for(auto & ev : events)
1120 {
1121 if (typeid(event_replay_settings) == ev.type())
1122 {
1123 const auto & rep_settings = boost::get<event_replay_settings>(ev);
1124 if (rep_settings.hard_forks)
1125 {
1126 const auto & hf = rep_settings.hard_forks.get();
1127 std::copy(hf.begin(), hf.end(), std::back_inserter(hard_forks));
1128 }
1129 }
1130 }
1131
1132 return !hard_forks.empty();
1133 }
1134
1135 bool extract_hard_forks_from_blocks(const std::vector<test_event_entry>& events, v_hardforks_t& hard_forks)
1136 {
1137 int hf = -1;
1138 int64_t height = 0;
1139
1140 for(auto & ev : events)
1141 {
1142 if (typeid(block) != ev.type())
1143 {
1144 continue;
1145 }
1146
1147 const block *blk = &boost::get<block>(ev);
1148 if (blk->major_version != hf)
1149 {
1150 hf = blk->major_version;
1151 hard_forks.push_back(std::make_pair(blk->major_version, (uint64_t)height));
1152 }
1153
1154 height += 1;
1155 }
1156
1157 return !hard_forks.empty();
1158 }
1159
1160 void get_confirmed_txs(const std::vector<cryptonote::block>& blockchain, const map_hash2tx_t& mtx, map_hash2tx_t& confirmed_txs)
1161 {
1162 std::unordered_set<crypto::hash> confirmed_hashes;
1163 BOOST_FOREACH(const block& blk, blockchain)
1164 {
1165 BOOST_FOREACH(const crypto::hash& tx_hash, blk.tx_hashes)
1166 {
1167 confirmed_hashes.insert(tx_hash);
1168 }
1169 }
1170
1171 BOOST_FOREACH(const auto& tx_pair, mtx)
1172 {
1173 if (0 != confirmed_hashes.count(tx_pair.first))
1174 {
1175 confirmed_txs.insert(tx_pair);
1176 }
1177 }
1178 }
1179
1180 bool trim_block_chain(std::vector<cryptonote::block>& blockchain, const crypto::hash& tail){
1181 size_t cut = 0;
1182 bool found = true;
1183
1184 for(size_t i = 0; i < blockchain.size(); ++i){
1185 crypto::hash chash = get_block_hash(blockchain[i]);
1186 if (chash == tail){
1187 cut = i;
1188 found = true;
1189 break;
1190 }
1191 }
1192
1193 if (found && cut > 0){
1194 blockchain.erase(blockchain.begin(), blockchain.begin() + cut);
1195 }
1196
1197 return found;
1198 }
1199
1200 bool trim_block_chain(std::vector<const cryptonote::block*>& blockchain, const crypto::hash& tail){
1201 size_t cut = 0;
1202 bool found = true;
1203
1204 for(size_t i = 0; i < blockchain.size(); ++i){
1205 crypto::hash chash = get_block_hash(*blockchain[i]);
1206 if (chash == tail){
1207 cut = i;
1208 found = true;
1209 break;
1210 }
1211 }
1212
1213 if (found && cut > 0){
1214 blockchain.erase(blockchain.begin(), blockchain.begin() + cut);
1215 }
1216
1217 return found;
1218 }
1219
1220 uint64_t num_blocks(const std::vector<test_event_entry>& events)
1221 {
1222 uint64_t res = 0;
1223 BOOST_FOREACH(const test_event_entry& ev, events)
1224 {
1225 if (typeid(block) == ev.type())
1226 {
1227 res += 1;
1228 }
1229 }
1230
1231 return res;
1232 }
1233
1234 cryptonote::block get_head_block(const std::vector<test_event_entry>& events)
1235 {
1236 for(auto it = events.rbegin(); it != events.rend(); ++it)
1237 {
1238 auto &ev = *it;
1239 if (typeid(block) == ev.type())
1240 {
1241 return boost::get<block>(ev);
1242 }
1243 }
1244
1245 throw std::runtime_error("No block event");
1246 }
1247
1248 bool find_block_chain(const std::vector<test_event_entry>& events, std::vector<cryptonote::block>& blockchain, map_hash2tx_t& mtx, const crypto::hash& head) {
1249 std::unordered_map<crypto::hash, const block*> block_index;
1250 BOOST_FOREACH(const test_event_entry& ev, events)
1251 {
1252 if (typeid(block) == ev.type())
1253 {
1254 const block* blk = &boost::get<block>(ev);
1255 block_index[get_block_hash(*blk)] = blk;
1256 }
1257 else if (typeid(transaction) == ev.type())
1258 {
1259 const transaction& tx = boost::get<transaction>(ev);
1260 mtx[get_transaction_hash(tx)] = &tx;
1261 }
1262 }
1263
1264 bool b_success = false;
1265 crypto::hash id = head;
1266 for (auto it = block_index.find(id); block_index.end() != it; it = block_index.find(id))
1267 {
1268 blockchain.push_back(*it->second);
1269 id = it->second->prev_id;
1270 if (null_hash == id)
1271 {
1272 b_success = true;
1273 break;
1274 }
1275 }
1276 reverse(blockchain.begin(), blockchain.end());
1277
1278 return b_success;
1279 }
1280
1281 bool find_block_chain(const std::vector<test_event_entry>& events, std::vector<const cryptonote::block*>& blockchain, map_hash2tx_t& mtx, const crypto::hash& head) {
1282 std::unordered_map<crypto::hash, const block*> block_index;
1283 BOOST_FOREACH(const test_event_entry& ev, events)
1284 {
1285 if (typeid(block) == ev.type())
1286 {
1287 const block* blk = &boost::get<block>(ev);
1288 block_index[get_block_hash(*blk)] = blk;
1289 }
1290 else if (typeid(transaction) == ev.type())
1291 {
1292 const transaction& tx = boost::get<transaction>(ev);
1293 mtx[get_transaction_hash(tx)] = &tx;
1294 }
1295 }
1296
1297 bool b_success = false;
1298 crypto::hash id = head;
1299 for (auto it = block_index.find(id); block_index.end() != it; it = block_index.find(id))
1300 {
1301 blockchain.push_back(it->second);
1302 id = it->second->prev_id;
1303 if (null_hash == id)
1304 {
1305 b_success = true;
1306 break;
1307 }
1308 }
1309 reverse(blockchain.begin(), blockchain.end());
1310 return b_success;
1311 }
1312
1313
1314 void test_chain_unit_base::register_callback(const std::string& cb_name, verify_callback cb)
1315 {
1316 m_callbacks[cb_name] = cb;
1317 }
1318 bool test_chain_unit_base::verify(const std::string& cb_name, cryptonote::core& c, size_t ev_index, const std::vector<test_event_entry> &events)
1319 {
1320 auto cb_it = m_callbacks.find(cb_name);
1321 if(cb_it == m_callbacks.end())
1322 {
1323 LOG_ERROR("Failed to find callback " << cb_name);
1324 return false;
1325 }
1326 return cb_it->second(c, ev_index, events);
1327 }
1328
1329 bool test_chain_unit_base::check_block_verification_context(const cryptonote::block_verification_context& bvc, size_t event_idx, const cryptonote::block& /*blk*/)
1330 {
1331 return !bvc.m_verifivation_failed;
1332 }
1333
1334 bool test_chain_unit_base::check_tx_verification_context(const cryptonote::tx_verification_context& tvc, bool /*tx_added*/, size_t /*event_index*/, const cryptonote::transaction& /*tx*/)
1335 {
1336 return !tvc.m_verifivation_failed;
1337 }
1338
1339 bool test_chain_unit_base::check_tx_verification_context_array(const std::vector<cryptonote::tx_verification_context>& tvcs, size_t /*tx_added*/, size_t /*event_index*/, const std::vector<cryptonote::transaction>& /*txs*/)
1340 {
1341 for (const cryptonote::tx_verification_context &tvc: tvcs)
1342 if (tvc.m_verifivation_failed)
1343 return false;
1344 return true;
1345 }