diff options
Diffstat (limited to 'tests')
-rw-r--r-- | tests/CMakeLists.txt | 2 | ||||
-rw-r--r-- | tests/README.md | 6 | ||||
-rw-r--r-- | tests/cryptolib.pl | 261 | ||||
-rw-r--r-- | tests/cryptotest.pl | 58 | ||||
-rw-r--r-- | tests/daemon_tests/CMakeLists.txt | 50 | ||||
-rw-r--r-- | tests/daemon_tests/transfers.cpp | 103 | ||||
-rw-r--r-- | tests/functional_tests/CMakeLists.txt | 4 | ||||
-rwxr-xr-x | tests/functional_tests/transfer.py | 227 | ||||
-rw-r--r-- | tests/performance_tests/main.cpp | 12 | ||||
-rw-r--r-- | tests/performance_tests/performance_tests.h | 99 | ||||
-rw-r--r-- | tests/unit_tests/CMakeLists.txt | 1 | ||||
-rw-r--r-- | tests/unit_tests/crypto.cpp | 24 | ||||
-rw-r--r-- | tests/unit_tests/epee_utils.cpp | 16 | ||||
-rw-r--r-- | tests/unit_tests/variant.cpp | 436 |
14 files changed, 783 insertions, 516 deletions
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f14f7ff5a..39e7ed8a9 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -105,8 +105,6 @@ if (TREZOR_DEBUG) add_subdirectory(trezor) endif() -# add_subdirectory(daemon_tests) - set(hash_targets_sources hash-target.cpp) diff --git a/tests/README.md b/tests/README.md index c63294e9b..0d2180d67 100644 --- a/tests/README.md +++ b/tests/README.md @@ -43,10 +43,6 @@ ctest To run the same tests on a release build, replace `debug` with `release`. -# Daemon tests - -[TODO] - # Functional tests [TODO] @@ -54,7 +50,7 @@ Functional tests are located under the `tests/functional_tests` directory. Building all the tests requires installing the following dependencies: ```bash -pip install requests psutil monotonic zmq +pip install requests psutil monotonic zmq deepdiff ``` First, run a regtest daemon in the offline mode and with a fixed difficulty: diff --git a/tests/cryptolib.pl b/tests/cryptolib.pl deleted file mode 100644 index dce58482d..000000000 --- a/tests/cryptolib.pl +++ /dev/null @@ -1,261 +0,0 @@ -# Copyright (c) 2014-2023, The Monero Project -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, are -# permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this list of -# conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, this list -# of conditions and the following disclaimer in the documentation and/or other -# materials provided with the distribution. -# -# 3. Neither the name of the copyright holder nor the names of its contributors may be -# used to endorse or promote products derived from this software without specific -# prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers - -use Math::BigInt only => 'GMP'; -use Digest::Keccak qw(keccak_256); - -my $p = Math::BigInt->new(2)->bpow(255)->bsub(19); #F_p -my $l = Math::BigInt->new(2)->bpow(252)->badd('27742317777372353535851937790883648493'); -#my $d = Math::BigInt->new(486662); #motgomery: y^2 = x^3 + 486662x^2 + x -my $d = Math::BigInt->new(-121665)->bmul(minv(121666))->bmod($p); #twisted edwards: -x^2 +y^2 = 1 + d*x^2*y^2 -my $x0 = Math::BigInt->new('15112221349535400772501151409588531511454012693041857206046113283949847762202'); -my $y0 = Math::BigInt->new('46316835694926478169428394003475163141307993866256225615783033603165251855960'); #y0 = 4/5 -my $m = Math::BigInt->new('7237005577332262213973186563042994240829374041602535252466099000494570602493'); #p = 8m+5 -my $ps = $p->copy()->bdec->bdiv(4); -my $pl = $p->copy()->bdec->bdiv(2); -my $ii = Math::BigInt->new(2)->bmodpow($ps,$p); #sqrt(-1) - -sub ec_rec { - my $y = Math::BigInt->new($_[0]); - my $xx = $y->copy()->bpow(2)->bdec()->bmul(minv($y->copy()->bpow(2)->bmul($d)->binc))->bmod($p); - return 0 if !($xx->copy()->bmodpow($pl,$p)->binc->bmod($p)); - my $p2 = $p->copy()->badd(3)->bdiv(8); - my $x = $xx->copy()->bmodpow($p2, $p); - if ($x->copy()->bpow(2)->bsub($xx)->bmod($p)) {$x->bmul($ii)->bmod($p)} - if ($x->is_odd) {$x = $p->copy()->bsub($x)}; - return $x; - } - -sub h2i { - return Math::BigInt->new('0x'.(unpack 'H*', (reverse pack 'H*', shift)));; - } - -sub i2h { - my $t = substr(Math::BigInt->new(shift)->as_hex(),2,64); - if (length($t)%2 == 1) {$t = '0'.$t} - return unpack 'H*', (reverse pack 'H*', $t); - } - - -sub random { - return keccak_256(rand(2**20)); - #return keccak_256(3); #I swear that's random! - } - -sub ec_pack { - my $x = Math::BigInt->new($_[0]); - my $y = Math::BigInt->new($_[1]); - my $or = Math::BigInt->new(2)->bpow(255); - $y |= $or if ($x->is_odd()); - return unpack 'H*', (reverse pack 'H*', substr($y->as_hex(),2,64)); - } - -sub ec_unpack { - my $y = Math::BigInt->new(h2i(shift)); - my $b = $y >> 255; - my $and = Math::BigInt->new(2)->bpow(255)->bdec(); - $y &= $and; - my $x = ec_rec($y); - return (0,0) if $x==0; - ($b==0) || ($x = $p->copy()->bsub($x)); - return ($x,$y); - } - - -sub minv { - my $x = Math::BigInt->new(shift); - $x->bmodpow($p-2,$p); - return $x; - } - - -sub ec_doub { - my $x = Math::BigInt->new($_[0]); - my $y = Math::BigInt->new($_[1]); - - #$t = $x->copy()->bpow(2)->bmul(3)->badd($x->copy()->bmul($d)->bmul(2))->binc()->bmul(minv($y->copy()->bmul(2))); #montgomery - #$x2 = $t->copy()->bpow(2)->bsub($d)->bsub($x)->bsub($x)->bmod($p); #montgomery - #$y2 = $x->copy()->bmul(2)->badd($x)->badd($d)->bmul($t)->bsub($t->copy()->bpow(3))->bsub($y)->bmod($p); #montgomery - $t = $x->copy()->bmul($x)->bmul($y)->bmul($y)->bmul($d)->bmod($p); - $x3 = $x->copy()->bmul($y)->bmul(2)->bmul(minv($t+1))->bmod($p); - $y3 = $y->copy()->bpow(2)->badd($x->copy()->bpow(2))->bmul(minv(1-$t))->bmod($p); - return ($x3,$y3); - } -sub ec_add { - my $x1 = Math::BigInt->new($_[0]); - my $y1 = Math::BigInt->new($_[1]); - my $x2 = Math::BigInt->new($_[2]); - my $y2 = Math::BigInt->new($_[3]); - - #$t = $y2->copy()->bsub($y1)->bmul(minv($x2->copy()->bsub($x1))); - #$x3 = $t->copy()->bpow(2)->bsub($d)->bsub($x1)->bsub($x2)->bmod($p); - #$y3 = $x1->copy()->bmul(2)->badd($x2)->badd($d)->bmul($t)->bsub($t->copy()->bpow(3))->bsub($y1)->bmod($p); - $t = $x1->copy->bmul($x2)->bmul($y1)->bmul($y2)->bmul($d)->bmod($p); - $x3 = $x1->copy()->bmul($y2)->badd($y1->copy()->bmul($x2))->bmul(minv($t+1))->bmod($p); - $y3 = $y1->copy()->bmul($y2)->badd($x1->copy()->bmul($x2))->bmul(minv(1-$t))->bmod($p); - - - return ($x3,$y3); - } - -sub ec_mul { - my $n = Math::BigInt->new($_[0]); - my $x = Math::BigInt->new($_[1]); - my $y = Math::BigInt->new($_[2]); - - if ($n->is_one()) { - return ($x,$y); - last; - } - elsif ($n->is_even()) { - $n->bdiv(2); - return ec_mul($n,&ec_doub($x,$y)); - } - else { - $n->bdec()->bdiv(2); - return ec_add($x,$y,ec_mul($n,&ec_doub($x,$y))); - } - } - -sub pkeygen { - my $key = Math::BigInt->new(h2i(shift))->bmod($l); - return ec_pack(ec_mul($key,$x0,$y0)); - } - -sub ec_hash { - my $h = pack 'H*', shift; - my $h = Math::BigInt->new('0x'.(unpack 'H*', reverse keccak_256($h))); - my ($x,$y) = (0,0); - while ($x == 0) { - ($x,$y) = ec_unpack(i2h($h)); - $h->binc(); - } - return ec_mul(8,$x,$y); - } - -sub im_gen { - my ($x,$y) = ec_hash(shift); - my $k = Math::BigInt->new(h2i(shift))->bmod($l); - return ec_pack(ec_mul($k,$x,$y)); - } - - -sub sign { - my ($m,$sec_key) = @_; - my $sec_key = Math::BigInt->new(h2i($sec_key)); - my ($x,$y) = ec_mul($sec_key,$x0,$y0); - my $k = Math::BigInt->new('0x'.(unpack 'H*', random()))->bmod($l); - #my $k = Math::BigInt->new('5267557024171956683337957876581522196748200715787296882078421399301151717969'); - my $e = unpack 'H*', keccak_256($m.(pack 'H*', ec_pack(ec_mul($k,$x0,$y0)))); - my $s = i2h(Math::BigInt->new(h2i($e))->bmul($sec_key)->bneg()->badd($k)->bmod($l)); - $e = i2h(Math::BigInt->new(h2i($e))->bmod($l)); - return ($s,$e); - } - -sub check_s { - my ($m,$pt,$s1,$e1) = @_; - my ($x,$y) = ec_unpack($pt); - my $s = Math::BigInt->new(h2i($s1))->bmod($l); - my $e = Math::BigInt->new(h2i($e1))->bmod($l); - my ($x1,$y1) = ec_add(ec_mul($s,$x0,$y0),ec_mul($e,$x,$y)); - $m = $m.(pack 'H*', ec_pack($x1,$y1)); - my $ev = Math::BigInt->new(h2i(unpack 'H*', keccak_256($m)))->bmod($l); - - return !$ev->bcmp($e); - } - -sub r_sign { - my ($m,$image,$sec_key,$index,@pkeys) = @_; - my ($ix,$iy) = ec_unpack($image); - my $n = @pkeys; - my $data = $m; - my $w = $a = $b = $hx = $hy = $px = $py = 0; - my @zc = (); - my $sum = Math::BigInt->new(); - #print "begin signing ($n keys)\n"; - for $i (0..$n-1) { - ($hx, $hy) = ec_hash(@pkeys[$i]); - ($px,$py) = ec_unpack(@pkeys[$i]); - if ($i == $index) { - $w = Math::BigInt->new('0x'.(unpack 'H*', random()))->bmod($l); - $a = pack 'H*', ec_pack(ec_mul($w,$x0,$y0)); - $b = pack 'H*', ec_pack(ec_mul($w,$hx,$hy)); - push @zc,0,0; - } - else { - $z = Math::BigInt->new('0x'.(unpack 'H*', random()))->bmod($l); - $c = Math::BigInt->new('0x'.(unpack 'H*', random()))->bmod($l); - $sum->badd($c); - $a = pack 'H*', ec_pack(ec_add(ec_mul($z,$x0,$y0),ec_mul($c,$px,$py))); - $b = pack 'H*', ec_pack(ec_add(ec_mul($z,$hx,$hy),ec_mul($c,$ix,$iy))); - push @zc,i2h($z),i2h($c); - } - $data = $data.$a.$b; - #print "key number $i done\n"; - } - #print "generating ringsig..\n"; - my $h = unpack 'H*', keccak_256($data); - my $cy = Math::BigInt->new(h2i($h))->bsub($sum)->bmod($l); - my $zy = $cy->copy()->bmul(h2i($sec_key))->bneg()->badd($w)->bmod($l); - @zc[2*$index] = i2h($zy); - @zc[2*$index+1] = i2h($cy); - return @zc; - } - -sub r_check_s { - my ($m,$image,@zc) = @_; - my $n = @zc/3; - for $j (0..$n-1) { - @pkeys[$j] = shift @zc; - } - my $data = $m; - my ($ix,$iy) = ec_unpack($image); - my $a = $b = $hx = $hy = $px = $py = $z = $c = 0; - my $sum = Math::BigInt->new(); - #print "\nBegin checking ($n keys)\n"; - for $i (0..$n-1) { - $z = Math::BigInt->new(h2i(shift @zc))->bmod($l); - $c = Math::BigInt->new(h2i(shift @zc))->bmod($l); - $sum->badd($c)->bmod($l); - ($px,$py) = ec_unpack(@pkeys[$i]); - $a = pack 'H*', ec_pack(ec_add(ec_mul($z,$x0,$y0),ec_mul($c,$px,$py))); - ($hx, $hy) = ec_hash(@pkeys[$i]); - $b = pack 'H*', ec_pack(ec_add(ec_mul($z,$hx,$hy),ec_mul($c,$ix,$iy))); - $data = $data.$a.$b; - #print "key number $i done\n"; - } - my $h = Math::BigInt->new(h2i(unpack 'H*', keccak_256($data)))->bmod($l); - - return !$h->bcmp($sum); - } - - - - diff --git a/tests/cryptotest.pl b/tests/cryptotest.pl deleted file mode 100644 index 67ccc1d79..000000000 --- a/tests/cryptotest.pl +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright (c) 2014-2023, The Monero Project -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, are -# permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this list of -# conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, this list -# of conditions and the following disclaimer in the documentation and/or other -# materials provided with the distribution. -# -# 3. Neither the name of the copyright holder nor the names of its contributors may be -# used to endorse or promote products derived from this software without specific -# prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers - -require 'cryptolib.pl'; - -$key = 'fc7557a2595788aea7205ffd801b8a157dc9c698adb2c598ba543eaa67cb700e'; -$pt = '664422cf6f4100dc6b3298e41ca53b173a98918fc9cb50fc2d590b7d1285f4ab'; -$m = keccak_256(pack 'H*', 'c8fedd380dbae40ffb52'); - - -$s = '26a9589121e569ee0ac2e8ac7a7ea331d348f9a0fa8d28926d27c7506759e406'; -$e = '780be966ad89ba526cc7adf4b771adbdaa0568038e6a30e776839a81e57dee0c'; - -print " self SIG -- OK\n" if check_s($m,$pt,sign($m,$key)); -print " test SIG -- OK\n" if check_s($m,$pt,$s,$e); - -@aa = r_sign($m,im_gen($pt,$key),$key,1,ec_pack(ec_mul(111,$x0,$y0)),$pt,ec_pack(ec_mul(47,$x0,$y0))); -print " self RSIG -- OK\n" if r_check_s($m,im_gen($pt,$key),ec_pack(ec_mul(111,$x0,$y0)),$pt,ec_pack(ec_mul(47,$x0,$y0)),@aa); - -$k1 = '6a7a81a52ba91b9785b484d761bfb3ad9a473c147e17b7fbbc3992e8c97108d7'; -$sk1 = '3ce3eb784016a53fa915053d24f55dc8fbc7af3fabc915701adb67e61a25f50f'; -$k2 = '0f3fe9c20b24a11bf4d6d1acd335c6a80543f1f0380590d7323caf1390c78e88'; -$sk2 = '4967a2bfa0c8a0afc0df238d068b6c7182577afd0781c9d3720bb7a6cf71630c'; #main key -$m = keccak_256(pack 'H*', '5020c4d530b6ec6cb4d9'); -@sig = ('b7903a4a3aca7253bb98be335014bebb33683aedca0bc46e288e229ecfccbe0e', - '2c15e4de88ff38d655e2deef0e06a7ca4541a7754c37e7b20875cce791754508', - '6acae497177b2eeaf658b813eaf50e1e06f3d1107694beff9b520c65ee624f05', - '026c8d9801f7330aa82426adf5bacf4546d83df0cc12321ede90df8c0d9aa800'); - - -print " test RSIG -- OK" if r_check_s($m,im_gen($k2,$sk2),$k1, $k2, @sig); diff --git a/tests/daemon_tests/CMakeLists.txt b/tests/daemon_tests/CMakeLists.txt deleted file mode 100644 index 182231132..000000000 --- a/tests/daemon_tests/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright (c) 2014-2023, The Monero Project -# -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without modification, are -# permitted provided that the following conditions are met: -# -# 1. Redistributions of source code must retain the above copyright notice, this list of -# conditions and the following disclaimer. -# -# 2. Redistributions in binary form must reproduce the above copyright notice, this list -# of conditions and the following disclaimer in the documentation and/or other -# materials provided with the distribution. -# -# 3. Neither the name of the copyright holder nor the names of its contributors may be -# used to endorse or promote products derived from this software without specific -# prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -set(transfers_sources - transfers.cpp) - -set(transfers_headers) - -monero_add_minimal_executable(transfers - ${transfers_sources} - ${transfers_headers}) -target_link_libraries(transfers - PRIVATE - useragent - rpc - cryptonote_core - cncrypto - common - epee - ${GTEST_LIBRARIES}) - -file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_transfers") -add_custom_target(test_transfers - COMMAND transfers - WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/test_transfers") diff --git a/tests/daemon_tests/transfers.cpp b/tests/daemon_tests/transfers.cpp deleted file mode 100644 index 2980c93ed..000000000 --- a/tests/daemon_tests/transfers.cpp +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) 2014-2023, The Monero Project -// -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without modification, are -// permitted provided that the following conditions are met: -// -// 1. Redistributions of source code must retain the above copyright notice, this list of -// conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright notice, this list -// of conditions and the following disclaimer in the documentation and/or other -// materials provided with the distribution. -// -// 3. Neither the name of the copyright holder nor the names of its contributors may be -// used to endorse or promote products derived from this software without specific -// prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers - -#include "gtest/gtest.h" -#include <sstream> -#include "wallet/wallet.h" -#include "rpc/core_rpc_server.h" -#include "cryptonote_basic/account.h" -#include "net/http_client_abstract_invoke.h" -using namespace std; -using namespace epee::misc_utils; -using namespace cryptonote; - -string daemon_address = "http://localhost:23400"; - -#define ACCS 5 - -TEST(Transfers, Transfers) -{ - log_space::get_set_log_detalisation_level(true, LOG_LEVEL_3); - log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL); - - cout << "TESTING: transfers" << endl; - - net_utils::http::http_simple_client http_client; - wallet miner, accs[100], receiver; - miner.generate(); - ASSERT_TRUE(miner.init()); - ASSERT_TRUE(miner.store("miner.b2wallet")); - cout << "miner: " << miner.get_account().get_public_address_str(false) << endl; - - for (int i = 0; i < ACCS; i++) { - ostringstream s; - s << "acc" << setw(2) << setfill('0') << i << ".b2wallet"; - accs[i].generate(); - assert(accs[i].init()); - assert(accs[i].store(s.str())); - } - receiver.generate(); - assert(receiver.init()); - receiver.store("receiver.b2wallet"); - - { - COMMAND_RPC_START_MINE::request req; - req.miner_address = miner.get_account().get_public_address_str(false); - req.threads_count = 1; - COMMAND_RPC_START_MINE::response res; - bool r = net_utils::http::invoke_http_json_remote_command(daemon_address + "/start_mine", req, res, http_client); - ASSERT_TRUE(r); - } - - string s; - //getline(cin, s); - sleep_no_w(1000); - ASSERT_TRUE(miner.refresh()); - cout << "miner balance: " << miner.balance() << endl; - - vector<pair<account_public_address, uint64_t>> d_accs; - for (int i = 0; i < ACCS; i++) - d_accs.push_back(make_pair(accs[i].get_account().get_keys().m_account_address, 1)); - ASSERT_TRUE(miner.transfer(d_accs)); - - //getline(cin, s); - sleep_no_w(1000); - for (int i = 0; i < ACCS; i++) { - ASSERT_TRUE(accs[i].refresh()); - ASSERT_TRUE(accs[i].transfer(receiver.get_account().get_keys().m_account_address, 1)); - } - - //getline(cin, s); - cout << "wait for block" << endl; - sleep_no_w(10000); - receiver.refresh(); - ASSERT_TRUE(receiver.balance() == ACCS); - cout << "OK" << endl; -} diff --git a/tests/functional_tests/CMakeLists.txt b/tests/functional_tests/CMakeLists.txt index 0daf71b59..306eba073 100644 --- a/tests/functional_tests/CMakeLists.txt +++ b/tests/functional_tests/CMakeLists.txt @@ -67,7 +67,7 @@ target_link_libraries(make_test_signature monero_add_minimal_executable(cpu_power_test cpu_power_test.cpp) find_program(PYTHON3_FOUND python3 REQUIRED) -execute_process(COMMAND ${PYTHON3_FOUND} "-c" "import requests; import psutil; import monotonic; import zmq; print('OK')" OUTPUT_VARIABLE REQUESTS_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE) +execute_process(COMMAND ${PYTHON3_FOUND} "-c" "import requests; import psutil; import monotonic; import zmq; import deepdiff; print('OK')" OUTPUT_VARIABLE REQUESTS_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE) if (REQUESTS_OUTPUT STREQUAL "OK") add_test( NAME functional_tests_rpc @@ -76,6 +76,6 @@ if (REQUESTS_OUTPUT STREQUAL "OK") NAME check_missing_rpc_methods COMMAND ${PYTHON3_FOUND} "${CMAKE_CURRENT_SOURCE_DIR}/check_missing_rpc_methods.py" "${CMAKE_SOURCE_DIR}") else() - message(WARNING "functional_tests_rpc and check_missing_rpc_methods skipped, needs the 'requests', 'psutil', 'monotonic', and 'zmq' python modules") + message(WARNING "functional_tests_rpc and check_missing_rpc_methods skipped, needs the 'requests', 'psutil', 'monotonic', 'zmq', and 'deepdiff' python modules") set(CTEST_CUSTOM_TESTS_IGNORE ${CTEST_CUSTOM_TESTS_IGNORE} functional_tests_rpc check_missing_rpc_methods) endif() diff --git a/tests/functional_tests/transfer.py b/tests/functional_tests/transfer.py index bd80f8f3c..ddc930eb0 100755 --- a/tests/functional_tests/transfer.py +++ b/tests/functional_tests/transfer.py @@ -30,6 +30,9 @@ from __future__ import print_function import json +import pprint +from deepdiff import DeepDiff +pp = pprint.PrettyPrinter(indent=2) """Test simple transfers """ @@ -37,6 +40,12 @@ import json from framework.daemon import Daemon from framework.wallet import Wallet +seeds = [ + 'velvet lymph giddy number token physics poetry unquoted nibs useful sabotage limits benches lifestyle eden nitrogen anvil fewest avoid batch vials washing fences goat unquoted', + 'peeled mixture ionic radar utopia puddle buying illness nuns gadget river spout cavernous bounced paradise drunk looking cottage jump tequila melting went winter adjust spout', + 'dilute gutter certain antics pamphlet macro enjoy left slid guarded bogeys upload nineteen bomb jubilee enhanced irritate turnip eggs swung jukebox loudly reduce sedan slid', +] + class TransferTest(): def run_test(self): self.reset() @@ -53,6 +62,7 @@ class TransferTest(): self.check_rescan() self.check_is_key_image_spent() self.check_multiple_submissions() + self.check_scan_tx() def reset(self): print('Resetting blockchain') @@ -63,11 +73,6 @@ class TransferTest(): def create(self): print('Creating wallets') - seeds = [ - 'velvet lymph giddy number token physics poetry unquoted nibs useful sabotage limits benches lifestyle eden nitrogen anvil fewest avoid batch vials washing fences goat unquoted', - 'peeled mixture ionic radar utopia puddle buying illness nuns gadget river spout cavernous bounced paradise drunk looking cottage jump tequila melting went winter adjust spout', - 'dilute gutter certain antics pamphlet macro enjoy left slid guarded bogeys upload nineteen bomb jubilee enhanced irritate turnip eggs swung jukebox loudly reduce sedan slid', - ] self.wallet = [None] * len(seeds) for i in range(len(seeds)): self.wallet[i] = Wallet(idx = i) @@ -864,5 +869,217 @@ class TransferTest(): res = self.wallet[0].get_balance() assert res.balance == balance + def check_scan_tx(self): + daemon = Daemon() + + print('Testing scan_tx') + + def diff_transfers(actual_transfers, expected_transfers): + diff = DeepDiff(actual_transfers, expected_transfers) + if diff != {}: + pp.pprint(diff) + assert diff == {} + + # set up sender_wallet + sender_wallet = self.wallet[0] + try: sender_wallet.close_wallet() + except: pass + sender_wallet.restore_deterministic_wallet(seed = seeds[0]) + sender_wallet.auto_refresh(enable = False) + sender_wallet.refresh() + res = sender_wallet.get_transfers() + out_len = 0 if 'out' not in res else len(res.out) + sender_starting_balance = sender_wallet.get_balance().balance + amount = 1000000000000 + assert sender_starting_balance > amount + + # set up receiver_wallet + receiver_wallet = self.wallet[1] + try: receiver_wallet.close_wallet() + except: pass + receiver_wallet.restore_deterministic_wallet(seed = seeds[1]) + receiver_wallet.auto_refresh(enable = False) + receiver_wallet.refresh() + res = receiver_wallet.get_transfers() + in_len = 0 if 'in' not in res else len(res['in']) + receiver_starting_balance = receiver_wallet.get_balance().balance + + # transfer from sender_wallet to receiver_wallet + dst = {'address': '44Kbx4sJ7JDRDV5aAhLJzQCjDz2ViLRduE3ijDZu3osWKBjMGkV1XPk4pfDUMqt1Aiezvephdqm6YD19GKFD9ZcXVUTp6BW', 'amount': amount} + res = sender_wallet.transfer([dst]) + assert len(res.tx_hash) == 32*2 + txid = res.tx_hash + assert res.amount == amount + assert res.fee > 0 + fee = res.fee + + expected_sender_balance = sender_starting_balance - (amount + fee) + expected_receiver_balance = receiver_starting_balance + amount + + test = 'Checking scan_tx on outgoing pool tx' + for attempt in range(2): # test re-scanning + print(test + ' (' + ('first attempt' if attempt == 0 else 're-scanning tx') + ')') + sender_wallet.scan_tx([txid]) + res = sender_wallet.get_transfers() + assert 'pool' not in res or len(res.pool) == 0 + if out_len == 0: + assert 'out' not in res + else: + assert len(res.out) == out_len + assert len(res.pending) == 1 + tx = [x for x in res.pending if x.txid == txid] + assert len(tx) == 1 + tx = tx[0] + assert tx.amount == amount + assert tx.fee == fee + assert len(tx.destinations) == 1 + assert tx.destinations[0].amount == amount + assert tx.destinations[0].address == dst['address'] + assert sender_wallet.get_balance().balance == expected_sender_balance + + test = 'Checking scan_tx on incoming pool tx' + for attempt in range(2): # test re-scanning + print(test + ' (' + ('first attempt' if attempt == 0 else 're-scanning tx') + ')') + receiver_wallet.scan_tx([txid]) + res = receiver_wallet.get_transfers() + assert 'pending' not in res or len(res.pending) == 0 + if in_len == 0: + assert 'in' not in res + else: + assert len(res['in']) == in_len + assert 'pool' in res and len(res.pool) == 1 + tx = [x for x in res.pool if x.txid == txid] + assert len(tx) == 1 + tx = tx[0] + assert tx.amount == amount + assert tx.fee == fee + assert receiver_wallet.get_balance().balance == expected_receiver_balance + + # mine the tx + height = daemon.generateblocks(dst['address'], 1).height + block_header = daemon.getblockheaderbyheight(height = height).block_header + miner_txid = block_header.miner_tx_hash + expected_receiver_balance += block_header.reward + + print('Checking scan_tx on outgoing tx before refresh') + sender_wallet.scan_tx([txid]) + res = sender_wallet.get_transfers() + assert 'pending' not in res or len(res.pending) == 0 + assert 'pool' not in res or len (res.pool) == 0 + assert len(res.out) == out_len + 1 + tx = [x for x in res.out if x.txid == txid] + assert len(tx) == 1 + tx = tx[0] + assert tx.amount == amount + assert tx.fee == fee + assert len(tx.destinations) == 1 + assert tx.destinations[0].amount == amount + assert tx.destinations[0].address == dst['address'] + assert sender_wallet.get_balance().balance == expected_sender_balance + + print('Checking scan_tx on outgoing tx after refresh') + sender_wallet.refresh() + sender_wallet.scan_tx([txid]) + diff_transfers(sender_wallet.get_transfers(), res) + assert sender_wallet.get_balance().balance == expected_sender_balance + + print("Checking scan_tx on outgoing wallet's earliest tx") + earliest_height = height + earliest_txid = txid + for x in res['in']: + if x.height < earliest_height: + earliest_height = x.height + earliest_txid = x.txid + sender_wallet.scan_tx([earliest_txid]) + diff_transfers(sender_wallet.get_transfers(), res) + assert sender_wallet.get_balance().balance == expected_sender_balance + + test = 'Checking scan_tx on outgoing wallet restored at current height' + for i, out_tx in enumerate(res.out): + if 'destinations' in out_tx: + del res.out[i]['destinations'] # destinations are not expected after wallet restore + out_txids = [x.txid for x in res.out] + in_txids = [x.txid for x in res['in']] + all_txs = out_txids + in_txids + for test_type in ["all txs", "incoming first", "duplicates within", "duplicates across"]: + print(test + ' (' + test_type + ')') + sender_wallet.close_wallet() + sender_wallet.restore_deterministic_wallet(seed = seeds[0], restore_height = height) + assert sender_wallet.get_transfers() == {} + if test_type == "all txs": + sender_wallet.scan_tx(all_txs) + elif test_type == "incoming first": + sender_wallet.scan_tx(in_txids) + sender_wallet.scan_tx(out_txids) + # TODO: test_type == "outgoing first" + elif test_type == "duplicates within": + sender_wallet.scan_tx(all_txs + all_txs) + elif test_type == "duplicates across": + sender_wallet.scan_tx(all_txs) + sender_wallet.scan_tx(all_txs) + else: + assert True == False + diff_transfers(sender_wallet.get_transfers(), res) + assert sender_wallet.get_balance().balance == expected_sender_balance + + print('Sanity check against outgoing wallet restored at height 0') + sender_wallet.close_wallet() + sender_wallet.restore_deterministic_wallet(seed = seeds[0], restore_height = 0) + sender_wallet.refresh() + diff_transfers(sender_wallet.get_transfers(), res) + assert sender_wallet.get_balance().balance == expected_sender_balance + + print('Checking scan_tx on incoming txs before refresh') + receiver_wallet.scan_tx([txid, miner_txid]) + res = receiver_wallet.get_transfers() + assert 'pending' not in res or len(res.pending) == 0 + assert 'pool' not in res or len (res.pool) == 0 + assert len(res['in']) == in_len + 2 + tx = [x for x in res['in'] if x.txid == txid] + assert len(tx) == 1 + tx = tx[0] + assert tx.amount == amount + assert tx.fee == fee + assert receiver_wallet.get_balance().balance == expected_receiver_balance + + print('Checking scan_tx on incoming txs after refresh') + receiver_wallet.refresh() + receiver_wallet.scan_tx([txid, miner_txid]) + diff_transfers(receiver_wallet.get_transfers(), res) + assert receiver_wallet.get_balance().balance == expected_receiver_balance + + print("Checking scan_tx on incoming wallet's earliest tx") + earliest_height = height + earliest_txid = txid + for x in res['in']: + if x.height < earliest_height: + earliest_height = x.height + earliest_txid = x.txid + receiver_wallet.scan_tx([earliest_txid]) + diff_transfers(receiver_wallet.get_transfers(), res) + assert receiver_wallet.get_balance().balance == expected_receiver_balance + + print('Checking scan_tx on incoming wallet restored at current height') + txids = [x.txid for x in res['in']] + if 'out' in res: + txids = txids + [x.txid for x in res.out] + receiver_wallet.close_wallet() + receiver_wallet.restore_deterministic_wallet(seed = seeds[1], restore_height = height) + assert receiver_wallet.get_transfers() == {} + receiver_wallet.scan_tx(txids) + if 'out' in res: + for i, out_tx in enumerate(res.out): + if 'destinations' in out_tx: + del res.out[i]['destinations'] # destinations are not expected after wallet restore + diff_transfers(receiver_wallet.get_transfers(), res) + assert receiver_wallet.get_balance().balance == expected_receiver_balance + + print('Sanity check against incoming wallet restored at height 0') + receiver_wallet.close_wallet() + receiver_wallet.restore_deterministic_wallet(seed = seeds[1], restore_height = 0) + receiver_wallet.refresh() + diff_transfers(receiver_wallet.get_transfers(), res) + assert receiver_wallet.get_balance().balance == expected_receiver_balance + if __name__ == '__main__': TransferTest().run_test() diff --git a/tests/performance_tests/main.cpp b/tests/performance_tests/main.cpp index 92bcedcba..9cae5df1f 100644 --- a/tests/performance_tests/main.cpp +++ b/tests/performance_tests/main.cpp @@ -101,12 +101,14 @@ int main(int argc, char** argv) const std::string filter = tools::glob_to_regex(command_line::get_arg(vm, arg_filter)); const std::string timings_database = command_line::get_arg(vm, arg_timings_database); - Params p; + Params core_params; if (!timings_database.empty()) - p.td = TimingsDatabase(timings_database); - p.verbose = command_line::get_arg(vm, arg_verbose); - p.stats = command_line::get_arg(vm, arg_stats); - p.loop_multiplier = command_line::get_arg(vm, arg_loop_multiplier); + core_params.td = TimingsDatabase(timings_database); + core_params.verbose = command_line::get_arg(vm, arg_verbose); + core_params.stats = command_line::get_arg(vm, arg_stats); + core_params.loop_multiplier = command_line::get_arg(vm, arg_loop_multiplier); + + ParamsShuttle p{core_params}; performance_timer timer; timer.start(); diff --git a/tests/performance_tests/performance_tests.h b/tests/performance_tests/performance_tests.h index 531e9d7fb..0f16ff8fc 100644 --- a/tests/performance_tests/performance_tests.h +++ b/tests/performance_tests/performance_tests.h @@ -31,6 +31,8 @@ #pragma once #include <iostream> +#include <memory> +#include <type_traits> #include <stdint.h> #include <boost/chrono.hpp> @@ -41,7 +43,7 @@ #include "common/perf_timer.h" #include "common/timings.h" -class performance_timer +class performance_timer final { public: typedef boost::chrono::high_resolution_clock clock; @@ -67,7 +69,7 @@ private: clock::time_point m_start; }; -struct Params +struct Params final { TimingsDatabase td; bool verbose; @@ -75,45 +77,79 @@ struct Params unsigned loop_multiplier; }; -template <typename T> -class test_runner +struct ParamsShuttle +{ + Params core_params; + + ParamsShuttle() = default; + + ParamsShuttle(Params ¶ms) : core_params{params} + {} + + virtual ~ParamsShuttle() = default; // virtual for non-final type +}; + +template <typename T, typename ParamsT, + typename std::enable_if<!std::is_same<ParamsT, ParamsShuttle>::value, bool>::type = true> +bool init_test(T &test, ParamsT ¶ms_shuttle) +{ + // assume if the params shuttle isn't the base shuttle type, then the test must take the shuttle as an input on init + if (!test.init(params_shuttle)) + return false; + + return true; +} + +template <typename T, typename ParamsT, + typename std::enable_if<std::is_same<ParamsT, ParamsShuttle>::value, bool>::type = true> +bool init_test(T &test, ParamsT ¶ms_shuttle) +{ + if (!test.init()) + return false; + + return true; +} + +template <typename T, typename ParamsT> +class test_runner final { public: - test_runner(const Params ¶ms) + test_runner(const ParamsT ¶ms_shuttle) : m_elapsed(0) - , m_params(params) - , m_per_call_timers(T::loop_count * params.loop_multiplier, {true}) + , m_params_shuttle(params_shuttle) + , m_core_params(params_shuttle.core_params) + , m_per_call_timers(T::loop_count * params_shuttle.core_params.loop_multiplier, {true}) { } - bool run() + int run() { static_assert(0 < T::loop_count, "T::loop_count must be greater than 0"); T test; - if (!test.init()) - return false; + if (!init_test(test, m_params_shuttle)) + return -1; performance_timer timer; timer.start(); warm_up(); - if (m_params.verbose) + if (m_core_params.verbose) std::cout << "Warm up: " << timer.elapsed_ms() << " ms" << std::endl; timer.start(); - for (size_t i = 0; i < T::loop_count * m_params.loop_multiplier; ++i) + for (size_t i = 0; i < T::loop_count * m_core_params.loop_multiplier; ++i) { - if (m_params.stats) + if (m_core_params.stats) m_per_call_timers[i].resume(); if (!test.test()) - return false; - if (m_params.stats) + return i + 1; + if (m_core_params.stats) m_per_call_timers[i].pause(); } m_elapsed = timer.elapsed_ms(); m_stats.reset(new Stats<tools::PerformanceTimer, uint64_t>(m_per_call_timers)); - return true; + return 0; } int elapsed_time() const { return m_elapsed; } @@ -122,7 +158,7 @@ public: int time_per_call(int scale = 1) const { static_assert(0 < T::loop_count, "T::loop_count must be greater than 0"); - return m_elapsed * scale / (T::loop_count * m_params.loop_multiplier); + return m_elapsed * scale / (T::loop_count * m_core_params.loop_multiplier); } uint64_t get_min() const { return m_stats->get_min(); } @@ -156,20 +192,25 @@ private: private: volatile uint64_t m_warm_up; ///<! This field is intended for preclude compiler optimizations int m_elapsed; - Params m_params; + Params m_core_params; + ParamsT m_params_shuttle; std::vector<tools::PerformanceTimer> m_per_call_timers; std::unique_ptr<Stats<tools::PerformanceTimer, uint64_t>> m_stats; }; -template <typename T> -void run_test(const std::string &filter, Params ¶ms, const char* test_name) +template <typename T, typename ParamsT> +bool run_test(const std::string &filter, ParamsT ¶ms_shuttle, const char* test_name) { + static_assert(std::is_base_of<ParamsShuttle, ParamsT>::value, "Must use a ParamsShuttle."); + Params ¶ms = params_shuttle.core_params; + boost::smatch match; if (!filter.empty() && !boost::regex_match(std::string(test_name), match, boost::regex(filter))) - return; + return true; - test_runner<T> runner(params); - if (runner.run()) + test_runner<T, ParamsT> runner(params_shuttle); + int run_result{runner.run()}; + if (run_result == 0) { if (params.verbose) { @@ -227,16 +268,24 @@ void run_test(const std::string &filter, Params ¶ms, const char* test_name) double pc = fabs(100. * (prev_instance.mean - runner.get_mean()) / prev_instance.mean); cmp = ", " + std::to_string(pc) + "% " + (mean > prev_instance.mean ? "slower" : "faster"); } -cmp += " -- " + std::to_string(prev_instance.mean); + cmp += " -- " + std::to_string(prev_instance.mean); } std::cout << " (min " << mins << " " << unit << ", 90th " << p95s << " " << unit << ", median " << meds << " " << unit << ", std dev " << stddevs << " " << unit << ")" << cmp; } std::cout << std::endl; } + else if (run_result == -1) + { + std::cout << test_name << " - FAILED ON INIT" << std::endl; + return false; + } else { - std::cout << test_name << " - FAILED" << std::endl; + std::cout << test_name << " - FAILED ON TEST LOOP " << run_result << std::endl; + return false; } + + return true; } #define QUOTEME(x) #x diff --git a/tests/unit_tests/CMakeLists.txt b/tests/unit_tests/CMakeLists.txt index d57c9bd7b..cbed5e6de 100644 --- a/tests/unit_tests/CMakeLists.txt +++ b/tests/unit_tests/CMakeLists.txt @@ -90,6 +90,7 @@ set(unit_tests_sources hardfork.cpp unbound.cpp uri.cpp + variant.cpp varint.cpp ver_rct_non_semantics_simple_cached.cpp ringct.cpp diff --git a/tests/unit_tests/crypto.cpp b/tests/unit_tests/crypto.cpp index 4cac0b89f..e41f3955f 100644 --- a/tests/unit_tests/crypto.cpp +++ b/tests/unit_tests/crypto.cpp @@ -32,8 +32,15 @@ #include <sstream> #include <string> +extern "C" +{ +#include "crypto/crypto-ops.h" +} +#include "crypto/generators.h" #include "cryptonote_basic/cryptonote_basic_impl.h" #include "cryptonote_basic/merge_mining.h" +#include "ringct/rctOps.h" +#include "ringct/rctTypes.h" namespace { @@ -312,3 +319,20 @@ TEST(Crypto, tree_branch) } } } + +TEST(Crypto, generator_consistency) +{ + // crypto/generators.h + const crypto::public_key G{crypto::get_G()}; + const crypto::public_key H{crypto::get_H()}; + const ge_p3 H_p3 = crypto::get_H_p3(); + + // crypto/crypto-ops.h + ASSERT_TRUE(memcmp(&H_p3, &ge_p3_H, sizeof(ge_p3)) == 0); + + // ringct/rctOps.h + ASSERT_TRUE(memcmp(G.data, rct::G.bytes, 32) == 0); + + // ringct/rctTypes.h + ASSERT_TRUE(memcmp(H.data, rct::H.bytes, 32) == 0); +} diff --git a/tests/unit_tests/epee_utils.cpp b/tests/unit_tests/epee_utils.cpp index 185cb73b1..c776fbcc9 100644 --- a/tests/unit_tests/epee_utils.cpp +++ b/tests/unit_tests/epee_utils.cpp @@ -1241,6 +1241,22 @@ TEST(ToHex, ArrayFromPod) ); } +TEST(ToHex, Buffer) +{ + static constexpr const std::uint8_t source[] = {0xFF, 0x00, 0xAB, 0x01}; + const std::vector<char> expected{'f', 'f', '0', '0', 'a', 'b', '0', '1'}; + + std::vector<char> buffer; + buffer.resize(expected.size()); + EXPECT_TRUE(epee::to_hex::buffer(epee::to_mut_span(buffer), source)); + EXPECT_EQ(expected, buffer); + + buffer.pop_back(); + EXPECT_FALSE(epee::to_hex::buffer(epee::to_mut_span(buffer), source)); + buffer.pop_back(); + EXPECT_FALSE(epee::to_hex::buffer(epee::to_mut_span(buffer), source)); +} + TEST(ToHex, Ostream) { std::stringstream out; diff --git a/tests/unit_tests/variant.cpp b/tests/unit_tests/variant.cpp new file mode 100644 index 000000000..d7ded8e4b --- /dev/null +++ b/tests/unit_tests/variant.cpp @@ -0,0 +1,436 @@ +// Copyright (c) 2023, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "common/variant.h" + +#include <boost/mpl/deref.hpp> +#include <boost/variant/recursive_wrapper.hpp> +#include <boost/variant/recursive_variant.hpp> + +#include "gtest/gtest.h" + +#include <sstream> +#include <type_traits> +#include <vector> + +using tools::variant; +using tools::variant_static_visitor; + +namespace +{ +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template <typename T> +using strip_all_t = std::remove_reference_t<std::remove_cv_t<T>>; +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template <typename T, typename U> +using strip_same = std::is_same<strip_all_t<T>, strip_all_t<U>>; +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template +< + typename PositiveType, + typename TestType, + typename... VariantTypes, + class VecTypes = boost::mpl::vector<VariantTypes...>, + class VecBegin = typename boost::mpl::begin<VecTypes>::type, + class VecIndexT = typename boost::mpl::find<VecTypes, TestType>::type, + size_t TYPE_INDEX = boost::mpl::distance<VecBegin, VecIndexT>::value, + bool LAST_VARIANT_TYPE = TYPE_INDEX == sizeof...(VariantTypes) - 1 +> +static std::enable_if_t<LAST_VARIANT_TYPE> +test_is_type_match(const variant<VariantTypes...>& v) +{ + constexpr bool expected = strip_same<PositiveType, TestType>(); + const bool actual = v.template is_type<TestType>(); + EXPECT_EQ(expected, actual); + + EXPECT_FALSE(v.template is_type<boost::blank>()); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template +< + typename PositiveType, + typename TestType, + typename... VariantTypes, + class VecTypes = boost::mpl::vector<VariantTypes...>, + class VecBegin = typename boost::mpl::begin<VecTypes>::type, + class VecIndexT = typename boost::mpl::find<VecTypes, TestType>::type, + size_t TYPE_INDEX = boost::mpl::distance<VecBegin, VecIndexT>::value, + bool LAST_VARIANT_TYPE = TYPE_INDEX == sizeof...(VariantTypes) - 1 +> +static std::enable_if_t<!LAST_VARIANT_TYPE> +test_is_type_match(const variant<VariantTypes...>& v) +{ + constexpr bool expected = strip_same<PositiveType, TestType>(); + const bool actual = v.template is_type<TestType>(); + EXPECT_EQ(expected, actual); + + using NextTypeIt = typename boost::mpl::advance<VecIndexT, boost::mpl::int_<1>>::type; + using NextTestType = typename boost::mpl::deref<NextTypeIt>::type; + test_is_type_match<PositiveType, NextTestType>(v); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template +< + typename VariantType0, + typename... VariantTypesRest, + typename AssignType +> +static void test_is_type_ref +( + variant<VariantType0, VariantTypesRest...>& v, + AssignType&& val +) +{ + v = val; + test_is_type_match<AssignType, VariantType0>(v); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template +< + typename VariantType0, + typename... VariantTypesRest, + typename AssignType0, + typename... AssignTypesRest +> +static void test_is_type_ref +( + variant<VariantType0, VariantTypesRest...>& v, + AssignType0&& val_0, + AssignTypesRest&&... val_rest +) +{ + v = val_0; + test_is_type_match<AssignType0, VariantType0>(v); + test_is_type_ref(v, val_rest...); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template <typename... VariantTypes> +static void test_is_type_full(VariantTypes&&... test_vals) +{ + variant<VariantTypes...> v; + test_is_type_ref(v, test_vals...); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template +< + size_t IJ = 0, + typename... VariantTypes, + bool END = IJ == sizeof...(VariantTypes) * sizeof...(VariantTypes) +> +static std::enable_if_t<END> +test_same_type_ref +( + variant<VariantTypes...>& v1, + variant<VariantTypes...>& v2, + const std::tuple<VariantTypes...>& tup_i, + const std::tuple<VariantTypes...>& tup_j +) +{ /* trivial end case */ } +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template +< + size_t IJ = 0, + typename... VariantTypes, + bool END = IJ == sizeof...(VariantTypes) * sizeof...(VariantTypes) +> +static std::enable_if_t<!END> +test_same_type_ref +( + variant<VariantTypes...>& v1, + variant<VariantTypes...>& v2, + const std::tuple<VariantTypes...>& tup_i, + const std::tuple<VariantTypes...>& tup_j +) +{ + constexpr size_t I = IJ / sizeof...(VariantTypes); + constexpr size_t J = IJ % sizeof...(VariantTypes); + constexpr bool expected = I == J; + + v1 = std::get<I>(tup_i); + v2 = std::get<J>(tup_j); + const bool actual = variant<VariantTypes...>::same_type(v1, v2); + + EXPECT_EQ(expected, actual); + + test_same_type_ref<IJ + 1>(v1, v2, tup_i, tup_j); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +template <typename... VariantTypes> +static void test_same_type_full +( + const std::tuple<VariantTypes...>& vals_i, + const std::tuple<VariantTypes...>& vals_j +) +{ + using Variant = variant<VariantTypes...>; + Variant v_i; + Variant v_j; + test_same_type_ref(v_i, v_j, vals_i, vals_j); +} +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +struct test_stringify_visitor: public variant_static_visitor<std::string> +{ + template <typename T> + static std::string stringify(const T& t) + { + std::stringstream ss; + ss << typeid(T).name(); + ss << "::"; + ss << t; + return ss.str(); + } + + template <class Variant, typename T> + static void test_visitation(const Variant& v, const T& t) + { + EXPECT_EQ(test_stringify_visitor::stringify(t), v.visit(test_stringify_visitor())); + } + + // Make sure boost::blank errors + using variant_static_visitor::operator(); + + // Visitation implementation + template <typename T> + std::string operator()(const T& t) const + { + return test_stringify_visitor::stringify(t); + } +}; +//------------------------------------------------------------------------------------------------------------------- +//------------------------------------------------------------------------------------------------------------------- +} // anonymous namespace + +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, operatorbool) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_FALSE(v); + v = (int16_t) 2023; + EXPECT_TRUE(v); + v = (int16_t) 0; + EXPECT_TRUE(v); + v = boost::blank{}; + EXPECT_FALSE(v); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, is_empty) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_TRUE(v.is_empty()); + v = (int16_t) 2023; + EXPECT_FALSE(v.is_empty()); + v = (int16_t) 0; + EXPECT_FALSE(v.is_empty()); + v = boost::blank{}; + EXPECT_TRUE(v.is_empty()); + + variant<> v2; + EXPECT_TRUE(v2.is_empty()); + v2 = boost::blank{}; + EXPECT_TRUE(v2.is_empty()); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, is_type) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_TRUE(v.is_type<boost::blank>()); + v = (int16_t) 2023; + EXPECT_TRUE(v.is_type<int16_t>()); + + test_is_type_full((uint32_t) 2023, (char) '\n', std::string("HOWDY")); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, try_unwrap) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_FALSE(v.try_unwrap<int8_t>()); + v = (int16_t) 5252; + ASSERT_TRUE(v.try_unwrap<int16_t>()); + EXPECT_EQ(5252, *v.try_unwrap<int16_t>()); + EXPECT_FALSE(v.try_unwrap<uint16_t>()); + EXPECT_FALSE(v.try_unwrap<std::string>()); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, unwrap) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_THROW(v.unwrap<int8_t>(), std::runtime_error); + v = (int16_t) 5252; + EXPECT_EQ(5252, v.unwrap<int16_t>()); + EXPECT_THROW(v.unwrap<uint16_t>(), std::runtime_error); + EXPECT_THROW(v.unwrap<std::string>(), std::runtime_error); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, mutation) +{ + variant<uint8_t> v; + v = (uint8_t) 5; + EXPECT_EQ(5, v.unwrap<uint8_t>()); + uint8_t &intref{v.unwrap<uint8_t>()}; + intref = 10; + EXPECT_EQ(10, v.unwrap<uint8_t>()); + EXPECT_TRUE(v.try_unwrap<uint8_t>()); + uint8_t *intptr{v.try_unwrap<uint8_t>()}; + *intptr = 15; + EXPECT_EQ(15, v.unwrap<uint8_t>()); + + const variant<uint8_t> &v_ref{v}; + EXPECT_EQ(15, v_ref.unwrap<uint8_t>()); + EXPECT_TRUE(v_ref.try_unwrap<uint8_t>()); + EXPECT_EQ(15, *(v_ref.try_unwrap<uint8_t>())); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, index) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_EQ(0, v.index()); + v = (int8_t) 7; + EXPECT_EQ(1, v.index()); + v = (uint8_t) 7; + EXPECT_EQ(2, v.index()); + v = (int16_t) 7; + EXPECT_EQ(3, v.index()); + v = (uint16_t) 7; + EXPECT_EQ(4, v.index()); + v = "verifiable variant vying for vengence versus visa"; + EXPECT_EQ(5, v.index()); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, type_index_of) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_EQ(0, decltype(v)::type_index_of<boost::blank>()); + EXPECT_EQ(1, decltype(v)::type_index_of<int8_t>()); + EXPECT_EQ(2, decltype(v)::type_index_of<uint8_t>()); + EXPECT_EQ(3, decltype(v)::type_index_of<int16_t>()); + EXPECT_EQ(4, decltype(v)::type_index_of<uint16_t>()); + EXPECT_EQ(5, decltype(v)::type_index_of<std::string>()); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, constexpr_type_index_of) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + constexpr int TINDEX0 = decltype(v)::type_index_of<boost::blank>(); + EXPECT_EQ(0, TINDEX0); + constexpr int TINDEX5 = decltype(v)::type_index_of<std::string>(); + EXPECT_EQ(5, TINDEX5); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, same_type) +{ + const std::tuple<int, std::string, char> vals_i(77840, "Hullubaloo", '\0'); + const std::tuple<int, std::string, char> vals_j(1876, "Canneck", '\t'); + test_same_type_full(vals_i, vals_j); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, visit) +{ + variant<int8_t, uint8_t, int16_t, uint16_t, std::string> v; + EXPECT_THROW(v.visit(test_stringify_visitor()), std::runtime_error); + + v = "Rev"; + test_stringify_visitor::test_visitation(v, std::string("Rev")); + + v = (int16_t) 2001; + test_stringify_visitor::test_visitation(v, (int16_t) 2001); + EXPECT_NE(test_stringify_visitor::stringify((uint16_t) 2001), v.visit(test_stringify_visitor())); +} +//------------------------------------------------------------------------------------------------------------------- +TEST(variant, ad_hoc_recursion) +{ + struct left_t; + struct right_t; + + using twisty = variant<boost::recursive_wrapper<left_t>, boost::recursive_wrapper<right_t>>; + + struct left_t + { + twisty l; + }; + + struct right_t + { + twisty r; + }; + + auto right = [](twisty&& t = {}) -> twisty + { + right_t r; + r.r = t; + return r; + }; + + auto left = [](twisty&& t = {}) -> twisty + { + left_t l; + l.l = t; + return l; + }; + + struct twisty_counter: variant_static_visitor<std::pair<int, int>> + { + std::pair<int, int> operator()(boost::blank) const + { + return {0, 0}; + } + + std::pair<int, int> operator()(const left_t& l) const + { + auto count = l.l.visit(twisty_counter()); + count.first += 1; + return count; + } + + std::pair<int, int> operator()(const right_t& r) const + { + auto count = r.r.visit(twisty_counter()); + count.second += 1; + return count; + } + }; + + const twisty tw = left(left(right(right(left(right(left(right(left())))))))); + + int left_count, right_count; + std::tie(left_count, right_count) = tw.visit(twisty_counter()); + + EXPECT_EQ(5, left_count); + EXPECT_EQ(4, right_count); +} +//------------------------------------------------------------------------------------------------------------------- |