From 0e441c15159babe3fdd1042afec965e91ed8ac66 Mon Sep 17 00:00:00 2001 From: galp Date: Thu, 6 Feb 2020 13:56:12 -0700 Subject: [PATCH 01/25] Enable signing & verifying - fix test --- divi/src/test/rpc_tests.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/divi/src/test/rpc_tests.cpp b/divi/src/test/rpc_tests.cpp index 953674c78..821745ef2 100644 --- a/divi/src/test/rpc_tests.cpp +++ b/divi/src/test/rpc_tests.cpp @@ -90,7 +90,7 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams) BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error); } -BOOST_AUTO_TEST_CASE(rpc_rawsign,SKIP_TEST) +BOOST_AUTO_TEST_CASE(rpc_rawsign) { Value r; // input is a 1-of-2 multisig (so is output): @@ -103,10 +103,15 @@ BOOST_AUTO_TEST_CASE(rpc_rawsign,SKIP_TEST) string notsigned = r.get_str(); string privkey1 = "\"YVobcS47fr6kceZy9LzLJR8WQ6YRpUwYKoJhrnEXepebMxaSpbnn\""; string privkey2 = "\"YRyMjG8hbm8jHeDMAfrzSeHq5GgAj7kuHFvJtMudCUH3sCkq1WtA\""; + r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false); + + ECCVerifyHandle verificationModule; + ECC_Start(); r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true); + ECC_Stop(); } BOOST_AUTO_TEST_CASE(rpc_format_monetary_values) From 14d2fb1813c5e2212834ba69447c01bb53b39e71 Mon Sep 17 00:00:00 2001 From: galp Date: Thu, 6 Feb 2020 14:05:52 -0700 Subject: [PATCH 02/25] Fix rpc wallet signing and verifying issues --- divi/src/test/rpc_wallet_tests.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/divi/src/test/rpc_wallet_tests.cpp b/divi/src/test/rpc_wallet_tests.cpp index 5f0359bff..148fae98e 100644 --- a/divi/src/test/rpc_wallet_tests.cpp +++ b/divi/src/test/rpc_wallet_tests.cpp @@ -70,6 +70,8 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) Value r; LOCK2(cs_main, pwalletMain->cs_wallet); + ECCVerifyHandle verificationModule; + ECC_Start(); CPubKey demoPubkey = pwalletMain->GenerateNewKey(0,false); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); @@ -171,7 +173,7 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) /* Correct address and signature but wrong message */ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); /* Correct address, message and signature*/ - BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); + BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); /********************************* * getaddressesbyaccount @@ -181,7 +183,6 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); - ECC_Stop(); } From ea06c6c84725386118c5aaae62ccabaf2a8d8272 Mon Sep 17 00:00:00 2001 From: Chris Cates Date: Fri, 7 Feb 2020 13:31:07 -0500 Subject: [PATCH 03/25] rpc_tests.cpp: fix memory violation error --- divi/src/test/rpc_tests.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/divi/src/test/rpc_tests.cpp b/divi/src/test/rpc_tests.cpp index 821745ef2..996b6f7a9 100644 --- a/divi/src/test/rpc_tests.cpp +++ b/divi/src/test/rpc_tests.cpp @@ -92,6 +92,9 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams) BOOST_AUTO_TEST_CASE(rpc_rawsign) { + ECCVerifyHandle verificationModule; + ECC_Start(); + Value r; // input is a 1-of-2 multisig (so is output): string prevout = @@ -103,14 +106,13 @@ BOOST_AUTO_TEST_CASE(rpc_rawsign) string notsigned = r.get_str(); string privkey1 = "\"YVobcS47fr6kceZy9LzLJR8WQ6YRpUwYKoJhrnEXepebMxaSpbnn\""; string privkey2 = "\"YRyMjG8hbm8jHeDMAfrzSeHq5GgAj7kuHFvJtMudCUH3sCkq1WtA\""; - + r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false); - ECCVerifyHandle verificationModule; - ECC_Start(); r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true); + ECC_Stop(); } From 41a66bac6772c2c5644766bf4a22b1645de7491a Mon Sep 17 00:00:00 2001 From: galp Date: Mon, 10 Feb 2020 14:59:16 -0700 Subject: [PATCH 04/25] Initialize global signature objects --- divi/src/core_read.cpp | 3 +++ divi/src/test/script_P2SH_tests.cpp | 20 ++++++++++++++++--- divi/src/test/script_tests.cpp | 31 ++++++++++++++++++++++++----- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/divi/src/core_read.cpp b/divi/src/core_read.cpp index 92376c8a7..6963d6151 100644 --- a/divi/src/core_read.cpp +++ b/divi/src/core_read.cpp @@ -32,6 +32,9 @@ CScript ParseScript(std::string s) static map mapOpNames; if (mapOpNames.empty()) { + mapOpNames["OP_RETURN"] = opcodetype::OP_META; + mapOpNames["RETURN"] = opcodetype::OP_META; + for (int op = 0; op <= OP_ZEROCOINSPEND; op++) { // Allow OP_RESERVED to get into mapOpNames if (op < OP_NOP && op != OP_RESERVED) diff --git a/divi/src/test/script_P2SH_tests.cpp b/divi/src/test/script_P2SH_tests.cpp index 03273e496..86a693d1f 100644 --- a/divi/src/test/script_P2SH_tests.cpp +++ b/divi/src/test/script_P2SH_tests.cpp @@ -49,9 +49,11 @@ Verify(const CScript& scriptSig, const CScript& scriptPubKey, bool fStrict, Scri BOOST_AUTO_TEST_SUITE(script_P2SH_tests) -BOOST_AUTO_TEST_CASE(sign,SKIP_TEST) +BOOST_AUTO_TEST_CASE(sign) { LOCK(cs_main); + ECCVerifyHandle verificationModule; + ECC_Start(); // Pay-to-script-hash looks like this: // scriptSig: // scriptPubKey: HASH160 EQUAL @@ -110,6 +112,7 @@ BOOST_AUTO_TEST_CASE(sign,SKIP_TEST) // All of the above should be OK, and the txTos have valid signatures // Check to make sure signature verification fails if we use the wrong ScriptSig: for (int i = 0; i < 8; i++) + { for (int j = 0; j < 8; j++) { CScript sigSave = txTo[i].vin[0].scriptSig; @@ -121,6 +124,9 @@ BOOST_AUTO_TEST_CASE(sign,SKIP_TEST) BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j)); txTo[i].vin[0].scriptSig = sigSave; } + } + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(norecurse) @@ -150,9 +156,11 @@ BOOST_AUTO_TEST_CASE(norecurse) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } -BOOST_AUTO_TEST_CASE(set,SKIP_TEST) +BOOST_AUTO_TEST_CASE(set) { LOCK(cs_main); + ECCVerifyHandle verificationModule; + ECC_Start(); // Test the CScript::Set* methods CBasicKeyStore keystore; CKey key[4]; @@ -205,6 +213,7 @@ BOOST_AUTO_TEST_CASE(set,SKIP_TEST) BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); BOOST_CHECK_MESSAGE(IsStandardTx(txTo[i], reason), strprintf("txTo[%d].IsStandard", i)); } + ECC_Stop(); } BOOST_AUTO_TEST_CASE(is) @@ -258,9 +267,12 @@ BOOST_AUTO_TEST_CASE(switchover) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EQUALVERIFY, ScriptErrorString(err)); } -BOOST_AUTO_TEST_CASE(AreInputsStandard,SKIP_TEST) +BOOST_AUTO_TEST_CASE(AreInputsStandard) { LOCK(cs_main); + ECCVerifyHandle verificationModule; + ECC_Start(); + CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); CBasicKeyStore keystore; @@ -376,6 +388,8 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard,SKIP_TEST) BOOST_CHECK(!::AreInputsStandard(txToNonStd2, coins)); BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd2, coins), 20U); + + ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/script_tests.cpp b/divi/src/test/script_tests.cpp index c79d64365..b8b99b2a8 100644 --- a/divi/src/test/script_tests.cpp +++ b/divi/src/test/script_tests.cpp @@ -621,13 +621,15 @@ BOOST_AUTO_TEST_CASE(script_build) #endif } -BOOST_AUTO_TEST_CASE(script_valid,SKIP_TEST) +BOOST_AUTO_TEST_CASE(script_valid) { // Read tests from test/data/script_valid.json // Format is an array of arrays // Inner arrays are [ "scriptSig", "scriptPubKey", "flags" ] // ... where scriptSig and scriptPubKey are stringified // scripts. + ECCVerifyHandle verificationModule; + ECC_Start(); Array tests = read_json(std::string(json_tests::script_valid, json_tests::script_valid + sizeof(json_tests::script_valid))); BOOST_FOREACH(Value& tv, tests) @@ -649,10 +651,13 @@ BOOST_AUTO_TEST_CASE(script_valid,SKIP_TEST) DoTest(scriptPubKey, scriptSig, scriptflags, true, strTest); } + ECC_Stop(); } -BOOST_AUTO_TEST_CASE(script_invalid, SKIP_TEST) +BOOST_AUTO_TEST_CASE(script_invalid) { + ECCVerifyHandle verificationModule; + ECC_Start(); // Scripts that should evaluate as invalid Array tests = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid))); @@ -675,6 +680,7 @@ BOOST_AUTO_TEST_CASE(script_invalid, SKIP_TEST) DoTest(scriptPubKey, scriptSig, scriptflags, false, strTest); } + ECC_Stop(); } BOOST_AUTO_TEST_CASE(script_PushData) @@ -739,8 +745,11 @@ sign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction) return sign_multisig(scriptPubKey, keys, transaction); } -BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12, SKIP_TEST) +BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) { + ECCVerifyHandle verificationModule; + ECC_Start(); + ScriptError err; CKey key1, key2, key3; key1.MakeNewKey(true); @@ -767,10 +776,15 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12, SKIP_TEST) CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12); BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); + + ECC_Stop(); } -BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23,SKIP_TEST) +BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) { + ECCVerifyHandle verificationModule; + ECC_Start(); + ScriptError err; CKey key1, key2, key3, key4; key1.MakeNewKey(true); @@ -836,10 +850,15 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23,SKIP_TEST) CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23); BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); + + ECC_Stop(); } -BOOST_AUTO_TEST_CASE(script_combineSigs, SKIP_TEST) +BOOST_AUTO_TEST_CASE(script_combineSigs) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Test the CombineSignatures function CBasicKeyStore keystore; vector keys; @@ -945,6 +964,8 @@ BOOST_AUTO_TEST_CASE(script_combineSigs, SKIP_TEST) BOOST_CHECK(combined == complete23); combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a); BOOST_CHECK(combined == partial3c); + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(script_standard_push) From 6348480add5f810384e904f7650e1b20882c0d9d Mon Sep 17 00:00:00 2001 From: Chris Cates Date: Fri, 7 Feb 2020 13:56:06 -0500 Subject: [PATCH 05/25] rpc_wallet_tests.cpp fix memory violation error --- divi/src/test/rpc_wallet_tests.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/divi/src/test/rpc_wallet_tests.cpp b/divi/src/test/rpc_wallet_tests.cpp index 148fae98e..5f0359bff 100644 --- a/divi/src/test/rpc_wallet_tests.cpp +++ b/divi/src/test/rpc_wallet_tests.cpp @@ -70,8 +70,6 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) Value r; LOCK2(cs_main, pwalletMain->cs_wallet); - ECCVerifyHandle verificationModule; - ECC_Start(); CPubKey demoPubkey = pwalletMain->GenerateNewKey(0,false); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); @@ -173,7 +171,7 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) /* Correct address and signature but wrong message */ BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " wrongmessage").get_bool() == false); /* Correct address, message and signature*/ - BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); + BOOST_CHECK(CallRPC("verifymessage " + demoAddress.ToString() + " " + retValue.get_str() + " mymessage").get_bool() == true); /********************************* * getaddressesbyaccount @@ -183,6 +181,7 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); + ECC_Stop(); } From b4bebde6a3bc55bbcca673d9244c8fe0d5ece42a Mon Sep 17 00:00:00 2001 From: galp Date: Tue, 11 Feb 2020 10:05:00 -0700 Subject: [PATCH 06/25] Update Makefile headers --- divi/src/Makefile.am | 2 ++ 1 file changed, 2 insertions(+) diff --git a/divi/src/Makefile.am b/divi/src/Makefile.am index c4e9fe4ed..4fdfb21ba 100644 --- a/divi/src/Makefile.am +++ b/divi/src/Makefile.am @@ -89,11 +89,13 @@ BITCOIN_CORE_H = \ bip39.h \ bip39_english.h \ bloom.h \ + blockmap.h\ chain.h \ chainparams.h \ chainparamsbase.h \ chainparamsseeds.h \ checkpoints.h \ + checkpoint_data.h\ checkqueue.h \ clientversion.h \ coincontrol.h \ From 41d886df3e47ef7db38edb99ec3d8b62d4ec7e03 Mon Sep 17 00:00:00 2001 From: galp Date: Wed, 12 Feb 2020 10:02:48 -0700 Subject: [PATCH 07/25] Dependency injection of ECC context --- divi/src/Makefile.am | 2 ++ divi/src/Secp256k1Context.cpp | 46 +++++++++++++++++++++++++++++++++++ divi/src/Secp256k1Context.h | 18 ++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 divi/src/Secp256k1Context.cpp create mode 100644 divi/src/Secp256k1Context.h diff --git a/divi/src/Makefile.am b/divi/src/Makefile.am index 4fdfb21ba..9c83fcce0 100644 --- a/divi/src/Makefile.am +++ b/divi/src/Makefile.am @@ -155,6 +155,7 @@ BITCOIN_CORE_H = \ script/standard.h \ script/script_error.h \ serialize.h \ + Secp256k1Context.h \ spork.h \ sporkdb.h \ spentindex.h \ @@ -384,6 +385,7 @@ libbitcoin_common_a_SOURCES = \ script/sign.cpp \ script/standard.cpp \ script/script_error.cpp \ + Secp256k1Context.cpp \ spork.cpp \ sporkdb.cpp \ $(BITCOIN_CORE_H) diff --git a/divi/src/Secp256k1Context.cpp b/divi/src/Secp256k1Context.cpp new file mode 100644 index 000000000..e8af3fd26 --- /dev/null +++ b/divi/src/Secp256k1Context.cpp @@ -0,0 +1,46 @@ +#include "Secp256k1Context.h" + +#include +#include "random.h" +#include "allocators.h" + +Secp256k1Context::Secp256k1Context() +{ + assert(verifying_context == NULL); + verifying_context = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); + assert(verifying_context != NULL); + + + assert(signing_context == NULL); + secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + assert(ctx != NULL); + { + // Pass in a random blinding seed to the secp256k1 context. + std::vector> vseed(32); + GetRandBytes(vseed.data(), 32); + bool ret = secp256k1_context_randomize(ctx, vseed.data()); + assert(ret); + } + signing_context = ctx; +} +Secp256k1Context::~Secp256k1Context() +{ + assert(verifying_context != NULL); + secp256k1_context_destroy(verifying_context); + verifying_context = NULL; + + secp256k1_context *ctx = signing_context; + signing_context = NULL; + if (ctx) { + secp256k1_context_destroy(ctx); + } +} + +secp256k1_context* Secp256k1Context::GetVerifyContext() +{ + return verifying_context; +} +secp256k1_context* Secp256k1Context::GetSigningContext() +{ + return signing_context; +} \ No newline at end of file diff --git a/divi/src/Secp256k1Context.h b/divi/src/Secp256k1Context.h new file mode 100644 index 000000000..ea887f0c4 --- /dev/null +++ b/divi/src/Secp256k1Context.h @@ -0,0 +1,18 @@ +#ifndef SECP256_K1_CONTEXT_H +#define SECP256_K1_CONTEXT_H +#include +#include + +class Secp256k1Context +{ +private: + secp256k1_context* verifying_context = NULL; + secp256k1_context* signing_context = NULL; +public: + Secp256k1Context(); + ~Secp256k1Context(); + + secp256k1_context* GetVerifyContext(); + secp256k1_context* GetSigningContext(); +}; +#endif //SECP256_K1_CONTEXT_H \ No newline at end of file From 8e25e26ebf780569394f3cbdecfdc51da8620fb3 Mon Sep 17 00:00:00 2001 From: galp Date: Fri, 14 Feb 2020 08:25:03 -0700 Subject: [PATCH 08/25] Make Secp context singleton --- divi/src/Secp256k1Context.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/divi/src/Secp256k1Context.h b/divi/src/Secp256k1Context.h index ea887f0c4..6ebe6fac3 100644 --- a/divi/src/Secp256k1Context.h +++ b/divi/src/Secp256k1Context.h @@ -8,9 +8,15 @@ class Secp256k1Context private: secp256k1_context* verifying_context = NULL; secp256k1_context* signing_context = NULL; -public: + Secp256k1Context(); ~Secp256k1Context(); +public: + static Secp256k1Context& instance() + { + static Secp256k1Context uniqueInstance; + return uniqueInstance; + } secp256k1_context* GetVerifyContext(); secp256k1_context* GetSigningContext(); From be11bf0fd3d0e21ed0f98be7cb70b4a4554b1315 Mon Sep 17 00:00:00 2001 From: galp Date: Fri, 14 Feb 2020 09:07:50 -0700 Subject: [PATCH 09/25] Initialize secp context intrinsically --- divi/src/init.cpp | 5 ---- divi/src/key.cpp | 31 ++----------------------- divi/src/key.h | 6 ----- divi/src/pubkey.cpp | 32 ++----------------------- divi/src/pubkey.h | 11 --------- divi/src/test/DoS_tests.cpp | 6 ++--- divi/src/test/key_tests.cpp | 6 ++--- divi/src/test/multisig_tests.cpp | 24 +++++++++---------- divi/src/test/rpc_tests.cpp | 6 ++--- divi/src/test/rpc_wallet_tests.cpp | 4 ---- divi/src/test/sanity_tests.cpp | 6 ++--- divi/src/test/script_P2SH_tests.cpp | 18 +++++++-------- divi/src/test/script_tests.cpp | 36 ++++++++++++++--------------- divi/src/test/sigopcount_tests.cpp | 6 ++--- divi/src/test/transaction_tests.cpp | 24 +++++++++---------- 15 files changed, 70 insertions(+), 151 deletions(-) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index bc8a528e3..3658cf71d 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -75,7 +75,6 @@ int nWalletBackups = 100; volatile bool fFeeEstimatesInitialized = false; volatile bool fRestartRequested = false; // true: restart false: shutdown extern std::list listAccCheckpointsNoDB; -static std::unique_ptr globalVerifyHandle; #if ENABLE_ZMQ static CZMQNotificationInterface* pzmqNotificationInterface = NULL; @@ -664,10 +663,6 @@ bool AppInitSanityChecks() { // ********************************************************* Step 4: sanity checks - // Initialize elliptic curve code - ECC_Start(); - globalVerifyHandle.reset(new ECCVerifyHandle()); - // Sanity check if (!InitSanityCheck()) return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME))); diff --git a/divi/src/key.cpp b/divi/src/key.cpp index d7eebab8f..8350b57a7 100644 --- a/divi/src/key.cpp +++ b/divi/src/key.cpp @@ -12,10 +12,9 @@ #include "random.h" #include "ecwrapper.h" -#include -#include +#include "Secp256k1Context.h" -static secp256k1_context* secp256k1_context_sign = NULL; +secp256k1_context* secp256k1_context_sign = Secp256k1Context::instance().GetSigningContext(); /** These functions are taken from the libsecp256k1 distribution and are very ugly. */ static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) { @@ -297,29 +296,3 @@ bool ECC_InitSanityCheck() { CPubKey pubkey = key.GetPubKey(); return key.VerifyPubKey(pubkey); } - -void ECC_Start() { - assert(secp256k1_context_sign == NULL); - - secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); - assert(ctx != NULL); - - { - // Pass in a random blinding seed to the secp256k1 context. - std::vector> vseed(32); - GetRandBytes(vseed.data(), 32); - bool ret = secp256k1_context_randomize(ctx, vseed.data()); - assert(ret); - } - - secp256k1_context_sign = ctx; -} - -void ECC_Stop() { - secp256k1_context *ctx = secp256k1_context_sign; - secp256k1_context_sign = NULL; - - if (ctx) { - secp256k1_context_destroy(ctx); - } -} diff --git a/divi/src/key.h b/divi/src/key.h index 8c9f16a86..a2c54a9f3 100644 --- a/divi/src/key.h +++ b/divi/src/key.h @@ -185,12 +185,6 @@ struct CExtKey { } }; -/** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */ -void ECC_Start(void); - -/** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */ -void ECC_Stop(void); - /** Check that required EC support is available at runtime. */ bool ECC_InitSanityCheck(void); #endif // BITCOIN_KEY_H diff --git a/divi/src/pubkey.cpp b/divi/src/pubkey.cpp index 4ebb6dc16..e084bd92e 100644 --- a/divi/src/pubkey.cpp +++ b/divi/src/pubkey.cpp @@ -4,15 +4,9 @@ #include "pubkey.h" -#include -#include - -namespace -{ -/* Global secp256k1_context object used for verification. */ -secp256k1_context* secp256k1_context_verify = NULL; -} +#include "Secp256k1Context.h" +secp256k1_context* secp256k1_context_verify = Secp256k1Context::instance().GetVerifyContext(); /** This function is taken from the libsecp256k1 distribution and implements * DER parsing for ECDSA signatures, while supporting an arbitrary subset of * format violations. @@ -279,25 +273,3 @@ bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const { } return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, NULL, &sig)); } - -/* static */ int ECCVerifyHandle::refcount = 0; - -ECCVerifyHandle::ECCVerifyHandle() -{ - if (refcount == 0) { - assert(secp256k1_context_verify == NULL); - secp256k1_context_verify = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); - assert(secp256k1_context_verify != NULL); - } - refcount++; -} - -ECCVerifyHandle::~ECCVerifyHandle() -{ - refcount--; - if (refcount == 0) { - assert(secp256k1_context_verify != NULL); - secp256k1_context_destroy(secp256k1_context_verify); - secp256k1_context_verify = NULL; - } -} diff --git a/divi/src/pubkey.h b/divi/src/pubkey.h index 7f108a6eb..2063a4fe3 100644 --- a/divi/src/pubkey.h +++ b/divi/src/pubkey.h @@ -252,15 +252,4 @@ struct CExtPubKey { } }; -/** Users of this module must hold an ECCVerifyHandle. The constructor and - * destructor of these are not allowed to run in parallel, though. */ -class ECCVerifyHandle -{ - static int refcount; - -public: - ECCVerifyHandle(); - ~ECCVerifyHandle(); -}; - #endif // BITCOIN_PUBKEY_H diff --git a/divi/src/test/DoS_tests.cpp b/divi/src/test/DoS_tests.cpp index 29a8ebe0a..dad0e2378 100644 --- a/divi/src/test/DoS_tests.cpp +++ b/divi/src/test/DoS_tests.cpp @@ -119,8 +119,8 @@ CTransaction RandomOrphan() BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + CKey key; key.MakeNewKey(true); @@ -199,7 +199,7 @@ BOOST_AUTO_TEST_CASE(DoS_mapOrphans) LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); BOOST_CHECK(mapOrphanTransactionsByPrev.empty()); - ECC_Stop(); + } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/key_tests.cpp b/divi/src/test/key_tests.cpp index 020d111d7..597d087ed 100644 --- a/divi/src/test/key_tests.cpp +++ b/divi/src/test/key_tests.cpp @@ -63,8 +63,8 @@ BOOST_AUTO_TEST_SUITE(key_tests) BOOST_AUTO_TEST_CASE(key_test1) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; BOOST_CHECK( bsecret1.SetString (strSecret1)); @@ -190,7 +190,7 @@ BOOST_AUTO_TEST_CASE(key_test1) BOOST_CHECK(detsig == ParseHex("1b4f304f1b05599f88bc517819f6d43c69503baea5f253c55ea2d791394f7ce0de4f23c0d4c1f4d7a89bf130fed755201d22581911a8a44cf594014794231d325a")); BOOST_CHECK(detsigc == ParseHex("1f4f304f1b05599f88bc517819f6d43c69503baea5f253c55ea2d791394f7ce0de4f23c0d4c1f4d7a89bf130fed755201d22581911a8a44cf594014794231d325a")); - ECC_Stop(); + } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/multisig_tests.cpp b/divi/src/test/multisig_tests.cpp index d72415ec0..1036f3aa2 100644 --- a/divi/src/test/multisig_tests.cpp +++ b/divi/src/test/multisig_tests.cpp @@ -47,8 +47,8 @@ sign_multisig(CScript scriptPubKey, vector keys, CTransaction transaction, BOOST_AUTO_TEST_CASE(multisig_verify) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; @@ -150,13 +150,13 @@ BOOST_AUTO_TEST_CASE(multisig_verify) } } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(multisig_IsStandard) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + CKey key[4]; for (int i = 0; i < 4; i++) @@ -195,13 +195,13 @@ BOOST_AUTO_TEST_CASE(multisig_IsStandard) BOOST_CHECK(!::IsStandard(malformed[i], whichType)); } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(multisig_Solver1) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Tests Solver() that returns lists of keys that are // required to satisfy a ScriptPubKey @@ -307,13 +307,13 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) BOOST_CHECK(solutions.size() == 5); } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(multisig_Sign) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; @@ -354,7 +354,7 @@ BOOST_AUTO_TEST_CASE(multisig_Sign) BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } - ECC_Stop(); + } diff --git a/divi/src/test/rpc_tests.cpp b/divi/src/test/rpc_tests.cpp index 996b6f7a9..7e26192e4 100644 --- a/divi/src/test/rpc_tests.cpp +++ b/divi/src/test/rpc_tests.cpp @@ -92,8 +92,8 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams) BOOST_AUTO_TEST_CASE(rpc_rawsign) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + Value r; // input is a 1-of-2 multisig (so is output): @@ -113,7 +113,7 @@ BOOST_AUTO_TEST_CASE(rpc_rawsign) r = CallRPC(string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true); - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(rpc_format_monetary_values) diff --git a/divi/src/test/rpc_wallet_tests.cpp b/divi/src/test/rpc_wallet_tests.cpp index 5f0359bff..167818d4b 100644 --- a/divi/src/test/rpc_wallet_tests.cpp +++ b/divi/src/test/rpc_wallet_tests.cpp @@ -63,9 +63,6 @@ BOOST_AUTO_TEST_CASE(rpc_addmultisig) BOOST_AUTO_TEST_CASE(rpc_wallet) { - ECCVerifyHandle verificationModule; - ECC_Start(); - // Test RPC calls for various wallet statistics Value r; @@ -182,7 +179,6 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); - ECC_Stop(); } diff --git a/divi/src/test/sanity_tests.cpp b/divi/src/test/sanity_tests.cpp index 6ba1b4570..742dd6ffe 100644 --- a/divi/src/test/sanity_tests.cpp +++ b/divi/src/test/sanity_tests.cpp @@ -15,10 +15,10 @@ BOOST_AUTO_TEST_CASE(basic_sanity) BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test"); BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); - ECCVerifyHandle verificationModule; - ECC_Start(); + + BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test"); - ECC_Stop(); + } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/script_P2SH_tests.cpp b/divi/src/test/script_P2SH_tests.cpp index 86a693d1f..61fe3d2a9 100644 --- a/divi/src/test/script_P2SH_tests.cpp +++ b/divi/src/test/script_P2SH_tests.cpp @@ -52,8 +52,8 @@ BOOST_AUTO_TEST_SUITE(script_P2SH_tests) BOOST_AUTO_TEST_CASE(sign) { LOCK(cs_main); - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Pay-to-script-hash looks like this: // scriptSig: // scriptPubKey: HASH160 EQUAL @@ -126,7 +126,7 @@ BOOST_AUTO_TEST_CASE(sign) } } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(norecurse) @@ -159,8 +159,8 @@ BOOST_AUTO_TEST_CASE(norecurse) BOOST_AUTO_TEST_CASE(set) { LOCK(cs_main); - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Test the CScript::Set* methods CBasicKeyStore keystore; CKey key[4]; @@ -213,7 +213,7 @@ BOOST_AUTO_TEST_CASE(set) BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); BOOST_CHECK_MESSAGE(IsStandardTx(txTo[i], reason), strprintf("txTo[%d].IsStandard", i)); } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(is) @@ -270,8 +270,8 @@ BOOST_AUTO_TEST_CASE(switchover) BOOST_AUTO_TEST_CASE(AreInputsStandard) { LOCK(cs_main); - ECCVerifyHandle verificationModule; - ECC_Start(); + + CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); @@ -389,7 +389,7 @@ BOOST_AUTO_TEST_CASE(AreInputsStandard) BOOST_CHECK(!::AreInputsStandard(txToNonStd2, coins)); BOOST_CHECK_EQUAL(GetP2SHSigOpCount(txToNonStd2, coins), 20U); - ECC_Stop(); + } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/script_tests.cpp b/divi/src/test/script_tests.cpp index b8b99b2a8..a81763497 100644 --- a/divi/src/test/script_tests.cpp +++ b/divi/src/test/script_tests.cpp @@ -329,8 +329,8 @@ class TestBuilder BOOST_AUTO_TEST_CASE(script_build) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + const KeyData keys; std::vector good; @@ -610,7 +610,7 @@ BOOST_AUTO_TEST_CASE(script_build) #endif strBad += str + ",\n"; } - ECC_Stop(); + #ifdef UPDATE_JSON_TESTS FILE* valid = fopen("script_valid.json.gen", "w"); fputs(strGood.c_str(), valid); @@ -628,8 +628,8 @@ BOOST_AUTO_TEST_CASE(script_valid) // Inner arrays are [ "scriptSig", "scriptPubKey", "flags" ] // ... where scriptSig and scriptPubKey are stringified // scripts. - ECCVerifyHandle verificationModule; - ECC_Start(); + + Array tests = read_json(std::string(json_tests::script_valid, json_tests::script_valid + sizeof(json_tests::script_valid))); BOOST_FOREACH(Value& tv, tests) @@ -651,13 +651,13 @@ BOOST_AUTO_TEST_CASE(script_valid) DoTest(scriptPubKey, scriptSig, scriptflags, true, strTest); } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(script_invalid) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Scripts that should evaluate as invalid Array tests = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid))); @@ -680,7 +680,7 @@ BOOST_AUTO_TEST_CASE(script_invalid) DoTest(scriptPubKey, scriptSig, scriptflags, false, strTest); } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(script_PushData) @@ -747,8 +747,8 @@ sign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction) BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + ScriptError err; CKey key1, key2, key3; @@ -777,13 +777,13 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + ScriptError err; CKey key1, key2, key3, key4; @@ -851,13 +851,13 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(script_combineSigs) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Test the CombineSignatures function CBasicKeyStore keystore; @@ -965,7 +965,7 @@ BOOST_AUTO_TEST_CASE(script_combineSigs) combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a); BOOST_CHECK(combined == partial3c); - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(script_standard_push) diff --git a/divi/src/test/sigopcount_tests.cpp b/divi/src/test/sigopcount_tests.cpp index 840387762..764fce913 100644 --- a/divi/src/test/sigopcount_tests.cpp +++ b/divi/src/test/sigopcount_tests.cpp @@ -27,8 +27,8 @@ BOOST_AUTO_TEST_SUITE(sigopcount_tests) BOOST_AUTO_TEST_CASE(GetSigOpCount) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Test CScript::GetSigOpCount() @@ -68,7 +68,7 @@ BOOST_AUTO_TEST_CASE(GetSigOpCount) scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U); - ECC_Stop(); + } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/transaction_tests.cpp b/divi/src/test/transaction_tests.cpp index 586be2ff7..c5d0b3234 100644 --- a/divi/src/test/transaction_tests.cpp +++ b/divi/src/test/transaction_tests.cpp @@ -87,8 +87,8 @@ BOOST_AUTO_TEST_SUITE(transaction_tests) BOOST_AUTO_TEST_CASE(tx_valid) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Read tests from test/data/tx_valid.json // Format is an array of arrays @@ -169,13 +169,13 @@ BOOST_AUTO_TEST_CASE(tx_valid) } } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(tx_invalid) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + // Read tests from test/data/tx_invalid.json // Format is an array of arrays @@ -255,7 +255,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) } } - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(basic_transaction_tests) @@ -314,8 +314,8 @@ SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsViewCache& coinsRet) BOOST_AUTO_TEST_CASE(test_Get) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + CBasicKeyStore keystore; CCoinsView coinsDummy; @@ -348,13 +348,13 @@ BOOST_AUTO_TEST_CASE(test_Get) t1.vin[0].scriptSig = CScript(); BOOST_CHECK(!AreInputsStandard(t1, coins)); - ECC_Stop(); + } BOOST_AUTO_TEST_CASE(test_IsStandard) { - ECCVerifyHandle verificationModule; - ECC_Start(); + + LOCK(cs_main); CBasicKeyStore keystore; @@ -437,7 +437,7 @@ BOOST_AUTO_TEST_CASE(test_IsStandard) t.vout[1].scriptPubKey = CScript() << OP_META; BOOST_CHECK(!IsStandardTx(t, reason)); - ECC_Stop(); + } BOOST_AUTO_TEST_SUITE_END() From 0a783643a71fab4472f4c56c2a04345e65a4653b Mon Sep 17 00:00:00 2001 From: galp Date: Wed, 12 Feb 2020 12:49:54 -0700 Subject: [PATCH 10/25] Remove dead code --- divi/src/keystore.cpp | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/divi/src/keystore.cpp b/divi/src/keystore.cpp index 3074675fa..390b4e43d 100644 --- a/divi/src/keystore.cpp +++ b/divi/src/keystore.cpp @@ -63,22 +63,6 @@ bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) return false; } -static bool ExtractPubKey(const CScript &dest, CPubKey& pubKeyOut) -{ - //TODO: Use Solver to extract this? - CScript::const_iterator pc = dest.begin(); - opcodetype opcode; - std::vector vch; - if (!dest.GetOp(pc, opcode, vch) || vch.size() < 33 || vch.size() > 65) - return false; - pubKeyOut = CPubKey(vch); - if (!pubKeyOut.IsFullyValid()) - return false; - if (!dest.GetOp(pc, opcode, vch) || opcode != OP_CHECKSIG || dest.GetOp(pc, opcode, vch)) - return false; - return true; -} - bool CBasicKeyStore::AddWatchOnly(const CScript &dest) { LOCK(cs_KeyStore); From 0fc9f22176b9af9389519501b623fb7703882084 Mon Sep 17 00:00:00 2001 From: galp Date: Fri, 14 Feb 2020 10:28:07 -0700 Subject: [PATCH 11/25] Break tests into named cases --- divi/src/test/key_tests.cpp | 137 ++++++++++++++++++++++++++++++++++-- 1 file changed, 130 insertions(+), 7 deletions(-) diff --git a/divi/src/test/key_tests.cpp b/divi/src/test/key_tests.cpp index 597d087ed..821ec51ab 100644 --- a/divi/src/test/key_tests.cpp +++ b/divi/src/test/key_tests.cpp @@ -61,26 +61,55 @@ void dumpKeyInfo(uint256 privkey) BOOST_AUTO_TEST_SUITE(key_tests) -BOOST_AUTO_TEST_CASE(key_test1) +BOOST_AUTO_TEST_CASE(willFailToSetSecretsForBadAddress) { - - + CBitcoinSecret baddress1; + BOOST_CHECK(!baddress1.SetString(strAddressBad)); +} +BOOST_AUTO_TEST_CASE(willSetSecretsCorrectlyForRightFormat) +{ CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; BOOST_CHECK( bsecret1.SetString (strSecret1)); BOOST_CHECK( bsecret2.SetString (strSecret2)); BOOST_CHECK( bsecret1C.SetString(strSecret1C)); BOOST_CHECK( bsecret2C.SetString(strSecret2C)); - BOOST_CHECK(!baddress1.SetString(strAddressBad)); +} + +BOOST_AUTO_TEST_CASE(willRecognizeCompressedKeysFromNonCompressedKeys) +{ + + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; + BOOST_CHECK( + bsecret1.SetString (strSecret1) && + bsecret2.SetString (strSecret2) && + bsecret1C.SetString(strSecret1C) && + bsecret2C.SetString(strSecret2C)); CKey key1 = bsecret1.GetKey(); - BOOST_CHECK(key1.IsCompressed() == false); CKey key2 = bsecret2.GetKey(); - BOOST_CHECK(key2.IsCompressed() == false); CKey key1C = bsecret1C.GetKey(); - BOOST_CHECK(key1C.IsCompressed() == true); CKey key2C = bsecret2C.GetKey(); + + BOOST_CHECK(key1.IsCompressed() == false); + BOOST_CHECK(key2.IsCompressed() == false); + BOOST_CHECK(key1C.IsCompressed() == true); BOOST_CHECK(key2C.IsCompressed() == true); +} + +BOOST_AUTO_TEST_CASE(willCheckPrivateKeysOnlyVerifyTheirPubKey) +{ + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; + + bsecret1.SetString (strSecret1); + bsecret2.SetString (strSecret2); + bsecret1C.SetString(strSecret1C); + bsecret2C.SetString(strSecret2C); + + CKey key1 = bsecret1.GetKey(); + CKey key2 = bsecret2.GetKey(); + CKey key1C = bsecret1C.GetKey(); + CKey key2C = bsecret2C.GetKey(); CPubKey pubkey1 = key1. GetPubKey(); CPubKey pubkey2 = key2. GetPubKey(); @@ -106,11 +135,46 @@ BOOST_AUTO_TEST_CASE(key_test1) BOOST_CHECK(!key2C.VerifyPubKey(pubkey1C)); BOOST_CHECK(!key2C.VerifyPubKey(pubkey2)); BOOST_CHECK(key2C.VerifyPubKey(pubkey2C)); +} + +BOOST_AUTO_TEST_CASE(willMatchPubkeyToAddress) +{ + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; + + bsecret1.SetString (strSecret1); + bsecret2.SetString (strSecret2); + bsecret1C.SetString(strSecret1C); + bsecret2C.SetString(strSecret2C); + + CPubKey pubkey1 = bsecret1.GetKey(). GetPubKey(); + CPubKey pubkey2 = bsecret2.GetKey(). GetPubKey(); + CPubKey pubkey1C = bsecret1C.GetKey().GetPubKey(); + CPubKey pubkey2C = bsecret2C.GetKey().GetPubKey(); BOOST_CHECK(addr1.Get() == CTxDestination(pubkey1.GetID())); BOOST_CHECK(addr2.Get() == CTxDestination(pubkey2.GetID())); BOOST_CHECK(addr1C.Get() == CTxDestination(pubkey1C.GetID())); BOOST_CHECK(addr2C.Get() == CTxDestination(pubkey2C.GetID())); +} + +BOOST_AUTO_TEST_CASE(willCheckKeysSignAndVerifySignatures) +{ + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; + + bsecret1.SetString (strSecret1); + bsecret2.SetString (strSecret2); + bsecret1C.SetString(strSecret1C); + bsecret2C.SetString(strSecret2C); + + CKey key1 = bsecret1.GetKey(); + CKey key2 = bsecret2.GetKey(); + CKey key1C = bsecret1C.GetKey(); + CKey key2C = bsecret2C.GetKey(); + + CPubKey pubkey1 = key1. GetPubKey(); + CPubKey pubkey2 = key2. GetPubKey(); + CPubKey pubkey1C = key1C.GetPubKey(); + CPubKey pubkey2C = key2C.GetPubKey(); for (int n=0; n<16; n++) { @@ -193,4 +257,63 @@ BOOST_AUTO_TEST_CASE(key_test1) } +BOOST_AUTO_TEST_CASE(willVerifyOnlySetKeysAreFullyValid) +{ + + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; + BOOST_CHECK( bsecret1.SetString (strSecret1)); + BOOST_CHECK( bsecret2.SetString (strSecret2)); + BOOST_CHECK( bsecret1C.SetString(strSecret1C)); + BOOST_CHECK( bsecret2C.SetString(strSecret2C)); + BOOST_CHECK(!baddress1.SetString(strAddressBad)); + + CKey key1 = bsecret1.GetKey(); + BOOST_CHECK(key1.IsCompressed() == false); + CKey key2 = bsecret2.GetKey(); + BOOST_CHECK(key2.IsCompressed() == false); + CKey key1C = bsecret1C.GetKey(); + BOOST_CHECK(key1C.IsCompressed() == true); + CKey key2C = bsecret2C.GetKey(); + BOOST_CHECK(key2C.IsCompressed() == true); + + CPubKey pubkey1 = key1. GetPubKey(); + CPubKey pubkey2 = key2. GetPubKey(); + CPubKey pubkey1C = key1C.GetPubKey(); + CPubKey pubkey2C = key2C.GetPubKey(); + CPubKey uninitializedKey; + + BOOST_CHECK(pubkey1.IsFullyValid()); + BOOST_CHECK(pubkey2.IsFullyValid()); + BOOST_CHECK(pubkey1C.IsFullyValid()); + BOOST_CHECK(pubkey2C.IsFullyValid()); + BOOST_CHECK(!uninitializedKey.IsFullyValid()); + +} + +BOOST_AUTO_TEST_CASE(willDecompressCompressedKeys) +{ + + CBitcoinSecret bsecret1C, bsecret2C; + BOOST_CHECK( bsecret1C.SetString(strSecret1C)); + BOOST_CHECK( bsecret2C.SetString(strSecret2C)); + + CKey key1C = bsecret1C.GetKey(); + CKey key2C = bsecret2C.GetKey(); + BOOST_CHECK(key1C.IsCompressed() == true); + BOOST_CHECK(key2C.IsCompressed() == true); + + CPubKey pubkey1C = key1C.GetPubKey(); + CPubKey pubkey2C = key2C.GetPubKey(); + BOOST_CHECK(pubkey1C.IsCompressed()); + BOOST_CHECK(pubkey2C.IsCompressed()); + + pubkey1C.Decompress(); + pubkey2C.Decompress(); + + BOOST_CHECK(!pubkey1C.IsCompressed()); + BOOST_CHECK(!pubkey2C.IsCompressed()); + +} + + BOOST_AUTO_TEST_SUITE_END() From 800859e620e224356ffedc34b7b3674b69371a46 Mon Sep 17 00:00:00 2001 From: galp Date: Fri, 14 Feb 2020 16:04:26 -0700 Subject: [PATCH 12/25] Remove unused include --- divi/src/key.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/divi/src/key.cpp b/divi/src/key.cpp index 8350b57a7..ab37c5035 100644 --- a/divi/src/key.cpp +++ b/divi/src/key.cpp @@ -7,7 +7,6 @@ #include "crypto/common.h" #include "crypto/hmac_sha512.h" #include "crypto/rfc6979_hmac_sha256.h" -#include "eccryptoverify.h" #include "pubkey.h" #include "random.h" From ac9585f842d891e3fa0f67c3607bdd5d0b066e32 Mon Sep 17 00:00:00 2001 From: galp Date: Mon, 17 Feb 2020 13:41:01 -0700 Subject: [PATCH 13/25] Rename to something meaningful --- divi/src/divid.cpp | 2 +- divi/src/init.cpp | 30 +++++++++++++++--------------- divi/src/init.h | 2 +- divi/src/qt/divi.cpp | 4 ++-- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/divi/src/divid.cpp b/divi/src/divid.cpp index 47d88dac3..34b2f0418 100644 --- a/divi/src/divid.cpp +++ b/divi/src/divid.cpp @@ -143,7 +143,7 @@ bool AppInit(int argc, char* argv[]) SoftSetBoolArg("-server", true); detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup)); - fRet = AppInit2(threadGroup); + fRet = InitializeDivi(threadGroup); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { diff --git a/divi/src/init.cpp b/divi/src/init.cpp index 3658cf71d..e54b0f2bd 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -122,7 +122,7 @@ CClientUIInterface uiInterface; // threads that should only be stopped after the main network-processing // threads have exited. // -// Note that if running -daemon the parent process returns from AppInit2 +// Note that if running -daemon the parent process returns from InitializeDivi // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // @@ -177,7 +177,7 @@ void PrepareShutdown() if (!lockShutdown) return; - /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way, + /// Note: Shutdown() must be able to handle cases in which InitializeDivi() failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. @@ -674,7 +674,7 @@ bool AppInitSanityChecks() /** Initialize divi. * @pre Parameters should be parsed and config file should be read. */ -bool AppInit2(boost::thread_group& threadGroup) +bool InitializeDivi(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER @@ -749,15 +749,15 @@ bool AppInit2(boost::thread_group& threadGroup) // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (SoftSetBoolArg("-listen", true)) - LogPrintf("AppInit2 : parameter interaction: -bind or -whitebind set -> setting -listen=1\n"); + LogPrintf("InitializeDivi : parameter interaction: -bind or -whitebind set -> setting -listen=1\n"); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (SoftSetBoolArg("-dnsseed", false)) - LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -connect set -> setting -dnsseed=0\n"); if (SoftSetBoolArg("-listen", false)) - LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -connect set -> setting -listen=0\n"); } if (mapArgs.count("-proxy")) { @@ -770,40 +770,40 @@ bool AppInit2(boost::thread_group& threadGroup) LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); // to protect privacy, do not discover addresses by default if (SoftSetBoolArg("-discover", false)) - LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -discover=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -proxy set -> setting -discover=0\n"); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (SoftSetBoolArg("-upnp", false)) - LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -upnp=0\n"); if (SoftSetBoolArg("-discover", false)) - LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -discover=0\n"); if (SoftSetBoolArg("-listenonion", false)) - LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -listenonion=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -listenonion=0\n"); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others if (SoftSetBoolArg("-discover", false)) - LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -externalip set -> setting -discover=0\n"); } if (GetBoolArg("-salvagewallet", false)) { // Rewrite just private keys: rescan to find transactions if (SoftSetBoolArg("-rescan", true)) - LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); + LogPrintf("InitializeDivi : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); } // -zapwallettx implies a rescan if (GetBoolArg("-zapwallettxes", false)) { if (SoftSetBoolArg("-rescan", true)) - LogPrintf("AppInit2 : parameter interaction: -zapwallettxes= -> setting -rescan=1\n"); + LogPrintf("InitializeDivi : parameter interaction: -zapwallettxes= -> setting -rescan=1\n"); } if (!GetBoolArg("-enableswifttx", fEnableSwiftTX)) { if (SoftSetArg("-swifttxdepth", 0)) - LogPrintf("AppInit2 : parameter interaction: -enableswifttx=false -> setting -nSwiftTXDepth=0\n"); + LogPrintf("InitializeDivi : parameter interaction: -enableswifttx=false -> setting -nSwiftTXDepth=0\n"); } if (mapArgs.count("-reservebalance")) { @@ -870,7 +870,7 @@ bool AppInit2(boost::thread_group& threadGroup) if (fDisableWallet) { #endif if (SoftSetBoolArg("-staking", false)) - LogPrintf("AppInit2 : parameter interaction: wallet functionality not enabled -> setting -staking=0\n"); + LogPrintf("InitializeDivi : parameter interaction: wallet functionality not enabled -> setting -staking=0\n"); #ifdef ENABLE_WALLET } #endif diff --git a/divi/src/init.h b/divi/src/init.h index 36300eade..f59b61593 100644 --- a/divi/src/init.h +++ b/divi/src/init.h @@ -21,7 +21,7 @@ void StartShutdown(); bool ShutdownRequested(); void Shutdown(); void PrepareShutdown(); -bool AppInit2(boost::thread_group& threadGroup); +bool InitializeDivi(boost::thread_group& threadGroup); /** The help message mode determines what help message to show */ enum HelpMessageMode { diff --git a/divi/src/qt/divi.cpp b/divi/src/qt/divi.cpp index b3701c575..37ecf49a9 100644 --- a/divi/src/qt/divi.cpp +++ b/divi/src/qt/divi.cpp @@ -269,8 +269,8 @@ void BitcoinCore::initialize() execute_restart = true; try { - qDebug() << __func__ << ": Running AppInit2 in thread"; - int rv = AppInit2(threadGroup); + qDebug() << __func__ << ": Running InitializeDivi in thread"; + int rv = InitializeDivi(threadGroup); if (rv) { /* Start a dummy RPC thread if no RPC thread is active yet * to handle timeouts. From 6a865270f82539e8b12edafbfa47218690ce29f1 Mon Sep 17 00:00:00 2001 From: galp Date: Mon, 17 Feb 2020 13:42:25 -0700 Subject: [PATCH 14/25] Remove useless comment --- divi/src/init.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index e54b0f2bd..b3e478182 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -671,9 +671,6 @@ bool AppInitSanityChecks() return true; } -/** Initialize divi. - * @pre Parameters should be parsed and config file should be read. - */ bool InitializeDivi(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup From 3f1b21aa4fc9b59972e399f6c62eee04c24491bf Mon Sep 17 00:00:00 2001 From: galp Date: Tue, 18 Feb 2020 13:31:34 -0700 Subject: [PATCH 15/25] Extract the setting of networking parameters --- divi/src/init.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index b3e478182..1be15ab6a 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -671,6 +671,53 @@ bool AppInitSanityChecks() return true; } +void SetNetworkingParameters() +{ + if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { + // when specifying an explicit binding address, you want to listen on it + // even when -connect or -proxy is specified + if (SoftSetBoolArg("-listen", true)) + LogPrintf("InitializeDivi : parameter interaction: -bind or -whitebind set -> setting -listen=1\n"); + } + + if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { + // when only connecting to trusted nodes, do not seed via DNS, or listen by default + if (SoftSetBoolArg("-dnsseed", false)) + LogPrintf("InitializeDivi : parameter interaction: -connect set -> setting -dnsseed=0\n"); + if (SoftSetBoolArg("-listen", false)) + LogPrintf("InitializeDivi : parameter interaction: -connect set -> setting -listen=0\n"); + } + + if (mapArgs.count("-proxy")) { + // to protect privacy, do not listen by default if a default proxy server is specified + if (SoftSetBoolArg("-listen", false)) + LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); + // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 + // to listen locally, so don't rely on this happening through -listen below. + if (SoftSetBoolArg("-upnp", false)) + LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); + // to protect privacy, do not discover addresses by default + if (SoftSetBoolArg("-discover", false)) + LogPrintf("InitializeDivi : parameter interaction: -proxy set -> setting -discover=0\n"); + } + + if (!GetBoolArg("-listen", true)) { + // do not map ports or try to retrieve public IP when not listening (pointless) + if (SoftSetBoolArg("-upnp", false)) + LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -upnp=0\n"); + if (SoftSetBoolArg("-discover", false)) + LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -discover=0\n"); + if (SoftSetBoolArg("-listenonion", false)) + LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -listenonion=0\n"); + } + + if (mapArgs.count("-externalip")) { + // if an explicit public IP is specified, do not try to find others + if (SoftSetBoolArg("-discover", false)) + LogPrintf("InitializeDivi : parameter interaction: -externalip set -> setting -discover=0\n"); + } +} + bool InitializeDivi(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup From be159ee5c921d9d35902760dc4df6a8f43fffaf7 Mon Sep 17 00:00:00 2001 From: galp Date: Tue, 18 Feb 2020 13:50:11 -0700 Subject: [PATCH 16/25] Replace extracted function --- divi/src/init.cpp | 44 +------------------------------------------- 1 file changed, 1 insertion(+), 43 deletions(-) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index 1be15ab6a..78419737e 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -789,49 +789,7 @@ bool InitializeDivi(boost::thread_group& threadGroup) fLogTimestamps = GetBoolArg("-logtimestamps", true); fLogIPs = GetBoolArg("-logips", false); - if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { - // when specifying an explicit binding address, you want to listen on it - // even when -connect or -proxy is specified - if (SoftSetBoolArg("-listen", true)) - LogPrintf("InitializeDivi : parameter interaction: -bind or -whitebind set -> setting -listen=1\n"); - } - - if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { - // when only connecting to trusted nodes, do not seed via DNS, or listen by default - if (SoftSetBoolArg("-dnsseed", false)) - LogPrintf("InitializeDivi : parameter interaction: -connect set -> setting -dnsseed=0\n"); - if (SoftSetBoolArg("-listen", false)) - LogPrintf("InitializeDivi : parameter interaction: -connect set -> setting -listen=0\n"); - } - - if (mapArgs.count("-proxy")) { - // to protect privacy, do not listen by default if a default proxy server is specified - if (SoftSetBoolArg("-listen", false)) - LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); - // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 - // to listen locally, so don't rely on this happening through -listen below. - if (SoftSetBoolArg("-upnp", false)) - LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); - // to protect privacy, do not discover addresses by default - if (SoftSetBoolArg("-discover", false)) - LogPrintf("InitializeDivi : parameter interaction: -proxy set -> setting -discover=0\n"); - } - - if (!GetBoolArg("-listen", true)) { - // do not map ports or try to retrieve public IP when not listening (pointless) - if (SoftSetBoolArg("-upnp", false)) - LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -upnp=0\n"); - if (SoftSetBoolArg("-discover", false)) - LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -discover=0\n"); - if (SoftSetBoolArg("-listenonion", false)) - LogPrintf("InitializeDivi : parameter interaction: -listen=0 -> setting -listenonion=0\n"); - } - - if (mapArgs.count("-externalip")) { - // if an explicit public IP is specified, do not try to find others - if (SoftSetBoolArg("-discover", false)) - LogPrintf("InitializeDivi : parameter interaction: -externalip set -> setting -discover=0\n"); - } + SetNetworkingParameters(); if (GetBoolArg("-salvagewallet", false)) { // Rewrite just private keys: rescan to find transactions From 4f2caf3240b8e31d5b7c58b0cd287f0f7feba8e1 Mon Sep 17 00:00:00 2001 From: galp Date: Tue, 18 Feb 2020 13:53:24 -0700 Subject: [PATCH 17/25] Extract function --- divi/src/init.cpp | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index 78419737e..e33fe1276 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -718,6 +718,34 @@ void SetNetworkingParameters() } } +bool EnableWalletFeatures() +{ + if (GetBoolArg("-salvagewallet", false)) { + // Rewrite just private keys: rescan to find transactions + if (SoftSetBoolArg("-rescan", true)) + LogPrintf("InitializeDivi : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); + } + + // -zapwallettx implies a rescan + if (GetBoolArg("-zapwallettxes", false)) { + if (SoftSetBoolArg("-rescan", true)) + LogPrintf("InitializeDivi : parameter interaction: -zapwallettxes= -> setting -rescan=1\n"); + } + + if (!GetBoolArg("-enableswifttx", fEnableSwiftTX)) { + if (SoftSetArg("-swifttxdepth", 0)) + LogPrintf("InitializeDivi : parameter interaction: -enableswifttx=false -> setting -nSwiftTXDepth=0\n"); + } + + if (mapArgs.count("-reservebalance")) { + if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) { + InitError(_("Invalid amount for -reservebalance=")); + return false; + } + } + return true; +} + bool InitializeDivi(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup From 052333fcb8a9e45e40a13a838d68c3dd53be0a23 Mon Sep 17 00:00:00 2001 From: galp Date: Tue, 18 Feb 2020 13:58:02 -0700 Subject: [PATCH 18/25] Replace extracted function --- divi/src/init.cpp | 25 +++---------------------- 1 file changed, 3 insertions(+), 22 deletions(-) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index e33fe1276..78719a32f 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -819,28 +819,9 @@ bool InitializeDivi(boost::thread_group& threadGroup) SetNetworkingParameters(); - if (GetBoolArg("-salvagewallet", false)) { - // Rewrite just private keys: rescan to find transactions - if (SoftSetBoolArg("-rescan", true)) - LogPrintf("InitializeDivi : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); - } - - // -zapwallettx implies a rescan - if (GetBoolArg("-zapwallettxes", false)) { - if (SoftSetBoolArg("-rescan", true)) - LogPrintf("InitializeDivi : parameter interaction: -zapwallettxes= -> setting -rescan=1\n"); - } - - if (!GetBoolArg("-enableswifttx", fEnableSwiftTX)) { - if (SoftSetArg("-swifttxdepth", 0)) - LogPrintf("InitializeDivi : parameter interaction: -enableswifttx=false -> setting -nSwiftTXDepth=0\n"); - } - - if (mapArgs.count("-reservebalance")) { - if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) { - InitError(_("Invalid amount for -reservebalance=")); - return false; - } + if(!EnableWalletFeatures()) + { + return false; } // Make sure enough file descriptors are available From af0a37f6f19a1b70b207428b604b7f46d06639dd Mon Sep 17 00:00:00 2001 From: galp Date: Wed, 19 Feb 2020 14:28:33 -0700 Subject: [PATCH 19/25] Replicate function --- divi/src/init.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index 78719a32f..6ffd28d98 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -746,6 +746,20 @@ bool EnableWalletFeatures() return true; } +bool SetMaxConnectionsAndFileDescriptors(int& nFD) +{ + int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1); + nMaxConnections = GetArg("-maxconnections", 125); + nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); + nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); + if (nFD < MIN_CORE_FILEDESCRIPTORS) + return InitError(_("Not enough file descriptors available.")); + if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) + nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; + + return true; +} + bool InitializeDivi(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup From 7f40e445e3a59076b2380e4592bbd1e22cfc12cc Mon Sep 17 00:00:00 2001 From: galp Date: Wed, 19 Feb 2020 14:34:43 -0700 Subject: [PATCH 20/25] Extract function --- divi/src/init.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index 6ffd28d98..3c438f62f 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -839,14 +839,11 @@ bool InitializeDivi(boost::thread_group& threadGroup) } // Make sure enough file descriptors are available - int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1); - nMaxConnections = GetArg("-maxconnections", 125); - nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); - int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); - if (nFD < MIN_CORE_FILEDESCRIPTORS) - return InitError(_("Not enough file descriptors available.")); - if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) - nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; + int nFD; + if(!SetMaxConnectionsAndFileDescriptors(nFD)) + { + return false; + } // ********************************************************* Step 3: parameter-to-internal-flags From 547a778c7a1f46cb89d0eabdf7c9d636a3c9f3ef Mon Sep 17 00:00:00 2001 From: galp Date: Wed, 19 Feb 2020 14:35:05 -0700 Subject: [PATCH 21/25] Rename variable --- divi/src/init.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/divi/src/init.cpp b/divi/src/init.cpp index 3c438f62f..ff8c25c21 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -839,8 +839,8 @@ bool InitializeDivi(boost::thread_group& threadGroup) } // Make sure enough file descriptors are available - int nFD; - if(!SetMaxConnectionsAndFileDescriptors(nFD)) + int numberOfFileDescriptors; + if(!SetMaxConnectionsAndFileDescriptors(numberOfFileDescriptors)) { return false; } @@ -1002,7 +1002,7 @@ bool InitializeDivi(boost::thread_group& threadGroup) LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Using data directory %s\n", strDataDir); LogPrintf("Using config file %s\n", GetConfigFile().string()); - LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); + LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, numberOfFileDescriptors); std::ostringstream strErrors; LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); From 4e8f6a8b968bca5b557fd5127d6269c75332351f Mon Sep 17 00:00:00 2001 From: galp Date: Fri, 21 Feb 2020 11:25:18 -0700 Subject: [PATCH 22/25] Strip info after building --- .../contrib/gitian-descriptors/gitian-win.yml | 38 ++++++++----------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/divi/contrib/gitian-descriptors/gitian-win.yml b/divi/contrib/gitian-descriptors/gitian-win.yml index c3fc1a8a4..cad7d3fb9 100644 --- a/divi/contrib/gitian-descriptors/gitian-win.yml +++ b/divi/contrib/gitian-descriptors/gitian-win.yml @@ -105,7 +105,7 @@ script: | BASEPREFIX=`pwd`/depends # Build dependencies for each host for i in $HOSTS; do - make ${MAKEOPTS} -C ${BASEPREFIX} HOST="${i}" + make ${MAKEOPTS} NO_QT=1 -C ${BASEPREFIX} HOST="${i}" done # Faketime for binaries @@ -144,29 +144,23 @@ script: | CONFIG_SITE=${BASEPREFIX}/${i}/share/config.site ./configure --prefix=/ --disable-ccache --disable-maintainer-mode --disable-dependency-tracking ${CONFIGFLAGS} CFLAGS="${HOST_CFLAGS}" CXXFLAGS="${HOST_CXXFLAGS}" make ${MAKEOPTS} - mkdir -p $OUTDIR/bin/${DISTNAME}-${i} - cp `pwd`/src/divi*.exe $OUTDIR/bin/${DISTNAME}-${i} - zip -r $OUTDIR/${DISTNAME}-${i}.zip $OUTDIR/bin/${DISTNAME}-${i} - #make deploy - #make install DESTDIR=${INSTALLPATH} - #cp -f divi-*setup*.exe $OUTDIR/ + make install DESTDIR=${INSTALLPATH} cd installed - # mv ${DISTNAME}/bin/*.dll ${DISTNAME}/lib/ # temporarily disabled for Zerocoin - # find . -name "lib*.la" -delete # temporarily disabled for Zerocoin - # find . -name "lib*.a" -delete # temporarily disabled for Zerocoin + + mkdir -p $OUTDIR/${DISTNAME}-${i} rm -rf ${DISTNAME}/lib/pkgconfig - #find ${DISTNAME}/bin -type f -executable -exec ${i}-objcopy --only-keep-debug {} {}.dbg \; -exec ${i}-strip -s {} \; -exec ${i}-objcopy --add-gnu-debuglink={}.dbg {} \; - # find ${DISTNAME}/lib -type f -exec ${i}-objcopy --only-keep-debug {} {}.dbg \; -exec ${i}-strip -s {} \; -exec ${i}-objcopy --add-gnu-debuglink={}.dbg {} \; - # find ${DISTNAME} -not -name "*.dbg" -type f | sort | zip -X@ ${OUTDIR}/${DISTNAME}-${i}.zip - # find ${DISTNAME} -name "*.dbg" -type f | sort | zip -X@ ${OUTDIR}/${DISTNAME}-${i}-debug.zip + find ${DISTNAME}/bin -type f -executable -exec ${i}-objcopy --only-keep-debug {} {}.dbg \; -exec ${i}-strip -s {} \; -exec ${i}-objcopy --add-gnu-debuglink={}.dbg {} \; + find . -name "lib*.la" -delete # temporarily disabled for Zerocoin + find . -name "lib*.a" -delete # temporarily disabled for Zerocoin + find ${DISTNAME}/lib -type f -exec ${i}-objcopy --only-keep-debug {} {}.dbg \; -exec ${i}-strip -s {} \; -exec ${i}-objcopy --add-gnu-debuglink={}.dbg {} \; + find ${DISTNAME} -not -name "*.dbg" -type f | sort | zip -X@ ${OUTDIR}/${DISTNAME}-${i}.zip + find ${DISTNAME} -name "*.dbg" -type f | sort | zip -X@ ${OUTDIR}/${DISTNAME}-${i}-debug.zip + cd ../../ rm -rf distsrc-${i} done - rm -rf $OUTDIR/bin - #cd $OUTDIR - #rename 's/-setup\.exe$/-setup-unsigned.exe/' *-setup.exe - #find . -name "*-setup-unsigned.exe" | sort | tar --no-recursion --mode='u+rw,go+r-w,a+X' --owner=0 --group=0 -c -T - | gzip -9n > ${OUTDIR}/${DISTNAME}-win-unsigned.tar.gz - #mv ${OUTDIR}/${DISTNAME}-x86_64-*-debug.zip ${OUTDIR}/${DISTNAME}-win64-debug.zip - #mv ${OUTDIR}/${DISTNAME}-i686-*-debug.zip ${OUTDIR}/${DISTNAME}-win32-debug.zip - #mv ${OUTDIR}/${DISTNAME}-x86_64-*.zip ${OUTDIR}/${DISTNAME}-win64.zip - #mv ${OUTDIR}/${DISTNAME}-i686-*.zip ${OUTDIR}/${DISTNAME}-win32.zip + + mv ${OUTDIR}/${DISTNAME}-x86_64-*-debug.zip ${OUTDIR}/${DISTNAME}-win64-debug.zip + mv ${OUTDIR}/${DISTNAME}-i686-*-debug.zip ${OUTDIR}/${DISTNAME}-win32-debug.zip + mv ${OUTDIR}/${DISTNAME}-x86_64-*.zip ${OUTDIR}/${DISTNAME}-win64.zip + mv ${OUTDIR}/${DISTNAME}-i686-*.zip ${OUTDIR}/${DISTNAME}-win32.zip From c98fec49eec7ab60d97592530fc6eee1024ac8f8 Mon Sep 17 00:00:00 2001 From: Octal Date: Wed, 26 Feb 2020 15:15:38 -0600 Subject: [PATCH 23/25] Test Fee Rates Move Tests --- divi/src/test/wallet_tests.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/divi/src/test/wallet_tests.cpp b/divi/src/test/wallet_tests.cpp index 90fc470e0..2db9fccbc 100644 --- a/divi/src/test/wallet_tests.cpp +++ b/divi/src/test/wallet_tests.cpp @@ -305,4 +305,17 @@ BOOST_AUTO_TEST_CASE(coin_selection_tests) empty_wallet(); } +BOOST_AUTO_TEST_CASE(check_if_charging_correct_amount_per_kilobyte) +{ + size_t kilobytes = 1000u; + CFeeRate feeRate = CFeeRate( 1 ); + + CAmount actualFee = feeRate.GetFee( kilobytes ); + + CAmount expectedFee = 1; + + BOOST_CHECK_EQUAL(actualFee, expectedFee); +} + + BOOST_AUTO_TEST_SUITE_END() From 9a8611d1b551b53ae85e09386bdd9666e7f3d336 Mon Sep 17 00:00:00 2001 From: galp Date: Thu, 27 Feb 2020 09:12:58 -0700 Subject: [PATCH 24/25] Remove reference to non-existent folder --- divi/contrib/gitian-descriptors/gitian-win.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/divi/contrib/gitian-descriptors/gitian-win.yml b/divi/contrib/gitian-descriptors/gitian-win.yml index cad7d3fb9..995b1e400 100644 --- a/divi/contrib/gitian-descriptors/gitian-win.yml +++ b/divi/contrib/gitian-descriptors/gitian-win.yml @@ -152,7 +152,6 @@ script: | find ${DISTNAME}/bin -type f -executable -exec ${i}-objcopy --only-keep-debug {} {}.dbg \; -exec ${i}-strip -s {} \; -exec ${i}-objcopy --add-gnu-debuglink={}.dbg {} \; find . -name "lib*.la" -delete # temporarily disabled for Zerocoin find . -name "lib*.a" -delete # temporarily disabled for Zerocoin - find ${DISTNAME}/lib -type f -exec ${i}-objcopy --only-keep-debug {} {}.dbg \; -exec ${i}-strip -s {} \; -exec ${i}-objcopy --add-gnu-debuglink={}.dbg {} \; find ${DISTNAME} -not -name "*.dbg" -type f | sort | zip -X@ ${OUTDIR}/${DISTNAME}-${i}.zip find ${DISTNAME} -name "*.dbg" -type f | sort | zip -X@ ${OUTDIR}/${DISTNAME}-${i}-debug.zip From 425c5de9421c19361be6693af12f4712cc51d416 Mon Sep 17 00:00:00 2001 From: galp Date: Thu, 27 Feb 2020 11:21:58 -0700 Subject: [PATCH 25/25] Revert "Revert "rpc_wallet_tests.cpp: fix memory violation error"" This reverts commit d446ef5948e3cbd437b05f74758a471c42828fd4. --- .travis.yml | 4 +- divi/DockerfileWithTests | 29 ++ divi/src/Makefile.am | 1 + divi/src/blockmap.h | 11 + divi/src/chainparams.cpp | 27 +- divi/src/chainparams.cpp.original | 445 ------------------ divi/src/chainparams.h | 5 +- divi/src/checkpoint_data.h | 21 + divi/src/checkpoints.cpp | 81 ++-- divi/src/checkpoints.h | 55 ++- divi/src/crypter.cpp | 1 + divi/src/crypto/aes.cpp | 2 + divi/src/init.cpp | 2 +- divi/src/main.cpp | 20 +- divi/src/main.h | 10 +- divi/src/qt/clientmodel.cpp | 3 +- divi/src/rpcblockchain.cpp | 3 +- divi/src/test/Checkpoints_tests.cpp | 218 ++++++++- divi/src/test/DoS_tests.cpp | 8 +- divi/src/test/coins_tests.cpp | 3 + divi/src/test/crypto_tests.cpp | 3 + .../test/data/bitcoin-deferred-util-test.json | 12 + divi/src/test/data/bitcoin-util-test.json | 10 - divi/src/test/key_tests.cpp | 6 + divi/src/test/main_tests.cpp | 53 +-- divi/src/test/miner_tests.cpp | 4 +- divi/src/test/multisig_tests.cpp | 60 ++- divi/src/test/rpc_tests.cpp | 3 +- divi/src/test/rpc_wallet_tests.cpp | 10 +- divi/src/test/sanity_tests.cpp | 6 + divi/src/test/script_P2SH_tests.cpp | 8 +- divi/src/test/script_tests.cpp | 20 +- divi/src/test/sighash_tests.cpp | 6 +- divi/src/test/sigopcount_tests.cpp | 10 +- divi/src/test/skiplist_tests.cpp | 3 + divi/src/test/test_only.h | 6 + divi/src/test/transaction_tests.cpp | 98 +++- divi/src/test/util_tests.cpp | 4 + .../test/zerocoin_implementation_tests.cpp | 11 +- divi/src/wallet.cpp | 10 +- 40 files changed, 643 insertions(+), 649 deletions(-) create mode 100644 divi/DockerfileWithTests create mode 100644 divi/src/blockmap.h delete mode 100644 divi/src/chainparams.cpp.original create mode 100644 divi/src/checkpoint_data.h create mode 100644 divi/src/test/data/bitcoin-deferred-util-test.json create mode 100644 divi/src/test/test_only.h diff --git a/.travis.yml b/.travis.yml index ba393d1ca..ed719cd4a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,5 +8,7 @@ services: script: # Compile from source - cd divi - - docker build -t divi -f Dockerfile . + - docker build -t divi -f DockerfileWithTests . - docker run divi +after_failure: + - cat ./src/test-suite.log \ No newline at end of file diff --git a/divi/DockerfileWithTests b/divi/DockerfileWithTests new file mode 100644 index 000000000..591d73040 --- /dev/null +++ b/divi/DockerfileWithTests @@ -0,0 +1,29 @@ +FROM ubuntu:bionic + +RUN apt-get update +RUN apt-get install apt-utils -y +RUN apt-get install bsdmainutils -y +RUN apt-get install software-properties-common -y +RUN add-apt-repository ppa:bitcoin/bitcoin -y +RUN apt-get update + +RUN apt-get install make -y +RUN apt-get install gcc -y +RUN apt-get install g++ -y +RUN apt-get install pkg-config -y +RUN apt-get install autoconf -y +RUN apt-get install libtool -y +RUN apt-get install libboost-all-dev -y +RUN apt-get install libssl1.0-dev -y +RUN apt-get install libevent-dev -y +RUN apt-get install libdb4.8-dev libdb4.8++-dev -y + +WORKDIR /app +COPY . . + +RUN ./autogen.sh +RUN ./configure --without-gui NO_QT=1 +RUN make NO_QT=1 +RUN make check + +CMD ["bash"] diff --git a/divi/src/Makefile.am b/divi/src/Makefile.am index a8ba4f6c6..c4e9fe4ed 100644 --- a/divi/src/Makefile.am +++ b/divi/src/Makefile.am @@ -258,6 +258,7 @@ libbitcoin_wallet_a_SOURCES = \ obfuscation.cpp \ obfuscation-relay.cpp \ db.cpp \ + crypto/aes.cpp \ crypter.cpp \ swifttx.cpp \ masternode.cpp \ diff --git a/divi/src/blockmap.h b/divi/src/blockmap.h new file mode 100644 index 000000000..7db03b7f6 --- /dev/null +++ b/divi/src/blockmap.h @@ -0,0 +1,11 @@ +#ifndef BLOCK_MAP_H +#define BLOCK_MAP_H +#include "chain.h" +#include +struct BlockHasher { + size_t operator()(const uint256& hash) const { return hash.GetLow64(); } +}; +class BlockMap: public boost::unordered_map +{ +}; +#endif // BLOCK_MAP_H \ No newline at end of file diff --git a/divi/src/chainparams.cpp b/divi/src/chainparams.cpp index a41aa0b78..72607de33 100755 --- a/divi/src/chainparams.cpp +++ b/divi/src/chainparams.cpp @@ -103,12 +103,12 @@ void MineGenesis(CBlock genesis) // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions -static Checkpoints::MapCheckpoints mapCheckpoints = +static MapCheckpoints mapCheckpoints = boost::assign::map_list_of (0, uint256("0x00000e258596876664989374c7ee36445cf5f4f80889af415cc32478214394ea")) (100, uint256("0x000000275b2b4a8af2c93ebdfd36ef8dd8c8ec710072bcc388ecbf5d0c8d3f9d")); -static const Checkpoints::CCheckpointData data = { +static const CCheckpointData data = { &mapCheckpoints, 1538069980, // * UNIX timestamp of last checkpoint block 100, // * total number of transactions between genesis and last checkpoint @@ -116,17 +116,17 @@ static const Checkpoints::CCheckpointData data = { 2000 // * estimated number of transactions per day after checkpoint }; -static Checkpoints::MapCheckpoints mapCheckpointsTestnet = +static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of(0, uint256("0x000000f351b8525f459c879f1e249b5d3d421b378ac6b760ea8b8e0df2454f33")); -static const Checkpoints::CCheckpointData dataTestnet = { +static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1537971708, 0, 250}; -static Checkpoints::MapCheckpoints mapCheckpointsRegtest = +static MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of(0, uint256("0x79ba0d9d15d36edee8d07cc300379ec65ab7e12765acd883e870aa618dbcc1a8")); -static const Checkpoints::CCheckpointData dataRegtest = { +static const CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 1518723178, 0, @@ -275,7 +275,7 @@ class CMainParams : public CChainParams nBudget_Fee_Confirmations = 6; // Number of confirmations for the finalization fee } - const Checkpoints::CCheckpointData& Checkpoints() const + const CCheckpointData& Checkpoints() const { return data; } @@ -414,7 +414,7 @@ class CBetaParams : public CChainParams nBudget_Fee_Confirmations = 6; // Number of confirmations for the finalization fee } - const Checkpoints::CCheckpointData& Checkpoints() const + const CCheckpointData& Checkpoints() const { return data; } @@ -534,7 +534,7 @@ class CTestNetParams : public CMainParams nBudget_Fee_Confirmations = 3; // Number of confirmations for the finalization fee. We have to make this very short // here because we only have a 8 block finalization window on testnet } - const Checkpoints::CCheckpointData& Checkpoints() const + const CCheckpointData& Checkpoints() const { return dataTestnet; } @@ -591,7 +591,7 @@ class CRegTestParams : public CTestNetParams fMineBlocksOnDemand = true; fTestnetToBeDeprecatedFieldRPC = false; } - const Checkpoints::CCheckpointData& Checkpoints() const + const CCheckpointData& Checkpoints() const { return dataRegtest; } @@ -619,7 +619,7 @@ class CUnitTestParams : public CMainParams, public CModifiableParams fMineBlocksOnDemand = true; } - const Checkpoints::CCheckpointData& Checkpoints() const + const CCheckpointData& Checkpoints() const { // UnitTest share the same checkpoints as MAIN return data; @@ -652,6 +652,11 @@ const CChainParams& Params() return *pCurrentParams; } +const CCheckpointData& GetCurrentChainCheckpoints() +{ + return Params().Checkpoints(); +} + CChainParams& Params(CBaseChainParams::Network network) { switch (network) { diff --git a/divi/src/chainparams.cpp.original b/divi/src/chainparams.cpp.original deleted file mode 100644 index af3e0576c..000000000 --- a/divi/src/chainparams.cpp.original +++ /dev/null @@ -1,445 +0,0 @@ -// Copyright (c) 2010 Satoshi Nakamoto -// Copyright (c) 2009-2014 The Bitcoin developers -// Copyright (c) 2014-2015 The Dash developers -// Copyright (c) 2015-2017 The PIVX Developers -// Distributed under the MIT software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include "libzerocoin/Params.h" -#include "chainparams.h" -#include "random.h" -#include "util.h" -#include "utilstrencodings.h" - -#include - -#include - -using namespace std; -using namespace boost::assign; - -struct SeedSpec6 { - uint8_t addr[16]; - uint16_t port; -}; - -#include "chainparamsseeds.h" - -/** - * Main network - */ - -//! Convert the pnSeeds6 array into usable address objects. -static void convertSeed6(std::vector& vSeedsOut, const SeedSpec6* data, unsigned int count) -{ - // It'll only connect to one or two seed nodes because once it connects, - // it'll get a pile of addresses with newer timestamps. - // Seed nodes are given a random 'last seen time' of between one and two - // weeks ago. - const int64_t nOneWeek = 7 * 24 * 60 * 60; - for (unsigned int i = 0; i < count; i++) { - struct in6_addr ip; - memcpy(&ip, data[i].addr, sizeof(ip)); - CAddress addr(CService(ip, data[i].port)); - addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; - vSeedsOut.push_back(addr); - } -} - -// What makes a good checkpoint block? -// + Is surrounded by blocks with reasonable timestamps -// (no blocks before with a timestamp after, none after with -// timestamp before) -// + Contains no strange transactions -static Checkpoints::MapCheckpoints mapCheckpoints = - boost::assign::map_list_of - (259201, uint256("1c9121bf9329a6234bfd1ea2d91515f19cd96990725265253f4b164283ade5dd")) - (424998, uint256("f31e381eedb0ed3ed65fcc98cc71f36012bee32e8efd017c4f9fb0620fd35f6b")) - (616764, uint256("29dd0bd1c59484f290896687b4ffb6a49afa5c498caf61967c69a541f8191557")) //first block to use modifierV2 - (623933, uint256("c7aafa648a0f1450157dc93bd4d7448913a85b7448f803b4ab970d91fc2a7da7")) - (791150, uint256("8e76f462e4e82d1bd21cb72e1ce1567d4ddda2390f26074ffd1f5d9c270e5e50")) - (795000, uint256("4423cceeb9fd574137a18733416275a70fdf95283cc79ad976ca399aa424a443")) - (863787, uint256("5b2482eca24caf2a46bb22e0545db7b7037282733faa3a42ec20542509999a64")) - (863795, uint256("2ad866818c4866e0d555181daccc628056216c0db431f88a825e84ed4f469067")) - (863805, uint256("a755bd9a22b63c70d3db474f4b2b61a1f86c835b290a081bb3ec1ba2103eb4cb")) - (867733, uint256("03b26296bf693de5782c76843d2fb649cb66d4b05550c6a79c047ff7e1c3ae15")) - (879650, uint256("227e1d2b738b6cd83c46d1d64617934ec899d77cee34336a56e61b71acd10bb2")) - (895400, uint256("7796a0274a608fac12d400198174e50beda992c1d522e52e5b95b884bc1beac6"))//block that serial# range is enforced - (895991, uint256("d53013ed7ea5c325b9696c95e07667d6858f8ff7ee13fecfa90827bf3c9ae316"))//network split here - (908000, uint256("202708f8c289b676fceb832a079ff6b308a28608339acbf7584de533619d014d")); -static const Checkpoints::CCheckpointData data = { - &mapCheckpoints, - 1510948627, // * UNIX timestamp of last checkpoint block - 1842739, // * total number of transactions between genesis and last checkpoint - // (the tx=... number in the SetBestChain debug.log lines) - 2000 // * estimated number of transactions per day after checkpoint -}; - -static Checkpoints::MapCheckpoints mapCheckpointsTestnet = - boost::assign::map_list_of(0, uint256("0x001")); -static const Checkpoints::CCheckpointData dataTestnet = { - &mapCheckpointsTestnet, - 1740710, - 0, - 250}; - -static Checkpoints::MapCheckpoints mapCheckpointsRegtest = - boost::assign::map_list_of(0, uint256("0x001")); -static const Checkpoints::CCheckpointData dataRegtest = { - &mapCheckpointsRegtest, - 1454124731, - 0, - 100}; - -libzerocoin::ZerocoinParams* CChainParams::Zerocoin_Params() const -{ - assert(this); - static CBigNum bnTrustedModulus(zerocoinModulus); - static libzerocoin::ZerocoinParams ZCParams = libzerocoin::ZerocoinParams(bnTrustedModulus); - - return &ZCParams; -} - -class CMainParams : public CChainParams -{ -public: - CMainParams() - { - networkID = CBaseChainParams::MAIN; - strNetworkID = "main"; - /** - * The message start string is designed to be unlikely to occur in normal data. - * The characters are rarely used upper ASCII, not valid as UTF-8, and produce - * a large 4-byte int at any alignment. - */ - pchMessageStart[0] = 0x90; - pchMessageStart[1] = 0xc4; - pchMessageStart[2] = 0xfd; - pchMessageStart[3] = 0xe9; - vAlertPubKey = ParseHex("0000098d3ba6ba6e7423fa5cbd6a89e0a9a5348f88d332b44a5cb1a8b7ed2c1eaa335fc8dc4f012cb8241cc0bdafd6ca70c5f5448916e4e6f511bcd746ed57dc50"); - nDefaultPort = 51472; - bnProofOfWorkLimit = ~uint256(0) >> 20; // DIVI starting difficulty is 1 / 2^12 - nSubsidyHalvingInterval = 210000; - nMaxReorganizationDepth = 100; - nEnforceBlockUpgradeMajority = 750; - nRejectBlockOutdatedMajority = 950; - nToCheckBlockUpgradeMajority = 1000; - nMinerThreads = 0; - nTargetTimespan = 1 * 60; // DIVI: 1 day - nTargetSpacing = 1 * 60; // DIVI: 1 minute - nMaturity = 100; - nMasternodeCountDrift = 20; - nMaxMoneyOut = 21000000 * COIN; - - /** Height or Time Based Activations **/ - nLastPOWBlock = 259200; - nModifierUpdateBlock = 615800; - nZerocoinStartHeight = 863787; - nZerocoinStartTime = 1508214600; // October 17, 2017 4:30:00 AM - nBlockEnforceSerialRange = 895400; //Enforce serial range starting this block - nBlockRecalculateAccumulators = 908000; //Trigger a recalculation of accumulators - nBlockFirstFraudulent = 891737; //First block that bad serials emerged - nBlockLastGoodCheckpoint = 891730; //Last valid accumulator checkpoint - nBlockEnforceInvalidUTXO = 902850; //Start enforcing the invalid UTXO's - - /** - * Build the genesis block. Note that the output of the genesis coinbase cannot - * be spent as it did not originally exist in the database. - * - * CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1) - * CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0) - * CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73) - * CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF) - * vMerkleTree: e0028e - */ - const char* pszTimestamp = "U.S. News & World Report Jan 28 2016 With His Absence, Trump Dominates Another Debate"; - CMutableTransaction txNew; - txNew.vin.resize(1); - txNew.vout.resize(1); - txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); - txNew.vout[0].nValue = 250 * COIN; - txNew.vout[0].scriptPubKey = CScript() << ParseHex("04c10e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9") << OP_CHECKSIG; - genesis.vtx.push_back(txNew); - genesis.hashPrevBlock = 0; - genesis.hashMerkleRoot = genesis.BuildMerkleTree(); - genesis.nVersion = 1; - genesis.nTime = 1454124731; - genesis.nBits = 0x1e0ffff0; - genesis.nNonce = 2402015; - - hashGenesisBlock = genesis.GetHash(); - assert(hashGenesisBlock == uint256("0x0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818")); - assert(genesis.hashMerkleRoot == uint256("0x1b2ef6e2f28be914103a277377ae7729dcd125dfeb8bf97bd5964ba72b6dc39b")); - - vSeeds.push_back(CDNSSeedData("fuzzbawls.pw", "divi.seed.fuzzbawls.pw")); // Primary DNS Seeder from Fuzzbawls - vSeeds.push_back(CDNSSeedData("fuzzbawls.pw", "divi.seed2.fuzzbawls.pw")); // Secondary DNS Seeder from Fuzzbawls - vSeeds.push_back(CDNSSeedData("coin-server.com", "coin-server.com")); // Single node address - vSeeds.push_back(CDNSSeedData("s3v3nh4cks.ddns.net", "s3v3nh4cks.ddns.net")); // Single node address - vSeeds.push_back(CDNSSeedData("178.254.23.111", "178.254.23.111")); // Single node address - - base58Prefixes[PUBKEY_ADDRESS] = std::vector(1, 30); - base58Prefixes[SCRIPT_ADDRESS] = std::vector(1, 13); - base58Prefixes[SECRET_KEY] = std::vector(1, 212); - base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x02)(0x2D)(0x25)(0x33).convert_to_container >(); - base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x02)(0x21)(0x31)(0x2B).convert_to_container >(); - // BIP44 coin type is from https://github.com/satoshilabs/slips/blob/master/slip-0044.md - base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x77).convert_to_container >(); - - convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); - - fRequireRPCPassword = true; - fMiningRequiresPeers = true; - fAllowMinDifficultyBlocks = false; - fDefaultConsistencyChecks = false; - fRequireStandard = true; - fMineBlocksOnDemand = false; - fSkipProofOfWorkCheck = false; - fTestnetToBeDeprecatedFieldRPC = false; - fHeadersFirstSyncingActive = false; - - nPoolMaxTransactions = 3; - strSporkKey = "04B433E6598390C992F4F022F20D3B4CBBE691652EE7C48243B81701CBDB7CC7D7BF0EE09E154E6FCBF2043D65AF4E9E97B89B5DBAF830D83B9B7F469A6C45A717"; - strObfuscationPoolDummyAddress = "D87q2gC9j6nNrnzCsg4aY6bHMLsT9nUhEw"; - nStartMasternodePayments = 1403728576; //Wed, 25 Jun 2014 20:36:16 GMT - - /** Zerocoin */ - zerocoinModulus = "25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784" - "4069182906412495150821892985591491761845028084891200728449926873928072877767359714183472702618963750149718246911" - "6507761337985909570009733045974880842840179742910064245869181719511874612151517265463228221686998754918242243363" - "7259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133" - "8441436038339044149526344321901146575444541784240209246165157233507787077498171257724679629263863563732899121548" - "31438167899885040445364023527381951378636564391212010397122822120720357"; - nMaxZerocoinSpendsPerTransaction = 7; // Assume about 20kb each - nMinZerocoinMintFee = 1 * CENT; //high fee required for zerocoin mints - nMintRequiredConfirmations = 20; //the maximum amount of confirmations until accumulated in 19 - nRequiredAccumulation = 2; - nDefaultSecurityLevel = 100; //full security level for accumulators - nZerocoinHeaderVersion = 4; //Block headers must be this version once zerocoin is active - nBudget_Fee_Confirmations = 6; // Number of confirmations for the finalization fee - } - - const Checkpoints::CCheckpointData& Checkpoints() const - { - return data; - } -}; -static CMainParams mainParams; - -/** - * Testnet (v3) - */ -class CTestNetParams : public CMainParams -{ -public: - CTestNetParams() - { - networkID = CBaseChainParams::TESTNET; - strNetworkID = "test"; - pchMessageStart[0] = 0x45; - pchMessageStart[1] = 0x76; - pchMessageStart[2] = 0x65; - pchMessageStart[3] = 0xba; - vAlertPubKey = ParseHex("000010e83b2703ccf322f7dbd62dd5855ac7c10bd055814ce121ba32607d573b8810c02c0582aed05b4deb9c4b77b26d92428c61256cd42774babea0a073b2ed0c9"); - nDefaultPort = 51474; - nEnforceBlockUpgradeMajority = 51; - nRejectBlockOutdatedMajority = 75; - nToCheckBlockUpgradeMajority = 100; - nMinerThreads = 0; - nTargetTimespan = 1 * 60; // DIVI: 1 day - nTargetSpacing = 1 * 60; // DIVI: 1 minute - nLastPOWBlock = 200; - nMaturity = 15; - nMasternodeCountDrift = 4; - nModifierUpdateBlock = 51197; //approx Mon, 17 Apr 2017 04:00:00 GMT - nMaxMoneyOut = 43199500 * COIN; - nZerocoinStartHeight = 201576; - nZerocoinStartTime = 1501776000; - nBlockEnforceSerialRange = 1; //Enforce serial range starting this block - nBlockRecalculateAccumulators = 9908000; //Trigger a recalculation of accumulators - nBlockFirstFraudulent = 9891737; //First block that bad serials emerged - nBlockLastGoodCheckpoint = 9891730; //Last valid accumulator checkpoint - nBlockEnforceInvalidUTXO = 9902850; //Start enforcing the invalid UTXO's - - //! Modify the testnet genesis block so the timestamp is valid for a later start. - genesis.nTime = 1454124731; - genesis.nNonce = 2402015; - - hashGenesisBlock = genesis.GetHash(); - assert(hashGenesisBlock == uint256("0x0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818")); - - vFixedSeeds.clear(); - vSeeds.clear(); - vSeeds.push_back(CDNSSeedData("fuzzbawls.pw", "divi-testnet.seed.fuzzbawls.pw")); - vSeeds.push_back(CDNSSeedData("fuzzbawls.pw", "divi-testnet.seed2.fuzzbawls.pw")); - vSeeds.push_back(CDNSSeedData("s3v3nh4cks.ddns.net", "s3v3nh4cks.ddns.net")); - vSeeds.push_back(CDNSSeedData("88.198.192.110", "88.198.192.110")); - - base58Prefixes[PUBKEY_ADDRESS] = std::vector(1, 139); // Testnet divi addresses start with 'x' or 'y' - base58Prefixes[SCRIPT_ADDRESS] = std::vector(1, 19); // Testnet divi script addresses start with '8' or '9' - base58Prefixes[SECRET_KEY] = std::vector(1, 239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) - // Testnet divi BIP32 pubkeys start with 'DRKV' - base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container >(); - // Testnet divi BIP32 prvkeys start with 'DRKP' - base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container >(); - // Testnet divi BIP44 coin type is '1' (All coin's testnet default) - base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container >(); - - convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); - - fRequireRPCPassword = true; - fMiningRequiresPeers = true; - fAllowMinDifficultyBlocks = true; - fDefaultConsistencyChecks = false; - fRequireStandard = false; - fMineBlocksOnDemand = false; - fTestnetToBeDeprecatedFieldRPC = true; - - nPoolMaxTransactions = 2; - strSporkKey = "04348C2F50F90267E64FACC65BFDC9D0EB147D090872FB97ABAE92E9A36E6CA60983E28E741F8E7277B11A7479B626AC115BA31463AC48178A5075C5A9319D4A38"; - strObfuscationPoolDummyAddress = "y57cqfGRkekRyDRNeJiLtYVEbvhXrNbmox"; - nStartMasternodePayments = 1420837558; //Fri, 09 Jan 2015 21:05:58 GMT - nBudget_Fee_Confirmations = 3; // Number of confirmations for the finalization fee. We have to make this very short - // here because we only have a 8 block finalization window on testnet - } - const Checkpoints::CCheckpointData& Checkpoints() const - { - return dataTestnet; - } -}; -static CTestNetParams testNetParams; - -/** - * Regression test - */ -class CRegTestParams : public CTestNetParams -{ -public: - CRegTestParams() - { - networkID = CBaseChainParams::REGTEST; - strNetworkID = "regtest"; - strNetworkID = "regtest"; - pchMessageStart[0] = 0xa1; - pchMessageStart[1] = 0xcf; - pchMessageStart[2] = 0x7e; - pchMessageStart[3] = 0xac; - nSubsidyHalvingInterval = 150; - nEnforceBlockUpgradeMajority = 750; - nRejectBlockOutdatedMajority = 950; - nToCheckBlockUpgradeMajority = 1000; - nMinerThreads = 1; - nTargetTimespan = 24 * 60 * 60; // Divi: 1 day - nTargetSpacing = 1 * 60; // Divi: 1 minutes - bnProofOfWorkLimit = ~uint256(0) >> 1; - genesis.nTime = 1454124731; - genesis.nBits = 0x207fffff; - genesis.nNonce = 12345; - - hashGenesisBlock = genesis.GetHash(); - nDefaultPort = 51476; - assert(hashGenesisBlock == uint256("0x4f023a2120d9127b21bbad01724fdb79b519f593f2a85b60d3d79160ec5f29df")); - - vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds. - vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds. - - fRequireRPCPassword = false; - fMiningRequiresPeers = false; - fAllowMinDifficultyBlocks = true; - fDefaultConsistencyChecks = true; - fRequireStandard = false; - fMineBlocksOnDemand = true; - fTestnetToBeDeprecatedFieldRPC = false; - } - const Checkpoints::CCheckpointData& Checkpoints() const - { - return dataRegtest; - } -}; -static CRegTestParams regTestParams; - -/** - * Unit test - */ -class CUnitTestParams : public CMainParams, public CModifiableParams -{ -public: - CUnitTestParams() - { - networkID = CBaseChainParams::UNITTEST; - strNetworkID = "unittest"; - nDefaultPort = 51478; - vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds. - vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds. - - fRequireRPCPassword = false; - fMiningRequiresPeers = false; - fDefaultConsistencyChecks = true; - fAllowMinDifficultyBlocks = false; - fMineBlocksOnDemand = true; - } - - const Checkpoints::CCheckpointData& Checkpoints() const - { - // UnitTest share the same checkpoints as MAIN - return data; - } - - //! Published setters to allow changing values in unit test cases - virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval = anSubsidyHalvingInterval; } - virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority = anEnforceBlockUpgradeMajority; } - virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority = anRejectBlockOutdatedMajority; } - virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority = anToCheckBlockUpgradeMajority; } - virtual void setDefaultConsistencyChecks(bool afDefaultConsistencyChecks) { fDefaultConsistencyChecks = afDefaultConsistencyChecks; } - virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks = afAllowMinDifficultyBlocks; } - virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; } -}; -static CUnitTestParams unitTestParams; - - -static CChainParams* pCurrentParams = 0; - -CModifiableParams* ModifiableParams() -{ - assert(pCurrentParams); - assert(pCurrentParams == &unitTestParams); - return (CModifiableParams*)&unitTestParams; -} - -const CChainParams& Params() -{ - assert(pCurrentParams); - return *pCurrentParams; -} - -CChainParams& Params(CBaseChainParams::Network network) -{ - switch (network) { - case CBaseChainParams::MAIN: - return mainParams; - case CBaseChainParams::TESTNET: - return testNetParams; - case CBaseChainParams::REGTEST: - return regTestParams; - case CBaseChainParams::UNITTEST: - return unitTestParams; - default: - assert(false && "Unimplemented network"); - return mainParams; - } -} - -void SelectParams(CBaseChainParams::Network network) -{ - SelectBaseParams(network); - pCurrentParams = &Params(network); -} - -bool SelectParamsFromCommandLine() -{ - CBaseChainParams::Network network = NetworkIdFromCommandLine(); - if (network == CBaseChainParams::MAX_NETWORK_TYPES) - return false; - - SelectParams(network); - return true; -} diff --git a/divi/src/chainparams.h b/divi/src/chainparams.h index 1f892130b..f543a03cc 100644 --- a/divi/src/chainparams.h +++ b/divi/src/chainparams.h @@ -9,7 +9,7 @@ #define BITCOIN_CHAINPARAMS_H #include "chainparamsbase.h" -#include "checkpoints.h" +#include "checkpoint_data.h" #include "primitives/block.h" #include "protocol.h" #include "uint256.h" @@ -93,7 +93,7 @@ class CChainParams const std::vector& DNSSeeds() const { return vSeeds; } const std::vector& Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } const std::vector& FixedSeeds() const { return vFixedSeeds; } - virtual const Checkpoints::CCheckpointData& Checkpoints() const = 0; + virtual const CCheckpointData& Checkpoints() const = 0; int PoolMaxTransactions() const { return nPoolMaxTransactions; } std::string SporkKey() const { return strSporkKey; } std::string ObfuscationPoolDummyAddress() const { return strObfuscationPoolDummyAddress; } @@ -223,6 +223,7 @@ class CModifiableParams * outside of the unit tests. */ const CChainParams& Params(); +const CCheckpointData& GetCurrentChainCheckpoints(); /** Return parameters for the given network. */ CChainParams& Params(CBaseChainParams::Network network); diff --git a/divi/src/checkpoint_data.h b/divi/src/checkpoint_data.h new file mode 100644 index 000000000..33e586378 --- /dev/null +++ b/divi/src/checkpoint_data.h @@ -0,0 +1,21 @@ +// Copyright (c) 2009-2014 The Bitcoin developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CHECKPOINT_DATA_H +#define BITCOIN_CHECKPOINT_DATA_H + +#include "uint256.h" +#include + +typedef std::map MapCheckpoints; +class CCheckpointData { +public: + const MapCheckpoints* mapCheckpoints; + int64_t nTimeLastCheckpoint; + int64_t nTransactionsLastCheckpoint; + double fTransactionsPerDay; +}; + + +#endif // BITCOIN_CHECKPOINT_DATA_H diff --git a/divi/src/checkpoints.cpp b/divi/src/checkpoints.cpp index fd22d6f44..a5e463ce1 100644 --- a/divi/src/checkpoints.cpp +++ b/divi/src/checkpoints.cpp @@ -6,16 +6,15 @@ #include "checkpoints.h" +#include "blockmap.h" #include "chainparams.h" -#include "main.h" #include "uint256.h" #include #include -namespace Checkpoints -{ + /** * How many times we expect transactions after the last checkpoint to * be slower. This number is a compromise, as it can't be accurate for @@ -23,16 +22,27 @@ namespace Checkpoints * can be up to 20, while when downloading from a slow network with a * fast multicore CPU, it won't be much higher than 1. */ -static const double SIGCHECK_VERIFICATION_FACTOR = 5.0; +bool CCheckpointServices::fEnabled = true; -bool fEnabled = true; +CCheckpointServices::CCheckpointServices( + CheckpointDataProvider checkpointDataProvider + ): checkpointDataProvider_(checkpointDataProvider) +{ +} + +CCheckpointServices::CCheckpointServices( + const CCheckpointData& staticCheckpointData + ): checkpointDataProvider_( + InternalCheckpointDataProvider([&staticCheckpointData]()-> const CCheckpointData&{return staticCheckpointData;} )) +{ +} -bool CheckBlock(int nHeight, const uint256& hash, bool fMatchesCheckpoint) +bool CCheckpointServices::CheckBlock(int nHeight, const uint256& hash, bool fMatchesCheckpoint) const { - if (!fEnabled) + if (!CCheckpointServices::fEnabled) return true; - const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; + const MapCheckpoints& checkpoints = *checkpointDataProvider_().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); // If looking for an exact match, then return false @@ -41,54 +51,59 @@ bool CheckBlock(int nHeight, const uint256& hash, bool fMatchesCheckpoint) } //! Guess how far we are in the verification process at the given block index -double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks) +double CCheckpointServices::GuessVerificationProgress(CBlockIndex* pindex, bool useConservativeEstimate) const { + static const double CONSERVATIVE_VERIFICATION_FACTOR = 5.0; if (pindex == NULL) return 0.0; int64_t nNow = time(NULL); - double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0; + double conservativeCheckVerificationFactor = useConservativeEstimate ? CONSERVATIVE_VERIFICATION_FACTOR : 1.0; double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkpoint, and - // fSigcheckVerificationFactor per transaction after. - - const CCheckpointData& data = Params().Checkpoints(); - - if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { - double nCheapBefore = pindex->nChainTx; - double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; - double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint) / 86400.0 * data.fTransactionsPerDay; - fWorkBefore = nCheapBefore; - fWorkAfter = nCheapAfter + nExpensiveAfter * fSigcheckVerificationFactor; + // conservativeCheckVerificationFactor per transaction after. + + const CCheckpointData& data = checkpointDataProvider_(); + bool lessTxsThanLastCheckpoint = pindex->nChainTx <= data.nTransactionsLastCheckpoint; + if (lessTxsThanLastCheckpoint) { + double transactionCountAtBlock = pindex->nChainTx; + double additionalTransactionsToReachCheckpoint = data.nTransactionsLastCheckpoint - pindex->nChainTx; + double estimatedAdditionalTransactionsMissing = (nNow - data.nTimeLastCheckpoint) / 86400.0 * data.fTransactionsPerDay; + fWorkBefore = transactionCountAtBlock; + fWorkAfter = additionalTransactionsToReachCheckpoint + estimatedAdditionalTransactionsMissing * conservativeCheckVerificationFactor; } else { - double nCheapBefore = data.nTransactionsLastCheckpoint; - double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; - double nExpensiveAfter = (nNow - pindex->GetBlockTime()) / 86400.0 * data.fTransactionsPerDay; - fWorkBefore = nCheapBefore + nExpensiveBefore * fSigcheckVerificationFactor; - fWorkAfter = nExpensiveAfter * fSigcheckVerificationFactor; + double transactionCountAtLastCheckpoint = data.nTransactionsLastCheckpoint; + double additionalTransactionsToReachBlock = pindex->nChainTx - data.nTransactionsLastCheckpoint; + double estimatedAdditionalTransactionsMissing = (nNow - pindex->GetBlockTime()) / 86400.0 * data.fTransactionsPerDay; + fWorkBefore = transactionCountAtLastCheckpoint + additionalTransactionsToReachBlock * conservativeCheckVerificationFactor; + fWorkAfter = estimatedAdditionalTransactionsMissing * conservativeCheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } -int GetTotalBlocksEstimate() +int CCheckpointServices::GetTotalBlocksEstimate() const { - if (!fEnabled) + if (!CCheckpointServices::fEnabled) return 0; - const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; + const MapCheckpoints& checkpoints = *checkpointDataProvider_().mapCheckpoints; + if(checkpoints.empty()) + { + return 0; + } return checkpoints.rbegin()->first; } -CBlockIndex* GetLastCheckpoint() +CBlockIndex* CCheckpointServices::GetLastCheckpoint(const BlockMap& mapBlockIndex) const { - if (!fEnabled) + if (!CCheckpointServices::fEnabled) return NULL; - const MapCheckpoints& checkpoints = *Params().Checkpoints().mapCheckpoints; + const MapCheckpoints& checkpoints = *checkpointDataProvider_().mapCheckpoints; BOOST_REVERSE_FOREACH (const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; @@ -97,6 +112,4 @@ CBlockIndex* GetLastCheckpoint() return t->second; } return NULL; -} - -} // namespace Checkpoints +} \ No newline at end of file diff --git a/divi/src/checkpoints.h b/divi/src/checkpoints.h index 2fdb2c978..7a5495e86 100644 --- a/divi/src/checkpoints.h +++ b/divi/src/checkpoints.h @@ -6,39 +6,42 @@ #define BITCOIN_CHECKPOINTS_H #include "uint256.h" - -#include +#include "checkpoint_data.h" +#include class CBlockIndex; +class CChainParams; +class BlockMap; /** * Block-chain checkpoints are compiled-in sanity checks. * They are updated every release or three. */ -namespace Checkpoints +class CCheckpointServices { -typedef std::map MapCheckpoints; - -struct CCheckpointData { - const MapCheckpoints* mapCheckpoints; - int64_t nTimeLastCheckpoint; - int64_t nTransactionsLastCheckpoint; - double fTransactionsPerDay; -}; - -//! Returns true if block passes checkpoint checks -bool CheckBlock(int nHeight, const uint256& hash, bool fMatchesCheckpoint = false); - -//! Return conservative estimate of total number of blocks, 0 if unknown -int GetTotalBlocksEstimate(); - -//! Returns last CBlockIndex* in mapBlockIndex that is a checkpoint -CBlockIndex* GetLastCheckpoint(); - -double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks = true); - -extern bool fEnabled; - -} //namespace Checkpoints +public: + typedef const CCheckpointData& (*CheckpointDataProvider)(); +private: + typedef std::function InternalCheckpointDataProvider; + InternalCheckpointDataProvider checkpointDataProvider_; +public: + explicit CCheckpointServices( + CheckpointDataProvider checkpointDataProvider); + explicit CCheckpointServices( + const CCheckpointData& staticCheckpointData); + + //! Returns true if block passes checkpoint checks + bool CheckBlock(int nHeight, const uint256& hash, bool fMatchesCheckpoint = false) const; + + //! Return conservative estimate of total number of blocks, 0 if unknown + int GetTotalBlocksEstimate() const; + + //! Returns last CBlockIndex* in mapBlockIndex that is a checkpoint + CBlockIndex* GetLastCheckpoint(const BlockMap& mapBlockIndex) const; + + double GuessVerificationProgress(CBlockIndex* pindex, bool fSigchecks = true) const; + + static bool fEnabled; +}; //class CCheckpoints #endif // BITCOIN_CHECKPOINTS_H diff --git a/divi/src/crypter.cpp b/divi/src/crypter.cpp index 7523fa905..7b8427d11 100644 --- a/divi/src/crypter.cpp +++ b/divi/src/crypter.cpp @@ -5,6 +5,7 @@ #include "crypter.h" #include "crypto/aes.h" + #include "crypto/sha512.h" #include "script/script.h" #include "script/standard.h" diff --git a/divi/src/crypto/aes.cpp b/divi/src/crypto/aes.cpp index a8c8be9d6..3e9d657d1 100644 --- a/divi/src/crypto/aes.cpp +++ b/divi/src/crypto/aes.cpp @@ -4,6 +4,8 @@ #include "aes.h" #include "crypto/common.h" +#include +#include #include #include diff --git a/divi/src/init.cpp b/divi/src/init.cpp index ff82e7a3d..bc8a528e3 100644 --- a/divi/src/init.cpp +++ b/divi/src/init.cpp @@ -855,7 +855,7 @@ bool AppInit2(boost::thread_group& threadGroup) // Checkmempool and checkblockindex default to true in regtest mode mempool.setSanityCheck(GetBoolArg("-checkmempool", Params().DefaultConsistencyChecks())); fCheckBlockIndex = GetBoolArg("-checkblockindex", Params().DefaultConsistencyChecks()); - Checkpoints::fEnabled = GetBoolArg("-checkpoints", true); + CCheckpointServices::fEnabled = GetBoolArg("-checkpoints", true); // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); diff --git a/divi/src/main.cpp b/divi/src/main.cpp index 94a0d6ff0..dc920d3a7 100755 --- a/divi/src/main.cpp +++ b/divi/src/main.cpp @@ -85,6 +85,8 @@ unsigned int nStakeMinAge = 60 * 60; unsigned int nStakeMaxAge = 60 * 60 * 24 * 7; int64_t nReserveBalance = 0; +CCheckpointServices checkpointsVerifier(GetCurrentChainCheckpoints); + /** Fees smaller than this (in duffs) are considered zero fee (for relaying and mining) * We are ~100 times smaller then bitcoin now (2015-06-23), set minRelayTxFee only 10 times higher * so it's still 10 times lower comparing to bitcoin. @@ -2291,7 +2293,7 @@ CBlockRewards GetBlockSubsidity(int nHeight) bool IsInitialBlockDownload() //2446 { LOCK(cs_main); - if (fImporting || fReindex || fVerifyingBlocks || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate()) + if (fImporting || fReindex || fVerifyingBlocks || chainActive.Height() < checkpointsVerifier.GetTotalBlocksEstimate()) return true; static bool lockIBDState = false; if (lockIBDState) @@ -3198,7 +3200,7 @@ bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pin return state.DoS(100, error("ConnectBlock() : PoW period ended"), REJECT_INVALID, "PoW-ended"); - bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(); + bool fScriptChecks = pindex->nHeight >= checkpointsVerifier.GetTotalBlocksEstimate(); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. @@ -3609,7 +3611,7 @@ void static UpdateTip(CBlockIndex* pindexNew) LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n", chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0), (unsigned long)chainActive.Tip()->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), - Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize()); + checkpointsVerifier.GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize()); cvBlockChange.notify_all(); @@ -4027,7 +4029,7 @@ bool ActivateBestChain(CValidationState& state, CBlock* pblock, bool fAlreadyChe if (!fInitialDownload) { uint256 hashNewTip = pindexNewTip->GetBlockHash(); // Relay inventory, but don't relay old inventory during initial block download. - int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); + int nBlockEstimate = checkpointsVerifier.GetTotalBlocksEstimate(); { LOCK(cs_vNodes); BOOST_FOREACH (CNode* pnode, vNodes) @@ -4542,12 +4544,12 @@ bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& sta } // Check that the block chain matches the known block chain up to a checkpoint - if (!Checkpoints::CheckBlock(nHeight, hash)) + if (!checkpointsVerifier.CheckBlock(nHeight, hash)) return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight), REJECT_CHECKPOINT, "checkpoint mismatch"); // Don't accept any forks from the main chain prior to last checkpoint - CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(); + CBlockIndex* pcheckpoint = checkpointsVerifier.GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && nHeight < pcheckpoint->nHeight) return state.DoS(0, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight)); @@ -4644,7 +4646,7 @@ bool AcceptBlockHeader(const CBlock& block, CValidationState& state, CBlockIndex pindexPrev = (*mi).second; if (pindexPrev->nStatus & BLOCK_FAILED_MASK) { //If this "invalid" block is an exact match from the checkpoints, then reconsider it - if (pindex && Checkpoints::CheckBlock(pindex->nHeight - 1, block.hashPrevBlock, true)) { + if (pindex && checkpointsVerifier.CheckBlock(pindex->nHeight - 1, block.hashPrevBlock, true)) { LogPrintf("%s : Reconsidering block %s height %d\n", __func__, pindexPrev->GetBlockHash().GetHex(), pindexPrev->nHeight); CValidationState statePrev; ReconsiderBlock(statePrev, pindexPrev); @@ -4687,7 +4689,7 @@ bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, pindexPrev = (*mi).second; if (pindexPrev->nStatus & BLOCK_FAILED_MASK) { //If this "invalid" block is an exact match from the checkpoints, then reconsider it - if (Checkpoints::CheckBlock(pindexPrev->nHeight, block.hashPrevBlock, true)) { + if (checkpointsVerifier.CheckBlock(pindexPrev->nHeight, block.hashPrevBlock, true)) { LogPrintf("%s : Reconsidering block %s height %d\n", __func__, pindexPrev->GetBlockHash().GetHex(), pindexPrev->nHeight); CValidationState statePrev; ReconsiderBlock(statePrev, pindexPrev); @@ -5177,7 +5179,7 @@ bool static LoadBlockIndexDB(string& strError) LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n", chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), - Checkpoints::GuessVerificationProgress(chainActive.Tip())); + checkpointsVerifier.GuessVerificationProgress(chainActive.Tip())); return true; } diff --git a/divi/src/main.h b/divi/src/main.h index b0125de15..81391ff67 100644 --- a/divi/src/main.h +++ b/divi/src/main.h @@ -13,6 +13,7 @@ #endif #include "amount.h" +#include "blockmap.h" #include "chain.h" #include "chainparams.h" #include "coins.h" @@ -124,14 +125,10 @@ static const unsigned char REJECT_DUST = 0x41; static const unsigned char REJECT_INSUFFICIENTFEE = 0x42; static const unsigned char REJECT_CHECKPOINT = 0x43; -struct BlockHasher { - size_t operator()(const uint256& hash) const { return hash.GetLow64(); } -}; extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern CTxMemPool mempool; -typedef boost::unordered_map BlockMap; extern BlockMap mapBlockIndex; extern uint64_t nLastBlockTx; extern uint64_t nLastBlockSize; @@ -270,6 +267,11 @@ struct CBlockRewards { const CAmount nCharityReward; const CAmount nLotteryReward; const CAmount nProposalsReward; + + CAmount total() const + { + return nStakeReward + nMasternodeReward + nTreasuryReward + nCharityReward + nLotteryReward + nProposalsReward; + } }; CBlockRewards GetBlockSubsidity(int nHeight); diff --git a/divi/src/qt/clientmodel.cpp b/divi/src/qt/clientmodel.cpp index b0de8f3fb..7da25e287 100644 --- a/divi/src/qt/clientmodel.cpp +++ b/divi/src/qt/clientmodel.cpp @@ -110,8 +110,9 @@ QDateTime ClientModel::getLastBlockDate() const double ClientModel::getVerificationProgress() const { + static const CCheckpoints checkpointsService(GetCurrentChainCheckpoints); LOCK(cs_main); - return Checkpoints::GuessVerificationProgress(chainActive.Tip()); + return checkpointsService.GuessVerificationProgress(chainActive.Tip()); } void ClientModel::updateTimer() diff --git a/divi/src/rpcblockchain.cpp b/divi/src/rpcblockchain.cpp index d600887e5..f0a3e9076 100644 --- a/divi/src/rpcblockchain.cpp +++ b/divi/src/rpcblockchain.cpp @@ -493,6 +493,7 @@ Value verifychain(const Array& params, bool fHelp) Value getblockchaininfo(const Array& params, bool fHelp) { + static const CCheckpointServices checkpointsVerifier(GetCurrentChainCheckpoints); if (fHelp || params.size() != 0) throw runtime_error( "getblockchaininfo\n" @@ -516,7 +517,7 @@ Value getblockchaininfo(const Array& params, bool fHelp) obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); - obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(chainActive.Tip()))); + obj.push_back(Pair("verificationprogress", checkpointsVerifier.GuessVerificationProgress(chainActive.Tip()))); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); return obj; } diff --git a/divi/src/test/Checkpoints_tests.cpp b/divi/src/test/Checkpoints_tests.cpp index 05a495b22..a5919cf4e 100644 --- a/divi/src/test/Checkpoints_tests.cpp +++ b/divi/src/test/Checkpoints_tests.cpp @@ -8,31 +8,223 @@ #include "checkpoints.h" +#include "blockmap.h" #include "uint256.h" +#include "random.h" #include - +#include "test_only.h" using namespace std; +class TestCase +{ +private: + int maxNumberOfBlocks = 800000; +public: + TestCase() + { + checkpointCount_ = 0; + data_ = CCheckpointData({&mapCheckpoints_,0,0,0}); + } + + TestCase(unsigned int numberOfCheckpoints): checkpointCount_(numberOfCheckpoints) + { + for(unsigned j = 0; j < numberOfCheckpoints; j++) + { + blockIndices_.push_back(GetRandInt(maxNumberOfBlocks)); + blockHashes_.push_back(GetRandHash()); + mapCheckpoints_.insert({blockIndices_.back(),blockHashes_.back()}); + } + data_ = CCheckpointData({&mapCheckpoints_,0,0,0}); + } + + void addCheckpoint( + int blockIndex, + uint256 hash, + int64_t checkpointTime = 0, + int64_t transactionsAtCheckpoint = 0) + { + const double transactionsPerDay = 86400.0; + blockIndices_.push_back(blockIndex); + blockHashes_.push_back(hash); + mapCheckpoints_.insert({blockIndex,hash}); + + data_.nTimeLastCheckpoint = checkpointTime; + data_.nTransactionsLastCheckpoint = transactionsAtCheckpoint; + data_.fTransactionsPerDay = + (data_.nTransactionsLastCheckpoint>0)? data_.nTransactionsLastCheckpoint/static_cast(data_.nTimeLastCheckpoint/transactionsPerDay): int64_t(0); + } + + const CCheckpointData& checkpoint_data() const + { + return data_; + } + const std::pair getRandomCorrectCheckpoint() + { + return *std::next(mapCheckpoints_.begin(), (abs(GetRandInt(maxNumberOfBlocks)) % checkpointCount_)); + } + const std::pair,bool> getRandomCheckpointAndExpectation() + { + std::pair randomPair({GetRandInt(maxNumberOfBlocks),GetRandHash()}); + auto it = mapCheckpoints_.find(randomPair.first); + if(it != mapCheckpoints_.end()) + { + return std::make_pair(randomPair, randomPair.second == it->second); + } + return std::make_pair(randomPair, true); + } + + unsigned int checkpointCount_; + std::vector blockIndices_; + std::vector blockHashes_; + MapCheckpoints mapCheckpoints_; + CCheckpointData data_; +}; + BOOST_AUTO_TEST_SUITE(Checkpoints_tests) -BOOST_AUTO_TEST_CASE(sanity) +BOOST_AUTO_TEST_CASE(allCheckpointsWillBeAccountedFor) +{ // Exhaustive search for correctness + unsigned checkpointCount = static_cast(abs(GetRandInt(25)))+10u; + TestCase testSetup(checkpointCount); + CCheckpointServices checkpointsService( testSetup.checkpoint_data() ); + + for(const auto& checkpoint: testSetup.mapCheckpoints_) + { + BOOST_CHECK(checkpointsService.CheckBlock(checkpoint.first,checkpoint.second)); + } +} + +BOOST_AUTO_TEST_CASE(randomCheckpointsWillBeCorrectlyHandled) +{ + unsigned checkpointCount = static_cast(abs(GetRandInt(25)))+10u; + TestCase testSetup(checkpointCount); + CCheckpointServices checkpointsService( testSetup.checkpoint_data() ); + + for(unsigned checkpointIndex = 0; checkpointIndex < checkpointCount; checkpointIndex++) + { + std::pair,bool> checkpointAndExpectation = testSetup.getRandomCheckpointAndExpectation(); + std::pair checkpoint = checkpointAndExpectation.first; + BOOST_CHECK(checkpointsService.CheckBlock(checkpoint.first,checkpoint.second) == checkpointAndExpectation.second); + } +} + + +BOOST_AUTO_TEST_CASE(deliberatlyIncorrectCheckpointsWillBeCorrectlyHandled) +{ + unsigned checkpointCount = static_cast(abs(GetRandInt(25)))+10u; + TestCase testSetup(checkpointCount); + CCheckpointServices checkpointsService( testSetup.checkpoint_data() ); + + for(unsigned checkpointIndex = 0; checkpointIndex < checkpointCount; checkpointIndex++) + { + std::pair checkpoint = testSetup.getRandomCorrectCheckpoint(); + uint256 correctHash = checkpoint.second; + while(checkpoint.second == correctHash) + { + checkpoint.second = GetRandHash(); + } + BOOST_CHECK(!checkpointsService.CheckBlock(checkpoint.first,checkpoint.second)); + } +} + +BOOST_AUTO_TEST_CASE(willNotFailDueToLackOfCheckpoints) +{ + TestCase testSetup(0); + CCheckpointServices checkpointsService( testSetup.checkpoint_data() ); + BlockMap map; + + BOOST_CHECK(checkpointsService.CheckBlock(GetRandInt(25),GetRandHash())); + BOOST_CHECK(checkpointsService.GetTotalBlocksEstimate()==0); + BOOST_CHECK(checkpointsService.GuessVerificationProgress(nullptr)==0.0); + BOOST_CHECK(checkpointsService.GetLastCheckpoint(map)==nullptr); +} + + +BOOST_AUTO_TEST_CASE(willFindLargestHeightAmongstCheckpoints) +{ + unsigned checkpointCount = static_cast(abs(GetRandInt(25)))+10u; + TestCase testSetup(checkpointCount); + CCheckpointServices checkpointsService( testSetup.checkpoint_data() ); + + int highestBlockInCheckpoints = 0; + for(const auto& checkpoint: testSetup.mapCheckpoints_) + { + highestBlockInCheckpoints = std::max(highestBlockInCheckpoints, checkpoint.first); + } + + BOOST_CHECK(checkpointsService.GetTotalBlocksEstimate()==highestBlockInCheckpoints); +} + + +BOOST_AUTO_TEST_CASE(willFindCorrectBlockInMap) { - uint256 p259201 = uint256("0x1c9121bf9329a6234bfd1ea2d91515f19cd96990725265253f4b164283ade5dd"); - uint256 p623933 = uint256("0xc7aafa648a0f1450157dc93bd4d7448913a85b7448f803b4ab970d91fc2a7da7"); - BOOST_CHECK(Checkpoints::CheckBlock(259201, p259201)); - BOOST_CHECK(Checkpoints::CheckBlock(623933, p623933)); + std::shared_ptr sharedBlockIndex = std::make_shared(); + uint256 blockHash = GetRandHash(); + sharedBlockIndex->phashBlock = &blockHash; + sharedBlockIndex->nHeight = GetRandInt(800); + TestCase testSetup; + testSetup.mapCheckpoints_.insert( + std::make_pair(static_cast(sharedBlockIndex->nHeight),sharedBlockIndex->GetBlockHash()) ); + testSetup.data_ = CCheckpointData({&testSetup.mapCheckpoints_,0,0,0}); + + BlockMap map; + map.insert( std::make_pair(sharedBlockIndex->GetBlockHash(),sharedBlockIndex.get()) ); + + CCheckpointServices checkpointsService( testSetup.checkpoint_data() ); + + BOOST_CHECK(checkpointsService.GetLastCheckpoint(map)!=nullptr); + BOOST_CHECK(checkpointsService.GetLastCheckpoint(map)->nHeight == sharedBlockIndex->nHeight); +} + +BOOST_AUTO_TEST_CASE(willEstimateProgressCorrectly) +{ + std::shared_ptr sharedBlockIndex = std::make_shared(); + sharedBlockIndex->nChainTx = 10000; + sharedBlockIndex->nTime = 1580841426u; + + {// _As100PercentWithoutCheckpoints + TestCase testSetup; + CCheckpointServices checkpointsService(testSetup.checkpoint_data()); + double progress = checkpointsService.GuessVerificationProgress(sharedBlockIndex.get(),false); + BOOST_CHECK_CLOSE(progress,1.0, 0.0001); + } + {// _CorrectlyWithcheckpointPrior + TestCase testSetup; + double transactionsAtCheckpoint = static_cast(sharedBlockIndex->nChainTx -1 -abs(GetRandInt(1000))); + int64_t checkpointTimeAtStart = sharedBlockIndex->nTime - 1000000u; + + testSetup.addCheckpoint(GetRandInt(100),GetRandHash(), checkpointTimeAtStart, transactionsAtCheckpoint); + + double transactionsPerDay = testSetup.data_.fTransactionsPerDay; + double secondsPerDay = 86400.0; + double numberOfDays = (static_cast(time(NULL)) - sharedBlockIndex->GetBlockTime())/secondsPerDay; + CCheckpointServices checkpointsService(testSetup.checkpoint_data()); + double initialTxs = static_cast(sharedBlockIndex->nChainTx); + double estimateOfTotalTransactions = initialTxs + static_cast(transactionsPerDay*numberOfDays); + + double progress = checkpointsService.GuessVerificationProgress(sharedBlockIndex.get(),false); + + BOOST_CHECK_CLOSE(progress, initialTxs/estimateOfTotalTransactions, 0.01); + } + {// _CorrectlyWithcheckpointAfter + TestCase testSetup; + double transactionsAtCheckpoint = static_cast(sharedBlockIndex->nChainTx + 1 + abs(GetRandInt(1000))); + int64_t checkpointTimeAtStart = sharedBlockIndex->nTime + 1000000u; + testSetup.addCheckpoint(GetRandInt(100),GetRandHash(), checkpointTimeAtStart, transactionsAtCheckpoint); - // Wrong hashes at checkpoints should fail: - BOOST_CHECK(!Checkpoints::CheckBlock(259201, p623933)); - BOOST_CHECK(!Checkpoints::CheckBlock(623933, p259201)); + double transactionsPerDay = testSetup.data_.fTransactionsPerDay; + double secondsPerDay = 86400.0; + double numberOfDays = (static_cast(time(NULL)) - checkpointTimeAtStart)/secondsPerDay; + CCheckpointServices checkpointsService(testSetup.checkpoint_data()); + double initialTxs = static_cast(sharedBlockIndex->nChainTx); + double estimateOfTotalTransactions = transactionsAtCheckpoint + static_cast(transactionsPerDay*numberOfDays); - // ... but any hash not at a checkpoint should succeed: - BOOST_CHECK(Checkpoints::CheckBlock(259201+1, p623933)); - BOOST_CHECK(Checkpoints::CheckBlock(623933+1, p259201)); + double progress = checkpointsService.GuessVerificationProgress(sharedBlockIndex.get(),false); - BOOST_CHECK(Checkpoints::GetTotalBlocksEstimate() >= 623933); + BOOST_CHECK_CLOSE(progress, initialTxs/estimateOfTotalTransactions, 0.01); + } } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/DoS_tests.cpp b/divi/src/test/DoS_tests.cpp index f9746fdaa..29a8ebe0a 100644 --- a/divi/src/test/DoS_tests.cpp +++ b/divi/src/test/DoS_tests.cpp @@ -23,6 +23,8 @@ #include #include +#include "test_only.h" + // Tests this internal-to-main.cpp method: extern bool AddOrphanTx(const CTransaction& tx, NodeId peer); extern void EraseOrphansFor(NodeId peer); @@ -117,11 +119,14 @@ CTransaction RandomOrphan() BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { + ECCVerifyHandle verificationModule; + ECC_Start(); + CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); - + // 50 orphan transactions: for (int i = 0; i < 50; i++) { @@ -194,6 +199,7 @@ BOOST_AUTO_TEST_CASE(DoS_mapOrphans) LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); BOOST_CHECK(mapOrphanTransactionsByPrev.empty()); + ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/coins_tests.cpp b/divi/src/test/coins_tests.cpp index 3ecd301bc..2916b797b 100644 --- a/divi/src/test/coins_tests.cpp +++ b/divi/src/test/coins_tests.cpp @@ -11,6 +11,9 @@ #include +FastRandomContext random_source; +auto insecure_rand = []() -> uint32_t { return random_source.rand32();}; + namespace { class CCoinsViewTest : public CCoinsView diff --git a/divi/src/test/crypto_tests.cpp b/divi/src/test/crypto_tests.cpp index 26708f507..ff132a0d8 100644 --- a/divi/src/test/crypto_tests.cpp +++ b/divi/src/test/crypto_tests.cpp @@ -19,6 +19,9 @@ BOOST_AUTO_TEST_SUITE(crypto_tests) +FastRandomContext random_source; +auto insecure_rand = []() -> uint32_t { return random_source.rand32();}; + template void TestVector(const Hasher &h, const In &in, const Out &out) { Out hash; diff --git a/divi/src/test/data/bitcoin-deferred-util-test.json b/divi/src/test/data/bitcoin-deferred-util-test.json new file mode 100644 index 000000000..6169bf14f --- /dev/null +++ b/divi/src/test/data/bitcoin-deferred-util-test.json @@ -0,0 +1,12 @@ +[ + { "exec": "./divi-tx", + "args": + ["-create", + "in=4d49a71ec9da436f71ec4ee231d04f292a29cd316f598bb7068feccabdc59485:0", + "set=privatekeys:[\"891ns7GR4owBiozmFa8jDSaJWNZ2q4XoSYdUS2kSNuKJ9BaxLkC\"]", + "set=prevtxs:[{\"txid\":\"4d49a71ec9da436f71ec4ee231d04f292a29cd316f598bb7068feccabdc59485\",\"vout\":0,\"scriptPubKey\":\"4d49a71ec9da436f71ec4ee231d04f292a29cd316f598bb7068feccabdc59485\"}]", + "sign=ALL", + "outaddr=0.001:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"], + "output_cmp": "txcreatesign.hex" + } +] \ No newline at end of file diff --git a/divi/src/test/data/bitcoin-util-test.json b/divi/src/test/data/bitcoin-util-test.json index ddcdc8ab3..cf4f51ef4 100644 --- a/divi/src/test/data/bitcoin-util-test.json +++ b/divi/src/test/data/bitcoin-util-test.json @@ -46,15 +46,5 @@ { "exec": "./divi-tx", "args": ["-create", "outscript=0:"], "output_cmp": "txcreate2.hex" - }, - { "exec": "./divi-tx", - "args": - ["-create", - "in=4d49a71ec9da436f71ec4ee231d04f292a29cd316f598bb7068feccabdc59485:0", - "set=privatekeys:[\"891ns7GR4owBiozmFa8jDSaJWNZ2q4XoSYdUS2kSNuKJ9BaxLkC\"]", - "set=prevtxs:[{\"txid\":\"4d49a71ec9da436f71ec4ee231d04f292a29cd316f598bb7068feccabdc59485\",\"vout\":0,\"scriptPubKey\":\"4d49a71ec9da436f71ec4ee231d04f292a29cd316f598bb7068feccabdc59485\"}]", - "sign=ALL", - "outaddr=0.001:D72dLgywmL73JyTwQBfuU29CADz9yCJ99v"], - "output_cmp": "txcreatesign.hex" } ] diff --git a/divi/src/test/key_tests.cpp b/divi/src/test/key_tests.cpp index 2631abbfc..020d111d7 100644 --- a/divi/src/test/key_tests.cpp +++ b/divi/src/test/key_tests.cpp @@ -14,6 +14,7 @@ #include #include +#include "test_only.h" using namespace std; @@ -62,6 +63,9 @@ BOOST_AUTO_TEST_SUITE(key_tests) BOOST_AUTO_TEST_CASE(key_test1) { + ECCVerifyHandle verificationModule; + ECC_Start(); + CBitcoinSecret bsecret1, bsecret2, bsecret1C, bsecret2C, baddress1; BOOST_CHECK( bsecret1.SetString (strSecret1)); BOOST_CHECK( bsecret2.SetString (strSecret2)); @@ -185,6 +189,8 @@ BOOST_AUTO_TEST_CASE(key_test1) BOOST_CHECK(key2C.SignCompact(hashMsg, detsigc)); BOOST_CHECK(detsig == ParseHex("1b4f304f1b05599f88bc517819f6d43c69503baea5f253c55ea2d791394f7ce0de4f23c0d4c1f4d7a89bf130fed755201d22581911a8a44cf594014794231d325a")); BOOST_CHECK(detsigc == ParseHex("1f4f304f1b05599f88bc517819f6d43c69503baea5f253c55ea2d791394f7ce0de4f23c0d4c1f4d7a89bf130fed755201d22581911a8a44cf594014794231d325a")); + + ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/main_tests.cpp b/divi/src/test/main_tests.cpp index b79fc5c45..e635b9919 100644 --- a/divi/src/test/main_tests.cpp +++ b/divi/src/test/main_tests.cpp @@ -9,43 +9,38 @@ #include +#include +#include "test_only.h" BOOST_AUTO_TEST_SUITE(main_tests) -CAmount nMoneySupplyPoWEnd = 43199500 * COIN; - BOOST_AUTO_TEST_CASE(subsidy_limit_test) { + SelectParams(CBaseChainParams::Network::MAIN); + int numberOfBlocksPerHalving = Params().SubsidyHalvingInterval(); CAmount nSum = 0; - for (int nHeight = 0; nHeight < 1; nHeight += 1) { - /* premine in block 1 (60,001 DIV) */ - CAmount nSubsidy = GetBlockValue(nHeight); - BOOST_CHECK(nSubsidy <= 60001 * COIN); - nSum += nSubsidy; - } - - for (int nHeight = 1; nHeight < 86400; nHeight += 1) { - /* PoW Phase One */ - CAmount nSubsidy = GetBlockValue(nHeight); - BOOST_CHECK(nSubsidy <= 250 * COIN); - nSum += nSubsidy; - } - - for (int nHeight = 86400; nHeight < 151200; nHeight += 1) { - /* PoW Phase Two */ - CAmount nSubsidy = GetBlockValue(nHeight); - BOOST_CHECK(nSubsidy <= 225 * COIN); - nSum += nSubsidy; - } - for (int nHeight = 151200; nHeight < 259200; nHeight += 1) { - /* PoW Phase Two */ - CAmount nSubsidy = GetBlockValue(nHeight); - BOOST_CHECK(nSubsidy <= 45 * COIN); - BOOST_CHECK(MoneyRange(nSubsidy)); + CAmount startingExpectedSubsidy = 1250 * COIN; + CAmount yearlySubsidyReduction = 100 * COIN; + CAmount minimumSubsidy = 250*COIN; + auto expectedSubsidy = [startingExpectedSubsidy,yearlySubsidyReduction,minimumSubsidy](int year)->CAmount{ + return (year>1)? std::max(startingExpectedSubsidy - yearlySubsidyReduction*(year-1),minimumSubsidy): startingExpectedSubsidy; + }; + + for(int nHeight = 0; nHeight < numberOfBlocksPerHalving*13; ++nHeight) + { + CAmount nSubsidy = GetBlockSubsidity(nHeight).total(); + if(nHeight < 2) + { + BOOST_CHECK(nSubsidy == ((nHeight==0)? 50*COIN: Params().premineAmt) ); + } + else + { + BOOST_CHECK_EQUAL(nSubsidy, expectedSubsidy(nHeight/numberOfBlocksPerHalving)); + } + + BOOST_CHECK( nSubsidy==0 || (nSum+nSubsidy > nSum)); nSum += nSubsidy; - BOOST_CHECK(nSum > 0 && nSum <= nMoneySupplyPoWEnd); } - BOOST_CHECK(nSum == 4109975100000000ULL); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/miner_tests.cpp b/divi/src/test/miner_tests.cpp index 38bc8a039..e8dc9007e 100644 --- a/divi/src/test/miner_tests.cpp +++ b/divi/src/test/miner_tests.cpp @@ -58,7 +58,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) uint256 hash; LOCK(cs_main); - Checkpoints::fEnabled = false; + CCheckpoints::fEnabled = false; // Simple block creation, nothing special yet: BOOST_CHECK(pblocktemplate = CreateNewBlock(scriptPubKey, pwalletMain, false)); @@ -261,7 +261,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) BOOST_FOREACH(CTransaction *tx, txFirst) delete tx; - Checkpoints::fEnabled = true; + CCheckpoints::fEnabled = true; } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/multisig_tests.cpp b/divi/src/test/multisig_tests.cpp index 0b5402f2f..d72415ec0 100644 --- a/divi/src/test/multisig_tests.cpp +++ b/divi/src/test/multisig_tests.cpp @@ -19,6 +19,8 @@ #include #include +#include "test_only.h" + using namespace std; using namespace boost::assign; @@ -45,6 +47,9 @@ sign_multisig(CScript scriptPubKey, vector keys, CTransaction transaction, BOOST_AUTO_TEST_CASE(multisig_verify) { + ECCVerifyHandle verificationModule; + ECC_Start(); + unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; ScriptError err; @@ -119,13 +124,14 @@ BOOST_AUTO_TEST_CASE(multisig_verify) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } + s.clear(); s << OP_0 << OP_1; BOOST_CHECK(!VerifyScript(s, a_or_b, flags, MutableTransactionSignatureChecker(&txTo[1], 0), &err)); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_SIG_DER, ScriptErrorString(err)); - for (int i = 0; i < 4; i++) + { for (int j = 0; j < 4; j++) { keys.clear(); @@ -142,13 +148,21 @@ BOOST_AUTO_TEST_CASE(multisig_verify) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } } + } + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(multisig_IsStandard) { + ECCVerifyHandle verificationModule; + ECC_Start(); + CKey key[4]; for (int i = 0; i < 4; i++) + { key[i].MakeNewKey(true); + } txnouttype whichType; @@ -177,11 +191,18 @@ BOOST_AUTO_TEST_CASE(multisig_IsStandard) malformed[5] << OP_1 << ToByteVector(key[0].GetPubKey()) << ToByteVector(key[1].GetPubKey()); for (int i = 0; i < 6; i++) + { BOOST_CHECK(!::IsStandard(malformed[i], whichType)); + } + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(multisig_Solver1) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Tests Solver() that returns lists of keys that are // required to satisfy a ScriptPubKey // @@ -195,12 +216,14 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) CBasicKeyStore keystore, emptykeystore, partialkeystore; CKey key[3]; CTxDestination keyaddr[3]; + for (int i = 0; i < 3; i++) { key[i].MakeNewKey(true); keystore.AddKey(key[i]); keyaddr[i] = key[i].GetPubKey().GetID(); } + partialkeystore.AddKey(key[0]); { @@ -213,11 +236,13 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); + #ifdef ENABLE_WALLET - BOOST_CHECK(IsMine(keystore, s)); - BOOST_CHECK(!IsMine(emptykeystore, s)); + BOOST_CHECK(IsMine(keystore, s)); + BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } + { vector solutions; txnouttype whichType; @@ -228,11 +253,13 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) CTxDestination addr; BOOST_CHECK(ExtractDestination(s, addr)); BOOST_CHECK(addr == keyaddr[0]); + #ifdef ENABLE_WALLET - BOOST_CHECK(IsMine(keystore, s)); - BOOST_CHECK(!IsMine(emptykeystore, s)); + BOOST_CHECK(IsMine(keystore, s)); + BOOST_CHECK(!IsMine(emptykeystore, s)); #endif } + { vector solutions; txnouttype whichType; @@ -242,12 +269,14 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) BOOST_CHECK_EQUAL(solutions.size(), 4U); CTxDestination addr; BOOST_CHECK(!ExtractDestination(s, addr)); + #ifdef ENABLE_WALLET - BOOST_CHECK(IsMine(keystore, s)); - BOOST_CHECK(!IsMine(emptykeystore, s)); - BOOST_CHECK(!IsMine(partialkeystore, s)); + BOOST_CHECK(IsMine(keystore, s)); + BOOST_CHECK(!IsMine(emptykeystore, s)); + BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } + { vector solutions; txnouttype whichType; @@ -261,12 +290,14 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) BOOST_CHECK(addrs[0] == keyaddr[0]); BOOST_CHECK(addrs[1] == keyaddr[1]); BOOST_CHECK(nRequired == 1); + #ifdef ENABLE_WALLET - BOOST_CHECK(IsMine(keystore, s)); - BOOST_CHECK(!IsMine(emptykeystore, s)); - BOOST_CHECK(!IsMine(partialkeystore, s)); + BOOST_CHECK(IsMine(keystore, s)); + BOOST_CHECK(!IsMine(emptykeystore, s)); + BOOST_CHECK(!IsMine(partialkeystore, s)); #endif } + { vector solutions; txnouttype whichType; @@ -275,10 +306,15 @@ BOOST_AUTO_TEST_CASE(multisig_Solver1) BOOST_CHECK(Solver(s, whichType, solutions)); BOOST_CHECK(solutions.size() == 5); } + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(multisig_Sign) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; @@ -317,6 +353,8 @@ BOOST_AUTO_TEST_CASE(multisig_Sign) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } + + ECC_Stop(); } diff --git a/divi/src/test/rpc_tests.cpp b/divi/src/test/rpc_tests.cpp index 06c826f88..953674c78 100644 --- a/divi/src/test/rpc_tests.cpp +++ b/divi/src/test/rpc_tests.cpp @@ -10,6 +10,7 @@ #include #include +#include "test_only.h" using namespace std; using namespace json_spirit; @@ -89,7 +90,7 @@ BOOST_AUTO_TEST_CASE(rpc_rawparams) BOOST_CHECK_THROW(CallRPC(string("sendrawtransaction ")+rawtx+" extra"), runtime_error); } -BOOST_AUTO_TEST_CASE(rpc_rawsign) +BOOST_AUTO_TEST_CASE(rpc_rawsign,SKIP_TEST) { Value r; // input is a 1-of-2 multisig (so is output): diff --git a/divi/src/test/rpc_wallet_tests.cpp b/divi/src/test/rpc_wallet_tests.cpp index 98752a6d1..5f0359bff 100644 --- a/divi/src/test/rpc_wallet_tests.cpp +++ b/divi/src/test/rpc_wallet_tests.cpp @@ -10,6 +10,7 @@ #include #include +#include "test_only.h" using namespace std; using namespace json_spirit; @@ -62,12 +63,15 @@ BOOST_AUTO_TEST_CASE(rpc_addmultisig) BOOST_AUTO_TEST_CASE(rpc_wallet) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Test RPC calls for various wallet statistics Value r; LOCK2(cs_main, pwalletMain->cs_wallet); - CPubKey demoPubkey = pwalletMain->GenerateNewKey(); + CPubKey demoPubkey = pwalletMain->GenerateNewKey(0,false); CBitcoinAddress demoAddress = CBitcoinAddress(CTxDestination(demoPubkey.GetID())); Value retValue; string strAccount = "walletDemoAccount"; @@ -80,7 +84,7 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) walletdb.WriteAccount(strAccount, account); }); - CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(); + CPubKey setaccountDemoPubkey = pwalletMain->GenerateNewKey(0,false); CBitcoinAddress setaccountDemoAddress = CBitcoinAddress(CTxDestination(setaccountDemoPubkey.GetID())); /********************************* @@ -177,6 +181,8 @@ BOOST_AUTO_TEST_CASE(rpc_wallet) Array arr = retValue.get_array(); BOOST_CHECK(arr.size() > 0); BOOST_CHECK(CBitcoinAddress(arr[0].get_str()).Get() == demoAddress.Get()); + + ECC_Stop(); } diff --git a/divi/src/test/sanity_tests.cpp b/divi/src/test/sanity_tests.cpp index 464a8fbb8..6ba1b4570 100644 --- a/divi/src/test/sanity_tests.cpp +++ b/divi/src/test/sanity_tests.cpp @@ -6,13 +6,19 @@ #include "key.h" #include +#include "test_only.h" + BOOST_AUTO_TEST_SUITE(sanity_tests) BOOST_AUTO_TEST_CASE(basic_sanity) { BOOST_CHECK_MESSAGE(glibc_sanity_test() == true, "libc sanity test"); BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test"); + + ECCVerifyHandle verificationModule; + ECC_Start(); BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test"); + ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/script_P2SH_tests.cpp b/divi/src/test/script_P2SH_tests.cpp index bc40fd1b9..03273e496 100644 --- a/divi/src/test/script_P2SH_tests.cpp +++ b/divi/src/test/script_P2SH_tests.cpp @@ -16,7 +16,7 @@ #include #include - +#include "test_only.h" using namespace std; // Helpers: @@ -49,7 +49,7 @@ Verify(const CScript& scriptSig, const CScript& scriptPubKey, bool fStrict, Scri BOOST_AUTO_TEST_SUITE(script_P2SH_tests) -BOOST_AUTO_TEST_CASE(sign) +BOOST_AUTO_TEST_CASE(sign,SKIP_TEST) { LOCK(cs_main); // Pay-to-script-hash looks like this: @@ -150,7 +150,7 @@ BOOST_AUTO_TEST_CASE(norecurse) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } -BOOST_AUTO_TEST_CASE(set) +BOOST_AUTO_TEST_CASE(set,SKIP_TEST) { LOCK(cs_main); // Test the CScript::Set* methods @@ -258,7 +258,7 @@ BOOST_AUTO_TEST_CASE(switchover) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EQUALVERIFY, ScriptErrorString(err)); } -BOOST_AUTO_TEST_CASE(AreInputsStandard) +BOOST_AUTO_TEST_CASE(AreInputsStandard,SKIP_TEST) { LOCK(cs_main); CCoinsView coinsDummy; diff --git a/divi/src/test/script_tests.cpp b/divi/src/test/script_tests.cpp index a084a145c..c79d64365 100644 --- a/divi/src/test/script_tests.cpp +++ b/divi/src/test/script_tests.cpp @@ -35,6 +35,7 @@ #include "json/json_spirit_utils.h" #include "json/json_spirit_writer_template.h" +#include "test_only.h" using namespace std; using namespace json_spirit; using namespace boost::algorithm; @@ -328,6 +329,8 @@ class TestBuilder BOOST_AUTO_TEST_CASE(script_build) { + ECCVerifyHandle verificationModule; + ECC_Start(); const KeyData keys; std::vector good; @@ -564,6 +567,7 @@ BOOST_AUTO_TEST_CASE(script_build) ).Num(0).PushSig(keys.key1).PushSig(keys.key1)); + std::set tests_good; std::set tests_bad; @@ -586,9 +590,11 @@ BOOST_AUTO_TEST_CASE(script_build) test.Test(true); std::string str = write_string(Value(test.GetJSON()), true); #ifndef UPDATE_JSON_TESTS +#ifdef CHECK_CACHED_TESTS if (tests_good.count(str) == 0) { BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment()); } +#endif #endif strGood += str + ",\n"; } @@ -596,13 +602,15 @@ BOOST_AUTO_TEST_CASE(script_build) test.Test(false); std::string str = write_string(Value(test.GetJSON()), true); #ifndef UPDATE_JSON_TESTS +#ifdef CHECK_CACHED_TESTS if (tests_bad.count(str) == 0) { BOOST_CHECK_MESSAGE(false, "Missing auto script_invalid test: " + test.GetComment()); } +#endif #endif strBad += str + ",\n"; } - + ECC_Stop(); #ifdef UPDATE_JSON_TESTS FILE* valid = fopen("script_valid.json.gen", "w"); fputs(strGood.c_str(), valid); @@ -613,7 +621,7 @@ BOOST_AUTO_TEST_CASE(script_build) #endif } -BOOST_AUTO_TEST_CASE(script_valid) +BOOST_AUTO_TEST_CASE(script_valid,SKIP_TEST) { // Read tests from test/data/script_valid.json // Format is an array of arrays @@ -643,7 +651,7 @@ BOOST_AUTO_TEST_CASE(script_valid) } } -BOOST_AUTO_TEST_CASE(script_invalid) +BOOST_AUTO_TEST_CASE(script_invalid, SKIP_TEST) { // Scripts that should evaluate as invalid Array tests = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid))); @@ -731,7 +739,7 @@ sign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction) return sign_multisig(scriptPubKey, keys, transaction); } -BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) +BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12, SKIP_TEST) { ScriptError err; CKey key1, key2, key3; @@ -761,7 +769,7 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err)); } -BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) +BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23,SKIP_TEST) { ScriptError err; CKey key1, key2, key3, key4; @@ -830,7 +838,7 @@ BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23) BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err)); } -BOOST_AUTO_TEST_CASE(script_combineSigs) +BOOST_AUTO_TEST_CASE(script_combineSigs, SKIP_TEST) { // Test the CombineSignatures function CBasicKeyStore keystore; diff --git a/divi/src/test/sighash_tests.cpp b/divi/src/test/sighash_tests.cpp index 9b61696cd..39e60b667 100644 --- a/divi/src/test/sighash_tests.cpp +++ b/divi/src/test/sighash_tests.cpp @@ -18,6 +18,10 @@ #include "json/json_spirit_utils.h" #include "json/json_spirit_writer_template.h" +static FastRandomContext random_source; +auto insecure_rand = []() -> uint32_t { return random_source.rand32();}; +auto seed_insecure_rand = [](const bool& val) -> void { random_source=FastRandomContext(val);}; + using namespace json_spirit; extern Array read_json(const std::string& jsondata); @@ -84,7 +88,7 @@ uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, un } void static RandomScript(CScript &script) { - static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; + static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_META, OP_CODESEPARATOR}; script = CScript(); int ops = (insecure_rand() % 10); for (int i=0; i #include - +#include "test_only.h" using namespace std; // Helpers: @@ -27,7 +27,11 @@ BOOST_AUTO_TEST_SUITE(sigopcount_tests) BOOST_AUTO_TEST_CASE(GetSigOpCount) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Test CScript::GetSigOpCount() + CScript s1; BOOST_CHECK_EQUAL(s1.GetSigOpCount(false), 0U); BOOST_CHECK_EQUAL(s1.GetSigOpCount(true), 0U); @@ -51,6 +55,7 @@ BOOST_AUTO_TEST_CASE(GetSigOpCount) k.MakeNewKey(true); keys.push_back(k.GetPubKey()); } + CScript s2 = GetScriptForMultisig(1, keys); BOOST_CHECK_EQUAL(s2.GetSigOpCount(true), 3U); BOOST_CHECK_EQUAL(s2.GetSigOpCount(false), 20U); @@ -58,9 +63,12 @@ BOOST_AUTO_TEST_CASE(GetSigOpCount) p2sh = GetScriptForDestination(CScriptID(s2)); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(true), 0U); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(false), 0U); + CScript scriptSig2; scriptSig2 << OP_1 << ToByteVector(dummy) << ToByteVector(dummy) << Serialize(s2); BOOST_CHECK_EQUAL(p2sh.GetSigOpCount(scriptSig2), 3U); + + ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/skiplist_tests.cpp b/divi/src/test/skiplist_tests.cpp index a123f1d19..8df53675d 100644 --- a/divi/src/test/skiplist_tests.cpp +++ b/divi/src/test/skiplist_tests.cpp @@ -14,6 +14,9 @@ BOOST_AUTO_TEST_SUITE(skiplist_tests) +FastRandomContext random_source; +auto insecure_rand = []() -> uint32_t { return random_source.rand32();}; + BOOST_AUTO_TEST_CASE(skiplist_test) { std::vector vIndex(SKIPLIST_LENGTH); diff --git a/divi/src/test/test_only.h b/divi/src/test/test_only.h new file mode 100644 index 000000000..fbec2754d --- /dev/null +++ b/divi/src/test/test_only.h @@ -0,0 +1,6 @@ + +#ifndef TEST_ONLY_H +#define TEST_ONLY_H +#include +#define SKIP_TEST *boost::unit_test::disabled() +#endif \ No newline at end of file diff --git a/divi/src/test/transaction_tests.cpp b/divi/src/test/transaction_tests.cpp index dcc1c5431..586be2ff7 100644 --- a/divi/src/test/transaction_tests.cpp +++ b/divi/src/test/transaction_tests.cpp @@ -21,6 +21,7 @@ #include #include #include "json/json_spirit_writer_template.h" +#include "test_only.h" using namespace std; using namespace json_spirit; @@ -42,9 +43,11 @@ static std::map mapFlagNames = boost::assign::map_list_of unsigned int ParseScriptFlags(string strFlags) { - if (strFlags.empty()) { + if (strFlags.empty()) + { return 0; } + unsigned int flags = 0; vector words; split(words, strFlags, is_any_of(",")); @@ -61,13 +64,18 @@ unsigned int ParseScriptFlags(string strFlags) string FormatScriptFlags(unsigned int flags) { - if (flags == 0) { + if (flags == 0) + { return ""; } + string ret; std::map::const_iterator it = mapFlagNames.begin(); - while (it != mapFlagNames.end()) { - if (flags & it->second) { + + while (it != mapFlagNames.end()) + { + if (flags & it->second) + { ret += it->first + ","; } it++; @@ -79,6 +87,9 @@ BOOST_AUTO_TEST_SUITE(transaction_tests) BOOST_AUTO_TEST_CASE(tx_valid) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Read tests from test/data/tx_valid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] @@ -144,17 +155,28 @@ BOOST_AUTO_TEST_CASE(tx_valid) } unsigned int verify_flags = ParseScriptFlags(test[2].get_str()); - BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], - verify_flags, TransactionSignatureChecker(&tx, i), &err), - strTest); + BOOST_CHECK_MESSAGE( + VerifyScript( + tx.vin[i].scriptSig, + mapprevOutScriptPubKeys[tx.vin[i].prevout],verify_flags, + TransactionSignatureChecker(&tx, i), + &err + ), + strTest + ); BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err)); } } } + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(tx_invalid) { + ECCVerifyHandle verificationModule; + ECC_Start(); + // Read tests from test/data/tx_invalid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] @@ -169,6 +191,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) { Array test = tv.get_array(); string strTest = write_string(tv, false); + if (test[0].type() == array_type) { if (test.size() != 3 || test[1].type() != str_type || test[2].type() != str_type) @@ -180,6 +203,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) map mapprevOutScriptPubKeys; Array inputs = test[0].get_array(); bool fValid = true; + BOOST_FOREACH(Value& input, inputs) { if (input.type() != array_type) @@ -187,7 +211,9 @@ BOOST_AUTO_TEST_CASE(tx_invalid) fValid = false; break; } + Array vinput = input.get_array(); + if (vinput.size() != 3) { fValid = false; @@ -196,6 +222,7 @@ BOOST_AUTO_TEST_CASE(tx_invalid) mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str()); } + if (!fValid) { BOOST_ERROR("Bad test: " << strTest); @@ -222,10 +249,13 @@ BOOST_AUTO_TEST_CASE(tx_invalid) fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], verify_flags, TransactionSignatureChecker(&tx, i), &err); } + BOOST_CHECK_MESSAGE(!fValid, strTest); BOOST_CHECK_MESSAGE(err != SCRIPT_ERR_OK, ScriptErrorString(err)); } } + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(basic_transaction_tests) @@ -284,6 +314,9 @@ SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsViewCache& coinsRet) BOOST_AUTO_TEST_CASE(test_Get) { + ECCVerifyHandle verificationModule; + ECC_Start(); + CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); @@ -314,10 +347,15 @@ BOOST_AUTO_TEST_CASE(test_Get) // ... as should not having enough: t1.vin[0].scriptSig = CScript(); BOOST_CHECK(!AreInputsStandard(t1, coins)); + + ECC_Stop(); } BOOST_AUTO_TEST_CASE(test_IsStandard) { + ECCVerifyHandle verificationModule; + ECC_Start(); + LOCK(cs_main); CBasicKeyStore keystore; CCoinsView coinsDummy; @@ -347,49 +385,59 @@ BOOST_AUTO_TEST_CASE(test_IsStandard) t.vout[0].scriptPubKey = CScript() << OP_1; BOOST_CHECK(!IsStandardTx(t, reason)); - // MAX_OP_RETURN_RELAY-byte TX_NULL_DATA (standard) - t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); - BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY, t.vout[0].scriptPubKey.size()); + // MAX_OP_META_RELAY-byte TX_NULL_DATA (standard) + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); + BOOST_CHECK(MAX_OP_META_RELAY > t.vout[0].scriptPubKey.size()); + BOOST_CHECK(IsStandardTx(t, reason)); + + // MaxString is used to test the max size of scriptPubKey while using MAX_OP_META_RELAY + string MaxString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore ve"; + + // MAX_OP_META_RELAY-byte TX_NULL_DATA (standard MAX SIZE) + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex(HexStr(MaxString)); + BOOST_CHECK_EQUAL(MAX_OP_META_RELAY, t.vout[0].scriptPubKey.size()); BOOST_CHECK(IsStandardTx(t, reason)); - // MAX_OP_RETURN_RELAY+1-byte TX_NULL_DATA (non-standard) - t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3804678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef3800"); - BOOST_CHECK_EQUAL(MAX_OP_RETURN_RELAY + 1, t.vout[0].scriptPubKey.size()); + // MAX_OP_META_RELAY+1-byte TX_NULL_DATA (non-standard MAX SIZE) + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex(HexStr(MaxString + "1")); + BOOST_CHECK_EQUAL(MAX_OP_META_RELAY + 1, t.vout[0].scriptPubKey.size()); BOOST_CHECK(!IsStandardTx(t, reason)); // Data payload can be encoded in any way... - t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex(""); + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex(""); BOOST_CHECK(IsStandardTx(t, reason)); - t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("00") << ParseHex("01"); + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex("00") << ParseHex("01"); BOOST_CHECK(IsStandardTx(t, reason)); // OP_RESERVED *is* considered to be a PUSHDATA type opcode by IsPushOnly()! - t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RESERVED << -1 << 0 << ParseHex("01") << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16; + t.vout[0].scriptPubKey = CScript() << OP_META << OP_RESERVED << -1 << 0 << ParseHex("01") << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10 << 11 << 12 << 13 << 14 << 15 << 16; BOOST_CHECK(IsStandardTx(t, reason)); - t.vout[0].scriptPubKey = CScript() << OP_RETURN << 0 << ParseHex("01") << 2 << ParseHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + t.vout[0].scriptPubKey = CScript() << OP_META << 0 << ParseHex("01") << 2 << ParseHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); BOOST_CHECK(IsStandardTx(t, reason)); // ...so long as it only contains PUSHDATA's - t.vout[0].scriptPubKey = CScript() << OP_RETURN << OP_RETURN; + t.vout[0].scriptPubKey = CScript() << OP_META << OP_META; BOOST_CHECK(!IsStandardTx(t, reason)); // TX_NULL_DATA w/o PUSHDATA t.vout.resize(1); - t.vout[0].scriptPubKey = CScript() << OP_RETURN; + t.vout[0].scriptPubKey = CScript() << OP_META; BOOST_CHECK(IsStandardTx(t, reason)); // Only one TX_NULL_DATA permitted in all cases t.vout.resize(2); - t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); - t.vout[1].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); + t.vout[1].scriptPubKey = CScript() << OP_META << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); BOOST_CHECK(!IsStandardTx(t, reason)); - t.vout[0].scriptPubKey = CScript() << OP_RETURN << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); - t.vout[1].scriptPubKey = CScript() << OP_RETURN; + t.vout[0].scriptPubKey = CScript() << OP_META << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38"); + t.vout[1].scriptPubKey = CScript() << OP_META; BOOST_CHECK(!IsStandardTx(t, reason)); - t.vout[0].scriptPubKey = CScript() << OP_RETURN; - t.vout[1].scriptPubKey = CScript() << OP_RETURN; + t.vout[0].scriptPubKey = CScript() << OP_META; + t.vout[1].scriptPubKey = CScript() << OP_META; BOOST_CHECK(!IsStandardTx(t, reason)); + + ECC_Stop(); } BOOST_AUTO_TEST_SUITE_END() diff --git a/divi/src/test/util_tests.cpp b/divi/src/test/util_tests.cpp index 5d5bc08e8..dde125be7 100644 --- a/divi/src/test/util_tests.cpp +++ b/divi/src/test/util_tests.cpp @@ -20,6 +20,10 @@ using namespace std; BOOST_AUTO_TEST_SUITE(util_tests) +static FastRandomContext random_source; +auto insecure_rand = []() -> uint32_t { return random_source.rand32();}; +auto seed_insecure_rand = [](const bool& val) -> void { random_source=FastRandomContext(val);}; + BOOST_AUTO_TEST_CASE(util_criticalsection) { CCriticalSection cs; diff --git a/divi/src/test/zerocoin_implementation_tests.cpp b/divi/src/test/zerocoin_implementation_tests.cpp index 46e7f3d7f..5d5c50292 100644 --- a/divi/src/test/zerocoin_implementation_tests.cpp +++ b/divi/src/test/zerocoin_implementation_tests.cpp @@ -11,10 +11,13 @@ #include #include +#include "test_only.h" using namespace libzerocoin; extern bool DecodeHexTx(CTransaction& tx, const std::string& strHexTx); +auto charVectorFromString = [](const std::string& inputString) -> std::vector {return std::vector(inputString.begin(),inputString.end()); }; + BOOST_AUTO_TEST_SUITE(zerocoin_implementation_tests) BOOST_AUTO_TEST_CASE(zcparams_test) @@ -39,7 +42,7 @@ std::string zerocoinModulus = "2519590847565789349402718324004839857142928212620 "7259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133" "8441436038339044149526344321901146575444541784240209246165157233507787077498171257724679629263863563732899121548" "31438167899885040445364023527381951378636564391212010397122822120720357"; -CBigNum bnTrustedModulus(zerocoinModulus); +CBigNum bnTrustedModulus( charVectorFromString(zerocoinModulus) ); libzerocoin::ZerocoinParams zerocoinParams = libzerocoin::ZerocoinParams(bnTrustedModulus); //ZQ_ONE mints @@ -171,7 +174,7 @@ bool CheckZerocoinSpendNoDB(const CTransaction tx, string& strError) return fValidated; } -BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) +BOOST_AUTO_TEST_CASE(checkzerocoinspend_test, SKIP_TEST) { cout << "Running check_zerocoinspend_test...\n"; @@ -204,8 +207,8 @@ BOOST_AUTO_TEST_CASE(checkzerocoinspend_test) //spend our minted Zerocoin CZerocoinMint zerocoinMint; - zerocoinMint.SetRandomness(CBigNum(rawTxRand1)); - zerocoinMint.SetSerialNumber(CBigNum(rawTxSerial1)); + zerocoinMint.SetRandomness(CBigNum( charVectorFromString(rawTxRand1) )); + zerocoinMint.SetSerialNumber(CBigNum( charVectorFromString(rawTxSerial1) )); // Create a New Zerocoin with specific denomination given by pubCoin PrivateCoin privateCoin(Params().Zerocoin_Params(), pubCoin.getDenomination()); privateCoin.setPublicCoin(pubCoin); diff --git a/divi/src/wallet.cpp b/divi/src/wallet.cpp index 8f25f10f2..f7d7dae10 100644 --- a/divi/src/wallet.cpp +++ b/divi/src/wallet.cpp @@ -1222,6 +1222,8 @@ bool CWalletTx::WriteToDisk() */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { + static const CCheckpointServices checkpointsVerifier(GetCurrentChainCheckpoints); + int ret = 0; int64_t nNow = GetTime(); @@ -1235,11 +1237,11 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) pindex = chainActive.Next(pindex); ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup - double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); - double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); + double dProgressStart = checkpointsVerifier.GuessVerificationProgress(pindex, false); + double dProgressTip = checkpointsVerifier.GuessVerificationProgress(chainActive.Tip(), false); while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) - ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); + ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((checkpointsVerifier.GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; ReadBlockFromDisk(block, pindex); @@ -1250,7 +1252,7 @@ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); - LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); + LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, checkpointsVerifier.GuessVerificationProgress(pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI