repo_id
stringlengths
0
42
file_path
stringlengths
15
97
content
stringlengths
2
2.41M
__index_level_0__
int64
0
0
bitcoin/src/wallet
bitcoin/src/wallet/test/db_tests.cpp
// Copyright (c) 2018-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <test/util/setup_common.h> #include <util/check.h> #include <util/fs.h> #include <util/translation.h> #ifdef USE_BDB #include <wallet/bdb.h> #endif #ifdef USE_SQLITE #include <wallet/sqlite.h> #endif #include <wallet/test/util.h> #include <wallet/walletutil.h> // for WALLET_FLAG_DESCRIPTORS #include <fstream> #include <memory> #include <string> inline std::ostream& operator<<(std::ostream& os, const std::pair<const SerializeData, SerializeData>& kv) { Span key{kv.first}, value{kv.second}; os << "(\"" << std::string_view{reinterpret_cast<const char*>(key.data()), key.size()} << "\", \"" << std::string_view{reinterpret_cast<const char*>(key.data()), key.size()} << "\")"; return os; } namespace wallet { static Span<const std::byte> StringBytes(std::string_view str) { return AsBytes<const char>({str.data(), str.size()}); } static SerializeData StringData(std::string_view str) { auto bytes = StringBytes(str); return SerializeData{bytes.begin(), bytes.end()}; } static void CheckPrefix(DatabaseBatch& batch, Span<const std::byte> prefix, MockableData expected) { std::unique_ptr<DatabaseCursor> cursor = batch.GetNewPrefixCursor(prefix); MockableData actual; while (true) { DataStream key, value; DatabaseCursor::Status status = cursor->Next(key, value); if (status == DatabaseCursor::Status::DONE) break; BOOST_CHECK(status == DatabaseCursor::Status::MORE); BOOST_CHECK( actual.emplace(SerializeData(key.begin(), key.end()), SerializeData(value.begin(), value.end())).second); } BOOST_CHECK_EQUAL_COLLECTIONS(actual.begin(), actual.end(), expected.begin(), expected.end()); } BOOST_FIXTURE_TEST_SUITE(db_tests, BasicTestingSetup) static std::shared_ptr<BerkeleyEnvironment> GetWalletEnv(const fs::path& path, fs::path& database_filename) { fs::path data_file = BDBDataFile(path); database_filename = data_file.filename(); return GetBerkeleyEnv(data_file.parent_path(), false); } BOOST_AUTO_TEST_CASE(getwalletenv_file) { fs::path test_name = "test_name.dat"; const fs::path datadir = m_args.GetDataDirNet(); fs::path file_path = datadir / test_name; std::ofstream f{file_path}; f.close(); fs::path filename; std::shared_ptr<BerkeleyEnvironment> env = GetWalletEnv(file_path, filename); BOOST_CHECK_EQUAL(filename, test_name); BOOST_CHECK_EQUAL(env->Directory(), datadir); } BOOST_AUTO_TEST_CASE(getwalletenv_directory) { fs::path expected_name = "wallet.dat"; const fs::path datadir = m_args.GetDataDirNet(); fs::path filename; std::shared_ptr<BerkeleyEnvironment> env = GetWalletEnv(datadir, filename); BOOST_CHECK_EQUAL(filename, expected_name); BOOST_CHECK_EQUAL(env->Directory(), datadir); } BOOST_AUTO_TEST_CASE(getwalletenv_g_dbenvs_multiple) { fs::path datadir = m_args.GetDataDirNet() / "1"; fs::path datadir_2 = m_args.GetDataDirNet() / "2"; fs::path filename; std::shared_ptr<BerkeleyEnvironment> env_1 = GetWalletEnv(datadir, filename); std::shared_ptr<BerkeleyEnvironment> env_2 = GetWalletEnv(datadir, filename); std::shared_ptr<BerkeleyEnvironment> env_3 = GetWalletEnv(datadir_2, filename); BOOST_CHECK(env_1 == env_2); BOOST_CHECK(env_2 != env_3); } BOOST_AUTO_TEST_CASE(getwalletenv_g_dbenvs_free_instance) { fs::path datadir = gArgs.GetDataDirNet() / "1"; fs::path datadir_2 = gArgs.GetDataDirNet() / "2"; fs::path filename; std::shared_ptr <BerkeleyEnvironment> env_1_a = GetWalletEnv(datadir, filename); std::shared_ptr <BerkeleyEnvironment> env_2_a = GetWalletEnv(datadir_2, filename); env_1_a.reset(); std::shared_ptr<BerkeleyEnvironment> env_1_b = GetWalletEnv(datadir, filename); std::shared_ptr<BerkeleyEnvironment> env_2_b = GetWalletEnv(datadir_2, filename); BOOST_CHECK(env_1_a != env_1_b); BOOST_CHECK(env_2_a == env_2_b); } static std::vector<std::unique_ptr<WalletDatabase>> TestDatabases(const fs::path& path_root) { std::vector<std::unique_ptr<WalletDatabase>> dbs; DatabaseOptions options; DatabaseStatus status; bilingual_str error; #ifdef USE_BDB dbs.emplace_back(MakeBerkeleyDatabase(path_root / "bdb", options, status, error)); #endif #ifdef USE_SQLITE dbs.emplace_back(MakeSQLiteDatabase(path_root / "sqlite", options, status, error)); #endif dbs.emplace_back(CreateMockableWalletDatabase()); return dbs; } BOOST_AUTO_TEST_CASE(db_cursor_prefix_range_test) { // Test each supported db for (const auto& database : TestDatabases(m_path_root)) { std::vector<std::string> prefixes = {"", "FIRST", "SECOND", "P\xfe\xff", "P\xff\x01", "\xff\xff"}; // Write elements to it std::unique_ptr<DatabaseBatch> handler = Assert(database)->MakeBatch(); for (unsigned int i = 0; i < 10; i++) { for (const auto& prefix : prefixes) { BOOST_CHECK(handler->Write(std::make_pair(prefix, i), i)); } } // Now read all the items by prefix and verify that each element gets parsed correctly for (const auto& prefix : prefixes) { DataStream s_prefix; s_prefix << prefix; std::unique_ptr<DatabaseCursor> cursor = handler->GetNewPrefixCursor(s_prefix); DataStream key; DataStream value; for (int i = 0; i < 10; i++) { DatabaseCursor::Status status = cursor->Next(key, value); BOOST_CHECK_EQUAL(status, DatabaseCursor::Status::MORE); std::string key_back; unsigned int i_back; key >> key_back >> i_back; BOOST_CHECK_EQUAL(key_back, prefix); unsigned int value_back; value >> value_back; BOOST_CHECK_EQUAL(value_back, i_back); } // Let's now read it once more, it should return DONE BOOST_CHECK(cursor->Next(key, value) == DatabaseCursor::Status::DONE); } } } // Lower level DatabaseBase::GetNewPrefixCursor test, to cover cases that aren't // covered in the higher level test above. The higher level test uses // serialized strings which are prefixed with string length, so it doesn't test // truly empty prefixes or prefixes that begin with \xff BOOST_AUTO_TEST_CASE(db_cursor_prefix_byte_test) { const MockableData::value_type e{StringData(""), StringData("e")}, p{StringData("prefix"), StringData("p")}, ps{StringData("prefixsuffix"), StringData("ps")}, f{StringData("\xff"), StringData("f")}, fs{StringData("\xffsuffix"), StringData("fs")}, ff{StringData("\xff\xff"), StringData("ff")}, ffs{StringData("\xff\xffsuffix"), StringData("ffs")}; for (const auto& database : TestDatabases(m_path_root)) { std::unique_ptr<DatabaseBatch> batch = database->MakeBatch(); for (const auto& [k, v] : {e, p, ps, f, fs, ff, ffs}) { batch->Write(Span{k}, Span{v}); } CheckPrefix(*batch, StringBytes(""), {e, p, ps, f, fs, ff, ffs}); CheckPrefix(*batch, StringBytes("prefix"), {p, ps}); CheckPrefix(*batch, StringBytes("\xff"), {f, fs, ff, ffs}); CheckPrefix(*batch, StringBytes("\xff\xff"), {ff, ffs}); } } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/init_test_fixture.cpp
// Copyright (c) 2018-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <common/args.h> #include <univalue.h> #include <util/chaintype.h> #include <util/check.h> #include <util/fs.h> #include <fstream> #include <string> #include <wallet/test/init_test_fixture.h> namespace wallet { InitWalletDirTestingSetup::InitWalletDirTestingSetup(const ChainType chainType) : BasicTestingSetup(chainType) { m_wallet_loader = MakeWalletLoader(*m_node.chain, m_args); const auto sep = fs::path::preferred_separator; m_datadir = m_args.GetDataDirNet(); m_cwd = fs::current_path(); m_walletdir_path_cases["default"] = m_datadir / "wallets"; m_walletdir_path_cases["custom"] = m_datadir / "my_wallets"; m_walletdir_path_cases["nonexistent"] = m_datadir / "path_does_not_exist"; m_walletdir_path_cases["file"] = m_datadir / "not_a_directory.dat"; m_walletdir_path_cases["trailing"] = (m_datadir / "wallets") + sep; m_walletdir_path_cases["trailing2"] = (m_datadir / "wallets") + sep + sep; fs::current_path(m_datadir); m_walletdir_path_cases["relative"] = "wallets"; fs::create_directories(m_walletdir_path_cases["default"]); fs::create_directories(m_walletdir_path_cases["custom"]); fs::create_directories(m_walletdir_path_cases["relative"]); std::ofstream f{m_walletdir_path_cases["file"]}; f.close(); } InitWalletDirTestingSetup::~InitWalletDirTestingSetup() { fs::current_path(m_cwd); } void InitWalletDirTestingSetup::SetWalletDir(const fs::path& walletdir_path) { m_args.ForceSetArg("-walletdir", fs::PathToString(walletdir_path)); } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/scriptpubkeyman_tests.cpp
// Copyright (c) 2020-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key.h> #include <test/util/setup_common.h> #include <script/solver.h> #include <wallet/scriptpubkeyman.h> #include <wallet/wallet.h> #include <wallet/test/util.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_FIXTURE_TEST_SUITE(scriptpubkeyman_tests, BasicTestingSetup) // Test LegacyScriptPubKeyMan::CanProvide behavior, making sure it returns true // for recognized scripts even when keys may not be available for signing. BOOST_AUTO_TEST_CASE(CanProvide) { // Set up wallet and keyman variables. CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); LegacyScriptPubKeyMan& keyman = *wallet.GetOrCreateLegacyScriptPubKeyMan(); // Make a 1 of 2 multisig script std::vector<CKey> keys(2); std::vector<CPubKey> pubkeys; for (CKey& key : keys) { key.MakeNewKey(true); pubkeys.emplace_back(key.GetPubKey()); } CScript multisig_script = GetScriptForMultisig(1, pubkeys); CScript p2sh_script = GetScriptForDestination(ScriptHash(multisig_script)); SignatureData data; // Verify the p2sh(multisig) script is not recognized until the multisig // script is added to the keystore to make it solvable BOOST_CHECK(!keyman.CanProvide(p2sh_script, data)); keyman.AddCScript(multisig_script); BOOST_CHECK(keyman.CanProvide(p2sh_script, data)); } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/ismine_tests.cpp
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key.h> #include <key_io.h> #include <node/context.h> #include <script/script.h> #include <script/solver.h> #include <script/signingprovider.h> #include <test/util/setup_common.h> #include <wallet/types.h> #include <wallet/wallet.h> #include <wallet/test/util.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_FIXTURE_TEST_SUITE(ismine_tests, BasicTestingSetup) wallet::ScriptPubKeyMan* CreateDescriptor(CWallet& keystore, const std::string& desc_str, const bool success) { keystore.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); FlatSigningProvider keys; std::string error; std::unique_ptr<Descriptor> parsed_desc = Parse(desc_str, keys, error, false); BOOST_CHECK(success == (parsed_desc != nullptr)); if (!success) return nullptr; const int64_t range_start = 0, range_end = 1, next_index = 0, timestamp = 1; WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index); LOCK(keystore.cs_wallet); return Assert(keystore.AddWalletDescriptor(w_desc, keys,/*label=*/"", /*internal=*/false)); }; BOOST_AUTO_TEST_CASE(ismine_standard) { CKey keys[2]; CPubKey pubkeys[2]; for (int i = 0; i < 2; i++) { keys[i].MakeNewKey(true); pubkeys[i] = keys[i].GetPubKey(); } CKey uncompressedKey; uncompressedKey.MakeNewKey(false); CPubKey uncompressedPubkey = uncompressedKey.GetPubKey(); std::unique_ptr<interfaces::Chain>& chain = m_node.chain; CScript scriptPubKey; isminetype result; // P2PK compressed - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); scriptPubKey = GetScriptForRawPubKey(pubkeys[0]); // Keystore does not have key result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has key BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2PK compressed - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "pk(" + EncodeSecret(keys[0]) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); scriptPubKey = GetScriptForRawPubKey(pubkeys[0]); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2PK uncompressed - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); scriptPubKey = GetScriptForRawPubKey(uncompressedPubkey); // Keystore does not have key result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has key BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(uncompressedKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2PK uncompressed - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "pk(" + EncodeSecret(uncompressedKey) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); scriptPubKey = GetScriptForRawPubKey(uncompressedPubkey); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2PKH compressed - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); scriptPubKey = GetScriptForDestination(PKHash(pubkeys[0])); // Keystore does not have key result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has key BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2PKH compressed - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "pkh(" + EncodeSecret(keys[0]) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); scriptPubKey = GetScriptForDestination(PKHash(pubkeys[0])); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2PKH uncompressed - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); scriptPubKey = GetScriptForDestination(PKHash(uncompressedPubkey)); // Keystore does not have key result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has key BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(uncompressedKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2PKH uncompressed - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "pkh(" + EncodeSecret(uncompressedKey) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); scriptPubKey = GetScriptForDestination(PKHash(uncompressedPubkey)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2SH - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); CScript redeemScript = GetScriptForDestination(PKHash(pubkeys[0])); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); // Keystore does not have redeemScript or key result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has redeemScript but no key BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(redeemScript)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has redeemScript and key BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2SH - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "sh(pkh(" + EncodeSecret(keys[0]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); CScript redeemScript = GetScriptForDestination(PKHash(pubkeys[0])); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // (P2PKH inside) P2SH inside P2SH (invalid) - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); CScript redeemscript_inner = GetScriptForDestination(PKHash(pubkeys[0])); CScript redeemscript = GetScriptForDestination(ScriptHash(redeemscript_inner)); scriptPubKey = GetScriptForDestination(ScriptHash(redeemscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(redeemscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(redeemscript_inner)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // (P2PKH inside) P2SH inside P2SH (invalid) - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "sh(sh(" + EncodeSecret(keys[0]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, false); BOOST_CHECK_EQUAL(spk_manager, nullptr); } // (P2PKH inside) P2SH inside P2WSH (invalid) - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); CScript redeemscript = GetScriptForDestination(PKHash(pubkeys[0])); CScript witnessscript = GetScriptForDestination(ScriptHash(redeemscript)); scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(witnessscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(redeemscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // (P2PKH inside) P2SH inside P2WSH (invalid) - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wsh(sh(" + EncodeSecret(keys[0]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, false); BOOST_CHECK_EQUAL(spk_manager, nullptr); } // P2WPKH inside P2WSH (invalid) - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); CScript witnessscript = GetScriptForDestination(WitnessV0KeyHash(pubkeys[0])); scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(witnessscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // P2WPKH inside P2WSH (invalid) - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wsh(wpkh(" + EncodeSecret(keys[0]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, false); BOOST_CHECK_EQUAL(spk_manager, nullptr); } // (P2PKH inside) P2WSH inside P2WSH (invalid) - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); CScript witnessscript_inner = GetScriptForDestination(PKHash(pubkeys[0])); CScript witnessscript = GetScriptForDestination(WitnessV0ScriptHash(witnessscript_inner)); scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(witnessscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessscript_inner)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessscript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // (P2PKH inside) P2WSH inside P2WSH (invalid) - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wsh(wsh(" + EncodeSecret(keys[0]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, false); BOOST_CHECK_EQUAL(spk_manager, nullptr); } // P2WPKH compressed - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkeys[0])); // Keystore implicitly has key and P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2WPKH compressed - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wpkh(" + EncodeSecret(keys[0]) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkeys[0])); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2WPKH uncompressed - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(uncompressedKey)); scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(uncompressedPubkey)); // Keystore has key, but no P2SH redeemScript result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has key and P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // P2WPKH uncompressed (invalid) - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wpkh(" + EncodeSecret(uncompressedKey) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, false); BOOST_CHECK_EQUAL(spk_manager, nullptr); } // scriptPubKey multisig - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); scriptPubKey = GetScriptForMultisig(2, {uncompressedPubkey, pubkeys[1]}); // Keystore does not have any keys result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has 1/2 keys BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(uncompressedKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has 2/2 keys BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[1])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has 2/2 keys and the script BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // scriptPubKey multisig - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "multi(2, " + EncodeSecret(uncompressedKey) + ", " + EncodeSecret(keys[1]) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); scriptPubKey = GetScriptForMultisig(2, {uncompressedPubkey, pubkeys[1]}); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2SH multisig - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(uncompressedKey)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[1])); CScript redeemScript = GetScriptForMultisig(2, {uncompressedPubkey, pubkeys[1]}); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); // Keystore has no redeemScript result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(redeemScript)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2SH multisig - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "sh(multi(2, " + EncodeSecret(uncompressedKey) + ", " + EncodeSecret(keys[1]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); CScript redeemScript = GetScriptForMultisig(2, {uncompressedPubkey, pubkeys[1]}); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2WSH multisig with compressed keys - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[1])); CScript witnessScript = GetScriptForMultisig(2, {pubkeys[0], pubkeys[1]}); scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(witnessScript)); // Keystore has keys, but no witnessScript or P2SH redeemScript result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has keys and witnessScript, but no P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessScript)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has keys, witnessScript, P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2WSH multisig with compressed keys - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wsh(multi(2, " + EncodeSecret(keys[0]) + ", " + EncodeSecret(keys[1]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); CScript redeemScript = GetScriptForMultisig(2, {pubkeys[0], pubkeys[1]}); scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(redeemScript)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // P2WSH multisig with uncompressed key - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(uncompressedKey)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[1])); CScript witnessScript = GetScriptForMultisig(2, {uncompressedPubkey, pubkeys[1]}); scriptPubKey = GetScriptForDestination(WitnessV0ScriptHash(witnessScript)); // Keystore has keys, but no witnessScript or P2SH redeemScript result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has keys and witnessScript, but no P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessScript)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has keys, witnessScript, P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(scriptPubKey)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // P2WSH multisig with uncompressed key (invalid) - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "wsh(multi(2, " + EncodeSecret(uncompressedKey) + ", " + EncodeSecret(keys[1]) + "))"; auto spk_manager = CreateDescriptor(keystore, desc_str, false); BOOST_CHECK_EQUAL(spk_manager, nullptr); } // P2WSH multisig wrapped in P2SH - Legacy { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); CScript witnessScript = GetScriptForMultisig(2, {pubkeys[0], pubkeys[1]}); CScript redeemScript = GetScriptForDestination(WitnessV0ScriptHash(witnessScript)); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); // Keystore has no witnessScript, P2SH redeemScript, or keys result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has witnessScript and P2SH redeemScript, but no keys BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(redeemScript)); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddCScript(witnessScript)); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); // Keystore has keys, witnessScript, P2SH redeemScript BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[1])); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 1); } // P2WSH multisig wrapped in P2SH - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "sh(wsh(multi(2, " + EncodeSecret(keys[0]) + ", " + EncodeSecret(keys[1]) + ")))"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); CScript witnessScript = GetScriptForMultisig(2, {pubkeys[0], pubkeys[1]}); CScript redeemScript = GetScriptForDestination(WitnessV0ScriptHash(witnessScript)); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // Combo - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "combo(" + EncodeSecret(keys[0]) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); // Test P2PK result = spk_manager->IsMine(GetScriptForRawPubKey(pubkeys[0])); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); // Test P2PKH result = spk_manager->IsMine(GetScriptForDestination(PKHash(pubkeys[0]))); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); // Test P2SH (combo descriptor does not describe P2SH) CScript redeemScript = GetScriptForDestination(PKHash(pubkeys[0])); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); // Test P2WPKH scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(pubkeys[0])); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); // P2SH-P2WPKH output redeemScript = GetScriptForDestination(WitnessV0KeyHash(pubkeys[0])); scriptPubKey = GetScriptForDestination(ScriptHash(redeemScript)); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); // Test P2TR (combo descriptor does not describe P2TR) XOnlyPubKey xpk(pubkeys[0]); Assert(xpk.IsFullyValid()); TaprootBuilder builder; builder.Finalize(xpk); WitnessV1Taproot output = builder.GetOutput(); scriptPubKey = GetScriptForDestination(output); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); } // Taproot - Descriptor { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); std::string desc_str = "tr(" + EncodeSecret(keys[0]) + ")"; auto spk_manager = CreateDescriptor(keystore, desc_str, true); XOnlyPubKey xpk(pubkeys[0]); Assert(xpk.IsFullyValid()); TaprootBuilder builder; builder.Finalize(xpk); WitnessV1Taproot output = builder.GetOutput(); scriptPubKey = GetScriptForDestination(output); result = spk_manager->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_SPENDABLE); } // OP_RETURN { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); scriptPubKey.clear(); scriptPubKey << OP_RETURN << ToByteVector(pubkeys[0]); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // witness unspendable { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); scriptPubKey.clear(); scriptPubKey << OP_0 << ToByteVector(ParseHex("aabb")); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // witness unknown { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); scriptPubKey.clear(); scriptPubKey << OP_16 << ToByteVector(ParseHex("aabb")); result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } // Nonstandard { CWallet keystore(chain.get(), "", CreateMockableWalletDatabase()); keystore.SetupLegacyScriptPubKeyMan(); LOCK(keystore.GetLegacyScriptPubKeyMan()->cs_KeyStore); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->AddKey(keys[0])); scriptPubKey.clear(); scriptPubKey << OP_9 << OP_ADD << OP_11 << OP_EQUAL; result = keystore.GetLegacyScriptPubKeyMan()->IsMine(scriptPubKey); BOOST_CHECK_EQUAL(result, ISMINE_NO); BOOST_CHECK(keystore.GetLegacyScriptPubKeyMan()->GetScriptPubKeys().count(scriptPubKey) == 0); } } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/wallet_test_fixture.h
// Copyright (c) 2016-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_TEST_WALLET_TEST_FIXTURE_H #define BITCOIN_WALLET_TEST_WALLET_TEST_FIXTURE_H #include <test/util/setup_common.h> #include <interfaces/chain.h> #include <interfaces/wallet.h> #include <node/context.h> #include <util/chaintype.h> #include <util/check.h> #include <wallet/wallet.h> #include <memory> namespace wallet { /** Testing setup and teardown for wallet. */ struct WalletTestingSetup : public TestingSetup { explicit WalletTestingSetup(const ChainType chainType = ChainType::MAIN); ~WalletTestingSetup(); std::unique_ptr<interfaces::WalletLoader> m_wallet_loader; CWallet m_wallet; std::unique_ptr<interfaces::Handler> m_chain_notifications_handler; }; } // namespace wallet #endif // BITCOIN_WALLET_TEST_WALLET_TEST_FIXTURE_H
0
bitcoin/src/wallet
bitcoin/src/wallet/test/wallet_transaction_tests.cpp
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/transaction.h> #include <wallet/test/wallet_test_fixture.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_FIXTURE_TEST_SUITE(wallet_transaction_tests, WalletTestingSetup) BOOST_AUTO_TEST_CASE(roundtrip) { for (uint8_t hash = 0; hash < 5; ++hash) { for (int index = -2; index < 3; ++index) { TxState state = TxStateInterpretSerialized(TxStateUnrecognized{uint256{hash}, index}); BOOST_CHECK_EQUAL(TxStateSerializedBlockHash(state), uint256{hash}); BOOST_CHECK_EQUAL(TxStateSerializedIndex(state), index); } } } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/feebumper_tests.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include <consensus/validation.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <script/script.h> #include <util/strencodings.h> #include <wallet/feebumper.h> #include <wallet/test/util.h> #include <wallet/test/wallet_test_fixture.h> #include <boost/test/unit_test.hpp> namespace wallet { namespace feebumper { BOOST_FIXTURE_TEST_SUITE(feebumper_tests, WalletTestingSetup) static void CheckMaxWeightComputation(const std::string& script_str, const std::vector<std::string>& witness_str_stack, const std::string& prevout_script_str, int64_t expected_max_weight) { std::vector script_data(ParseHex(script_str)); CScript script(script_data.begin(), script_data.end()); CTxIn input(Txid{}, 0, script); for (const auto& s : witness_str_stack) { input.scriptWitness.stack.push_back(ParseHex(s)); } std::vector prevout_script_data(ParseHex(prevout_script_str)); CScript prevout_script(prevout_script_data.begin(), prevout_script_data.end()); int64_t weight = GetTransactionInputWeight(input); SignatureWeights weights; SignatureWeightChecker size_checker(weights, DUMMY_CHECKER); bool script_ok = VerifyScript(input.scriptSig, prevout_script, &input.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, size_checker); BOOST_CHECK(script_ok); weight += weights.GetWeightDiffToMax(); BOOST_CHECK_EQUAL(weight, expected_max_weight); } BOOST_AUTO_TEST_CASE(external_max_weight_test) { // P2PKH CheckMaxWeightComputation("453042021f03c8957c5ce12940ee6e3333ecc3f633d9a1ac53a55b3ce0351c617fa96abe021f0dccdcce3ef45a63998be9ec748b561baf077b8e862941d0cd5ec08f5afe68012102fccfeb395f0ecd3a77e7bc31c3bc61dc987418b18e395d441057b42ca043f22c", {}, "76a914f60dcfd3392b28adc7662669603641f578eed72d88ac", 593); // P2SH-P2WPKH CheckMaxWeightComputation("160014001dca1b22c599b5a56a87c78417ad2ff39552f1", {"3042021f5443c58eaf45f3e5ef46f8516f966b334a7d497cedda4edb2b9fad57c90c3b021f63a77cb56cde848e2e2dd20b487eec2f53101f634193786083f60b4d23a82301", "026cfe86116f161057deb240201d6b82ebd4f161e0200d63dc9aca65a1d6b38bb7"}, "a9147c8ab5ad7708b97ccb6b483d57aba48ee85214df87", 364); // P2WPKH CheckMaxWeightComputation("", {"3042021f0f8906f0394979d5b737134773e5b88bf036c7d63542301d600ab677ba5a59021f0e9fe07e62c113045fa1c1532e2914720e8854d189c4f5b8c88f57956b704401", "0359edba11ed1a0568094a6296a16c4d5ee4c8cfe2f5e2e6826871b5ecf8188f79"}, "00149961a78658030cc824af4c54fbf5294bec0cabdd", 272); // P2WSH HTLC CheckMaxWeightComputation("", {"3042021f5c4c29e6b686aae5b6d0751e90208592ea96d26bc81d78b0d3871a94a21fa8021f74dc2f971e438ccece8699c8fd15704c41df219ab37b63264f2147d15c34d801", "01", "6321024cf55e52ec8af7866617dc4e7ff8433758e98799906d80e066c6f32033f685f967029000b275210214827893e2dcbe4ad6c20bd743288edad21100404eb7f52ccd6062fd0e7808f268ac"}, "002089e84892873c679b1129edea246e484fd914c2601f776d4f2f4a001eb8059703", 318); } BOOST_AUTO_TEST_SUITE_END() } // namespace feebumper } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/wallet_tests.cpp
// Copyright (c) 2012-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/wallet.h> #include <future> #include <memory> #include <stdint.h> #include <vector> #include <addresstype.h> #include <interfaces/chain.h> #include <key_io.h> #include <node/blockstorage.h> #include <policy/policy.h> #include <rpc/server.h> #include <script/solver.h> #include <test/util/logging.h> #include <test/util/random.h> #include <test/util/setup_common.h> #include <util/translation.h> #include <validation.h> #include <validationinterface.h> #include <wallet/coincontrol.h> #include <wallet/context.h> #include <wallet/receive.h> #include <wallet/spend.h> #include <wallet/test/util.h> #include <wallet/test/wallet_test_fixture.h> #include <boost/test/unit_test.hpp> #include <univalue.h> using node::MAX_BLOCKFILE_SIZE; namespace wallet { RPCHelpMan importmulti(); RPCHelpMan dumpwallet(); RPCHelpMan importwallet(); // Ensure that fee levels defined in the wallet are at least as high // as the default levels for node policy. static_assert(DEFAULT_TRANSACTION_MINFEE >= DEFAULT_MIN_RELAY_TX_FEE, "wallet minimum fee is smaller than default relay fee"); static_assert(WALLET_INCREMENTAL_RELAY_FEE >= DEFAULT_INCREMENTAL_RELAY_FEE, "wallet incremental fee is smaller than default incremental relay fee"); BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup) static CMutableTransaction TestSimpleSpend(const CTransaction& from, uint32_t index, const CKey& key, const CScript& pubkey) { CMutableTransaction mtx; mtx.vout.emplace_back(from.vout[index].nValue - DEFAULT_TRANSACTION_MAXFEE, pubkey); mtx.vin.push_back({CTxIn{from.GetHash(), index}}); FillableSigningProvider keystore; keystore.AddKey(key); std::map<COutPoint, Coin> coins; coins[mtx.vin[0].prevout].out = from.vout[index]; std::map<int, bilingual_str> input_errors; BOOST_CHECK(SignTransaction(mtx, &keystore, coins, SIGHASH_ALL, input_errors)); return mtx; } static void AddKey(CWallet& wallet, const CKey& key) { LOCK(wallet.cs_wallet); FlatSigningProvider provider; std::string error; std::unique_ptr<Descriptor> desc = Parse("combo(" + EncodeSecret(key) + ")", provider, error, /* require_checksum=*/ false); assert(desc); WalletDescriptor w_desc(std::move(desc), 0, 0, 1, 1); if (!wallet.AddWalletDescriptor(w_desc, provider, "", false)) assert(false); } BOOST_FIXTURE_TEST_CASE(scan_for_wallet_transactions, TestChain100Setup) { // Cap last block file size, and mine new block in a new block file. CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()); WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE); CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()); // Verify ScanForWalletTransactions fails to read an unknown start block. { CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); { LOCK(wallet.cs_wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); } AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(wallet); reserver.reserve(); CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/{}, /*start_height=*/0, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false); BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE); BOOST_CHECK(result.last_failed_block.IsNull()); BOOST_CHECK(result.last_scanned_block.IsNull()); BOOST_CHECK(!result.last_scanned_height); BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0); } // Verify ScanForWalletTransactions picks up transactions in both the old // and new block files. { CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); { LOCK(wallet.cs_wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); } AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(wallet); std::chrono::steady_clock::time_point fake_time; reserver.setNow([&] { fake_time += 60s; return fake_time; }); reserver.reserve(); { CBlockLocator locator; BOOST_CHECK(!WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator)); BOOST_CHECK(locator.IsNull()); } CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/true); BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS); BOOST_CHECK(result.last_failed_block.IsNull()); BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash()); BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight); BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 100 * COIN); { CBlockLocator locator; BOOST_CHECK(WalletBatch{wallet.GetDatabase()}.ReadBestBlock(locator)); BOOST_CHECK(!locator.IsNull()); } } // Prune the older block file. int file_number; { LOCK(cs_main); file_number = oldTip->GetBlockPos().nFile; Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number); } m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number}); // Verify ScanForWalletTransactions only picks transactions in the new block // file. { CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); { LOCK(wallet.cs_wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); } AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(wallet); reserver.reserve(); CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false); BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE); BOOST_CHECK_EQUAL(result.last_failed_block, oldTip->GetBlockHash()); BOOST_CHECK_EQUAL(result.last_scanned_block, newTip->GetBlockHash()); BOOST_CHECK_EQUAL(*result.last_scanned_height, newTip->nHeight); BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 50 * COIN); } // Prune the remaining block file. { LOCK(cs_main); file_number = newTip->GetBlockPos().nFile; Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number); } m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number}); // Verify ScanForWalletTransactions scans no blocks. { CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); { LOCK(wallet.cs_wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); } AddKey(wallet, coinbaseKey); WalletRescanReserver reserver(wallet); reserver.reserve(); CWallet::ScanResult result = wallet.ScanForWalletTransactions(/*start_block=*/oldTip->GetBlockHash(), /*start_height=*/oldTip->nHeight, /*max_height=*/{}, reserver, /*fUpdate=*/false, /*save_progress=*/false); BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::FAILURE); BOOST_CHECK_EQUAL(result.last_failed_block, newTip->GetBlockHash()); BOOST_CHECK(result.last_scanned_block.IsNull()); BOOST_CHECK(!result.last_scanned_height); BOOST_CHECK_EQUAL(GetBalance(wallet).m_mine_immature, 0); } } BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup) { // Cap last block file size, and mine new block in a new block file. CBlockIndex* oldTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()); WITH_LOCK(::cs_main, m_node.chainman->m_blockman.GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE); CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CBlockIndex* newTip = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()); // Prune the older block file. int file_number; { LOCK(cs_main); file_number = oldTip->GetBlockPos().nFile; Assert(m_node.chainman)->m_blockman.PruneOneBlockFile(file_number); } m_node.chainman->m_blockman.UnlinkPrunedFiles({file_number}); // Verify importmulti RPC returns failure for a key whose creation time is // before the missing block, and success for a key whose creation time is // after. { const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(newTip->nHeight, newTip->GetBlockHash())); WalletContext context; context.args = &m_args; AddWallet(context, wallet); UniValue keys; keys.setArray(); UniValue key; key.setObject(); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey()))); key.pushKV("timestamp", 0); key.pushKV("internal", UniValue(true)); keys.push_back(key); key.clear(); key.setObject(); CKey futureKey; futureKey.MakeNewKey(true); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey()))); key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1); key.pushKV("internal", UniValue(true)); keys.push_back(key); JSONRPCRequest request; request.context = &context; request.params.setArray(); request.params.push_back(keys); UniValue response = importmulti().HandleRequest(request); BOOST_CHECK_EQUAL(response.write(), strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation " "timestamp %d. There was an error reading a block from time %d, which is after or within %d " "seconds of key creation, and could contain transactions pertaining to the key. As a result, " "transactions and coins using this key may not appear in the wallet. This error could be caused " "by pruning or data corruption (see bitcoind log for details) and could be dealt with by " "downloading and rescanning the relevant blocks (see -reindex option and rescanblockchain " "RPC).\"}},{\"success\":true}]", 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW)); RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt); } } // Verify importwallet RPC starts rescan at earliest block with timestamp // greater or equal than key birthday. Previously there was a bug where // importwallet RPC would start the scan at the latest block with timestamp less // than or equal to key birthday. BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) { // Create two blocks with same timestamp to verify that importwallet rescan // will pick up both blocks, not just the first. const int64_t BLOCK_TIME = WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockTimeMax() + 5); SetMockTime(BLOCK_TIME); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); // Set key birthday to block time increased by the timestamp window, so // rescan will start at the block time. const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW; SetMockTime(KEY_TIME); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); std::string backup_file = fs::PathToString(m_args.GetDataDirNet() / "wallet.backup"); // Import key into wallet and call dumpwallet to create backup file. { WalletContext context; context.args = &m_args; const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase()); { auto spk_man = wallet->GetOrCreateLegacyScriptPubKeyMan(); LOCK2(wallet->cs_wallet, spk_man->cs_KeyStore); spk_man->mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME; spk_man->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); AddWallet(context, wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); } JSONRPCRequest request; request.context = &context; request.params.setArray(); request.params.push_back(backup_file); wallet::dumpwallet().HandleRequest(request); RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt); } // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME // were scanned, and no prior blocks were scanned. { const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase()); LOCK(wallet->cs_wallet); wallet->SetupLegacyScriptPubKeyMan(); WalletContext context; context.args = &m_args; JSONRPCRequest request; request.context = &context; request.params.setArray(); request.params.push_back(backup_file); AddWallet(context, wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); wallet::importwallet().HandleRequest(request); RemoveWallet(context, wallet, /* load_on_start= */ std::nullopt); BOOST_CHECK_EQUAL(wallet->mapWallet.size(), 3U); BOOST_CHECK_EQUAL(m_coinbase_txns.size(), 103U); for (size_t i = 0; i < m_coinbase_txns.size(); ++i) { bool found = wallet->GetWalletTx(m_coinbase_txns[i]->GetHash()); bool expected = i >= 100; BOOST_CHECK_EQUAL(found, expected); } } } // Check that GetImmatureCredit() returns a newly calculated value instead of // the cached value after a MarkDirty() call. // // This is a regression test written to verify a bugfix for the immature credit // function. Similar tests probably should be written for the other credit and // debit functions. BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) { CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); LOCK(wallet.cs_wallet); LOCK(Assert(m_node.chainman)->GetMutex()); CWalletTx wtx{m_coinbase_txns.back(), TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/0}}; wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetupDescriptorScriptPubKeyMans(); wallet.SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash()); // Call GetImmatureCredit() once before adding the key to the wallet to // cache the current immature credit amount, which is 0. BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 0); // Invalidate the cached value, add the key, and make sure a new immature // credit amount is calculated. wtx.MarkDirty(); AddKey(wallet, coinbaseKey); BOOST_CHECK_EQUAL(CachedTxGetImmatureCredit(wallet, wtx, ISMINE_SPENDABLE), 50*COIN); } static int64_t AddTx(ChainstateManager& chainman, CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime) { CMutableTransaction tx; TxState state = TxStateInactive{}; tx.nLockTime = lockTime; SetMockTime(mockTime); CBlockIndex* block = nullptr; if (blockTime > 0) { LOCK(cs_main); auto inserted = chainman.BlockIndex().emplace(std::piecewise_construct, std::make_tuple(GetRandHash()), std::make_tuple()); assert(inserted.second); const uint256& hash = inserted.first->first; block = &inserted.first->second; block->nTime = blockTime; block->phashBlock = &hash; state = TxStateConfirmed{hash, block->nHeight, /*index=*/0}; } return wallet.AddToWallet(MakeTransactionRef(tx), state, [&](CWalletTx& wtx, bool /* new_tx */) { // Assign wtx.m_state to simplify test and avoid the need to simulate // reorg events. Without this, AddToWallet asserts false when the same // transaction is confirmed in different blocks. wtx.m_state = state; return true; })->nTimeSmart; } // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be // expanded to cover more corner cases of smart time logic. BOOST_AUTO_TEST_CASE(ComputeTimeSmart) { // New transaction should use clock time if lower than block time. BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 100, 120), 100); // Test that updating existing transaction does not change smart time. BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 1, 200, 220), 100); // New transaction should use clock time if there's no block time. BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 2, 300, 0), 300); // New transaction should use block time if lower than clock time. BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 3, 420, 400), 400); // New transaction should use latest entry time if higher than // min(block time, clock time). BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 4, 500, 390), 400); // If there are future entries, new transaction should use time of the // newest entry that is no more than 300 seconds ahead of the clock time. BOOST_CHECK_EQUAL(AddTx(*m_node.chainman, m_wallet, 5, 50, 600), 300); } void TestLoadWallet(const std::string& name, DatabaseFormat format, std::function<void(std::shared_ptr<CWallet>)> f) { node::NodeContext node; auto chain{interfaces::MakeChain(node)}; DatabaseOptions options; options.require_format = format; DatabaseStatus status; bilingual_str error; std::vector<bilingual_str> warnings; auto database{MakeWalletDatabase(name, options, status, error)}; auto wallet{std::make_shared<CWallet>(chain.get(), "", std::move(database))}; BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK); WITH_LOCK(wallet->cs_wallet, f(wallet)); } BOOST_FIXTURE_TEST_CASE(LoadReceiveRequests, TestingSetup) { for (DatabaseFormat format : DATABASE_FORMATS) { const std::string name{strprintf("receive-requests-%i", format)}; TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) { BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash())); WalletBatch batch{wallet->GetDatabase()}; BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), true)); BOOST_CHECK(batch.WriteAddressPreviouslySpent(ScriptHash(), true)); BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "0", "val_rr00")); BOOST_CHECK(wallet->EraseAddressReceiveRequest(batch, PKHash(), "0")); BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr10")); BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, PKHash(), "1", "val_rr11")); BOOST_CHECK(wallet->SetAddressReceiveRequest(batch, ScriptHash(), "2", "val_rr20")); }); TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) { BOOST_CHECK(wallet->IsAddressPreviouslySpent(PKHash())); BOOST_CHECK(wallet->IsAddressPreviouslySpent(ScriptHash())); auto requests = wallet->GetAddressReceiveRequests(); auto erequests = {"val_rr11", "val_rr20"}; BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests)); WalletBatch batch{wallet->GetDatabase()}; BOOST_CHECK(batch.WriteAddressPreviouslySpent(PKHash(), false)); BOOST_CHECK(batch.EraseAddressData(ScriptHash())); }); TestLoadWallet(name, format, [](std::shared_ptr<CWallet> wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet) { BOOST_CHECK(!wallet->IsAddressPreviouslySpent(PKHash())); BOOST_CHECK(!wallet->IsAddressPreviouslySpent(ScriptHash())); auto requests = wallet->GetAddressReceiveRequests(); auto erequests = {"val_rr11"}; BOOST_CHECK_EQUAL_COLLECTIONS(requests.begin(), requests.end(), std::begin(erequests), std::end(erequests)); }); } } // Test some watch-only LegacyScriptPubKeyMan methods by the procedure of loading (LoadWatchOnly), // checking (HaveWatchOnly), getting (GetWatchPubKey) and removing (RemoveWatchOnly) a // given PubKey, resp. its corresponding P2PK Script. Results of the impact on // the address -> PubKey map is dependent on whether the PubKey is a point on the curve static void TestWatchOnlyPubKey(LegacyScriptPubKeyMan* spk_man, const CPubKey& add_pubkey) { CScript p2pk = GetScriptForRawPubKey(add_pubkey); CKeyID add_address = add_pubkey.GetID(); CPubKey found_pubkey; LOCK(spk_man->cs_KeyStore); // all Scripts (i.e. also all PubKeys) are added to the general watch-only set BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk)); spk_man->LoadWatchOnly(p2pk); BOOST_CHECK(spk_man->HaveWatchOnly(p2pk)); // only PubKeys on the curve shall be added to the watch-only address -> PubKey map bool is_pubkey_fully_valid = add_pubkey.IsFullyValid(); if (is_pubkey_fully_valid) { BOOST_CHECK(spk_man->GetWatchPubKey(add_address, found_pubkey)); BOOST_CHECK(found_pubkey == add_pubkey); } else { BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey)); BOOST_CHECK(found_pubkey == CPubKey()); // passed key is unchanged } spk_man->RemoveWatchOnly(p2pk); BOOST_CHECK(!spk_man->HaveWatchOnly(p2pk)); if (is_pubkey_fully_valid) { BOOST_CHECK(!spk_man->GetWatchPubKey(add_address, found_pubkey)); BOOST_CHECK(found_pubkey == add_pubkey); // passed key is unchanged } } // Cryptographically invalidate a PubKey whilst keeping length and first byte static void PollutePubKey(CPubKey& pubkey) { std::vector<unsigned char> pubkey_raw(pubkey.begin(), pubkey.end()); std::fill(pubkey_raw.begin()+1, pubkey_raw.end(), 0); pubkey = CPubKey(pubkey_raw); assert(!pubkey.IsFullyValid()); assert(pubkey.IsValid()); } // Test watch-only logic for PubKeys BOOST_AUTO_TEST_CASE(WatchOnlyPubKeys) { CKey key; CPubKey pubkey; LegacyScriptPubKeyMan* spk_man = m_wallet.GetOrCreateLegacyScriptPubKeyMan(); BOOST_CHECK(!spk_man->HaveWatchOnly()); // uncompressed valid PubKey key.MakeNewKey(false); pubkey = key.GetPubKey(); assert(!pubkey.IsCompressed()); TestWatchOnlyPubKey(spk_man, pubkey); // uncompressed cryptographically invalid PubKey PollutePubKey(pubkey); TestWatchOnlyPubKey(spk_man, pubkey); // compressed valid PubKey key.MakeNewKey(true); pubkey = key.GetPubKey(); assert(pubkey.IsCompressed()); TestWatchOnlyPubKey(spk_man, pubkey); // compressed cryptographically invalid PubKey PollutePubKey(pubkey); TestWatchOnlyPubKey(spk_man, pubkey); // invalid empty PubKey pubkey = CPubKey(); TestWatchOnlyPubKey(spk_man, pubkey); } class ListCoinsTestingSetup : public TestChain100Setup { public: ListCoinsTestingSetup() { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey); } ~ListCoinsTestingSetup() { wallet.reset(); } CWalletTx& AddTx(CRecipient recipient) { CTransactionRef tx; CCoinControl dummy; { auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, dummy); BOOST_CHECK(res); tx = res->tx; } wallet->CommitTransaction(tx, {}, {}); CMutableTransaction blocktx; { LOCK(wallet->cs_wallet); blocktx = CMutableTransaction(*wallet->mapWallet.at(tx->GetHash()).tx); } CreateAndProcessBlock({CMutableTransaction(blocktx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); LOCK(wallet->cs_wallet); LOCK(Assert(m_node.chainman)->GetMutex()); wallet->SetLastBlockProcessed(wallet->GetLastBlockHeight() + 1, m_node.chainman->ActiveChain().Tip()->GetBlockHash()); auto it = wallet->mapWallet.find(tx->GetHash()); BOOST_CHECK(it != wallet->mapWallet.end()); it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1}; return it->second; } std::unique_ptr<CWallet> wallet; }; BOOST_FIXTURE_TEST_CASE(ListCoinsTest, ListCoinsTestingSetup) { std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString(); // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey // address. std::map<CTxDestination, std::vector<COutput>> list; { LOCK(wallet->cs_wallet); list = ListCoins(*wallet); } BOOST_CHECK_EQUAL(list.size(), 1U); BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 1U); // Check initial balance from one mature coinbase transaction. BOOST_CHECK_EQUAL(50 * COIN, WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet).GetTotalAmount())); // Add a transaction creating a change address, and confirm ListCoins still // returns the coin associated with the change address underneath the // coinbaseKey pubkey, even though the change address has a different // pubkey. AddTx(CRecipient{PubKeyDestination{{}}, 1 * COIN, /*subtract_fee=*/false}); { LOCK(wallet->cs_wallet); list = ListCoins(*wallet); } BOOST_CHECK_EQUAL(list.size(), 1U); BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U); // Lock both coins. Confirm number of available coins drops to 0. { LOCK(wallet->cs_wallet); BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 2U); } for (const auto& group : list) { for (const auto& coin : group.second) { LOCK(wallet->cs_wallet); wallet->LockCoin(coin.outpoint); } } { LOCK(wallet->cs_wallet); BOOST_CHECK_EQUAL(AvailableCoinsListUnspent(*wallet).Size(), 0U); } // Confirm ListCoins still returns same result as before, despite coins // being locked. { LOCK(wallet->cs_wallet); list = ListCoins(*wallet); } BOOST_CHECK_EQUAL(list.size(), 1U); BOOST_CHECK_EQUAL(std::get<PKHash>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 2U); } void TestCoinsResult(ListCoinsTest& context, OutputType out_type, CAmount amount, std::map<OutputType, size_t>& expected_coins_sizes) { LOCK(context.wallet->cs_wallet); util::Result<CTxDestination> dest = Assert(context.wallet->GetNewDestination(out_type, "")); CWalletTx& wtx = context.AddTx(CRecipient{*dest, amount, /*fSubtractFeeFromAmount=*/true}); CoinFilterParams filter; filter.skip_locked = false; CoinsResult available_coins = AvailableCoins(*context.wallet, nullptr, std::nullopt, filter); // Lock outputs so they are not spent in follow-up transactions for (uint32_t i = 0; i < wtx.tx->vout.size(); i++) context.wallet->LockCoin({wtx.GetHash(), i}); for (const auto& [type, size] : expected_coins_sizes) BOOST_CHECK_EQUAL(size, available_coins.coins[type].size()); } BOOST_FIXTURE_TEST_CASE(BasicOutputTypesTest, ListCoinsTest) { std::map<OutputType, size_t> expected_coins_sizes; for (const auto& out_type : OUTPUT_TYPES) { expected_coins_sizes[out_type] = 0U; } // Verify our wallet has one usable coinbase UTXO before starting // This UTXO is a P2PK, so it should show up in the Other bucket expected_coins_sizes[OutputType::UNKNOWN] = 1U; CoinsResult available_coins = WITH_LOCK(wallet->cs_wallet, return AvailableCoins(*wallet)); BOOST_CHECK_EQUAL(available_coins.Size(), expected_coins_sizes[OutputType::UNKNOWN]); BOOST_CHECK_EQUAL(available_coins.coins[OutputType::UNKNOWN].size(), expected_coins_sizes[OutputType::UNKNOWN]); // We will create a self transfer for each of the OutputTypes and // verify it is put in the correct bucket after running GetAvailablecoins // // For each OutputType, We expect 2 UTXOs in our wallet following the self transfer: // 1. One UTXO as the recipient // 2. One UTXO from the change, due to payment address matching logic for (const auto& out_type : OUTPUT_TYPES) { if (out_type == OutputType::UNKNOWN) continue; expected_coins_sizes[out_type] = 2U; TestCoinsResult(*this, out_type, 1 * COIN, expected_coins_sizes); } } BOOST_FIXTURE_TEST_CASE(wallet_disableprivkeys, TestChain100Setup) { { const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase()); wallet->SetupLegacyScriptPubKeyMan(); wallet->SetMinVersion(FEATURE_LATEST); wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); BOOST_CHECK(!wallet->TopUpKeyPool(1000)); BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "")); } { const std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase()); LOCK(wallet->cs_wallet); wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet->SetMinVersion(FEATURE_LATEST); wallet->SetWalletFlag(WALLET_FLAG_DISABLE_PRIVATE_KEYS); BOOST_CHECK(!wallet->GetNewDestination(OutputType::BECH32, "")); } } // Explicit calculation which is used to test the wallet constant // We get the same virtual size due to rounding(weight/4) for both use_max_sig values static size_t CalculateNestedKeyhashInputSize(bool use_max_sig) { // Generate ephemeral valid pubkey CKey key; key.MakeNewKey(true); CPubKey pubkey = key.GetPubKey(); // Generate pubkey hash uint160 key_hash(Hash160(pubkey)); // Create inner-script to enter into keystore. Key hash can't be 0... CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end()); // Create outer P2SH script for the output uint160 script_id(Hash160(inner_script)); CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL; // Add inner-script to key store and key to watchonly FillableSigningProvider keystore; keystore.AddCScript(inner_script); keystore.AddKeyPubKey(key, pubkey); // Fill in dummy signatures for fee calculation. SignatureData sig_data; if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) { // We're hand-feeding it correct arguments; shouldn't happen assert(false); } CTxIn tx_in; UpdateInput(tx_in, sig_data); return (size_t)GetVirtualTransactionInputSize(tx_in); } BOOST_FIXTURE_TEST_CASE(dummy_input_size_test, TestChain100Setup) { BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(false), DUMMY_NESTED_P2WPKH_INPUT_SIZE); BOOST_CHECK_EQUAL(CalculateNestedKeyhashInputSize(true), DUMMY_NESTED_P2WPKH_INPUT_SIZE); } bool malformed_descriptor(std::ios_base::failure e) { std::string s(e.what()); return s.find("Missing checksum") != std::string::npos; } BOOST_FIXTURE_TEST_CASE(wallet_descriptor_test, BasicTestingSetup) { std::vector<unsigned char> malformed_record; VectorWriter vw{malformed_record, 0}; vw << std::string("notadescriptor"); vw << uint64_t{0}; vw << int32_t{0}; vw << int32_t{0}; vw << int32_t{1}; SpanReader vr{malformed_record}; WalletDescriptor w_desc; BOOST_CHECK_EXCEPTION(vr >> w_desc, std::ios_base::failure, malformed_descriptor); } //! Test CWallet::Create() and its behavior handling potential race //! conditions if it's called the same time an incoming transaction shows up in //! the mempool or a new block. //! //! It isn't possible to verify there aren't race condition in every case, so //! this test just checks two specific cases and ensures that timing of //! notifications in these cases doesn't prevent the wallet from detecting //! transactions. //! //! In the first case, block and mempool transactions are created before the //! wallet is loaded, but notifications about these transactions are delayed //! until after it is loaded. The notifications are superfluous in this case, so //! the test verifies the transactions are detected before they arrive. //! //! In the second case, block and mempool transactions are created after the //! wallet rescan and notifications are immediately synced, to verify the wallet //! must already have a handler in place for them, and there's no gap after //! rescanning where new transactions in new blocks could be lost. BOOST_FIXTURE_TEST_CASE(CreateWallet, TestChain100Setup) { m_args.ForceSetArg("-unsafesqlitesync", "1"); // Create new wallet with known key and unload it. WalletContext context; context.args = &m_args; context.chain = m_node.chain.get(); auto wallet = TestLoadWallet(context); CKey key; key.MakeNewKey(true); AddKey(*wallet, key); TestUnloadWallet(std::move(wallet)); // Add log hook to detect AddToWallet events from rescans, blockConnected, // and transactionAddedToMempool notifications int addtx_count = 0; DebugLogHelper addtx_counter("[default wallet] AddToWallet", [&](const std::string* s) { if (s) ++addtx_count; return false; }); bool rescan_completed = false; DebugLogHelper rescan_check("[default wallet] Rescan completed", [&](const std::string* s) { if (s) rescan_completed = true; return false; }); // Block the queue to prevent the wallet receiving blockConnected and // transactionAddedToMempool notifications, and create block and mempool // transactions paying to the wallet std::promise<void> promise; CallFunctionInValidationInterfaceQueue([&promise] { promise.get_future().wait(); }); std::string error; m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey())); m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); auto mempool_tx = TestSimpleSpend(*m_coinbase_txns[1], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey())); BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error)); // Reload wallet and make sure new transactions are detected despite events // being blocked // Loading will also ask for current mempool transactions wallet = TestLoadWallet(context); BOOST_CHECK(rescan_completed); // AddToWallet events for block_tx and mempool_tx (x2) BOOST_CHECK_EQUAL(addtx_count, 3); { LOCK(wallet->cs_wallet); BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U); BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U); } // Unblock notification queue and make sure stale blockConnected and // transactionAddedToMempool events are processed promise.set_value(); SyncWithValidationInterfaceQueue(); // AddToWallet events for block_tx and mempool_tx events are counted a // second time as the notification queue is processed BOOST_CHECK_EQUAL(addtx_count, 5); TestUnloadWallet(std::move(wallet)); // Load wallet again, this time creating new block and mempool transactions // paying to the wallet as the wallet finishes loading and syncing the // queue so the events have to be handled immediately. Releasing the wallet // lock during the sync is a little artificial but is needed to avoid a // deadlock during the sync and simulates a new block notification happening // as soon as possible. addtx_count = 0; auto handler = HandleLoadWallet(context, [&](std::unique_ptr<interfaces::Wallet> wallet) { BOOST_CHECK(rescan_completed); m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); block_tx = TestSimpleSpend(*m_coinbase_txns[2], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey())); m_coinbase_txns.push_back(CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); mempool_tx = TestSimpleSpend(*m_coinbase_txns[3], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey())); BOOST_CHECK(m_node.chain->broadcastTransaction(MakeTransactionRef(mempool_tx), DEFAULT_TRANSACTION_MAXFEE, false, error)); SyncWithValidationInterfaceQueue(); }); wallet = TestLoadWallet(context); // Since mempool transactions are requested at the end of loading, there will // be 2 additional AddToWallet calls, one from the previous test, and a duplicate for mempool_tx BOOST_CHECK_EQUAL(addtx_count, 2 + 2); { LOCK(wallet->cs_wallet); BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_tx.GetHash()), 1U); BOOST_CHECK_EQUAL(wallet->mapWallet.count(mempool_tx.GetHash()), 1U); } TestUnloadWallet(std::move(wallet)); } BOOST_FIXTURE_TEST_CASE(CreateWalletWithoutChain, BasicTestingSetup) { WalletContext context; context.args = &m_args; auto wallet = TestLoadWallet(context); BOOST_CHECK(wallet); UnloadWallet(std::move(wallet)); } BOOST_FIXTURE_TEST_CASE(ZapSelectTx, TestChain100Setup) { m_args.ForceSetArg("-unsafesqlitesync", "1"); WalletContext context; context.args = &m_args; context.chain = m_node.chain.get(); auto wallet = TestLoadWallet(context); CKey key; key.MakeNewKey(true); AddKey(*wallet, key); std::string error; m_coinbase_txns.push_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); auto block_tx = TestSimpleSpend(*m_coinbase_txns[0], 0, coinbaseKey, GetScriptForRawPubKey(key.GetPubKey())); CreateAndProcessBlock({block_tx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); SyncWithValidationInterfaceQueue(); { auto block_hash = block_tx.GetHash(); auto prev_tx = m_coinbase_txns[0]; LOCK(wallet->cs_wallet); BOOST_CHECK(wallet->HasWalletSpend(prev_tx)); BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 1u); std::vector<uint256> vHashIn{ block_hash }, vHashOut; BOOST_CHECK_EQUAL(wallet->ZapSelectTx(vHashIn, vHashOut), DBErrors::LOAD_OK); BOOST_CHECK(!wallet->HasWalletSpend(prev_tx)); BOOST_CHECK_EQUAL(wallet->mapWallet.count(block_hash), 0u); } TestUnloadWallet(std::move(wallet)); } /** * Checks a wallet invalid state where the inputs (prev-txs) of a new arriving transaction are not marked dirty, * while the transaction that spends them exist inside the in-memory wallet tx map (not stored on db due a db write failure). */ BOOST_FIXTURE_TEST_CASE(wallet_sync_tx_invalid_state_test, TestingSetup) { CWallet wallet(m_node.chain.get(), "", CreateMockableWalletDatabase()); { LOCK(wallet.cs_wallet); wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetupDescriptorScriptPubKeyMans(); } // Add tx to wallet const auto op_dest{*Assert(wallet.GetNewDestination(OutputType::BECH32M, ""))}; CMutableTransaction mtx; mtx.vout.emplace_back(COIN, GetScriptForDestination(op_dest)); mtx.vin.emplace_back(Txid::FromUint256(g_insecure_rand_ctx.rand256()), 0); const auto& tx_id_to_spend = wallet.AddToWallet(MakeTransactionRef(mtx), TxStateInMempool{})->GetHash(); { // Cache and verify available balance for the wtx LOCK(wallet.cs_wallet); const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend); BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 1 * COIN); } // Now the good case: // 1) Add a transaction that spends the previously created transaction // 2) Verify that the available balance of this new tx and the old one is updated (prev tx is marked dirty) mtx.vin.clear(); mtx.vin.emplace_back(tx_id_to_spend, 0); wallet.transactionAddedToMempool(MakeTransactionRef(mtx)); const auto good_tx_id{mtx.GetHash()}; { // Verify balance update for the new tx and the old one LOCK(wallet.cs_wallet); const CWalletTx* new_wtx = wallet.GetWalletTx(good_tx_id.ToUint256()); BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *new_wtx), 1 * COIN); // Now the old wtx const CWalletTx* wtx_to_spend = wallet.GetWalletTx(tx_id_to_spend); BOOST_CHECK_EQUAL(CachedTxGetAvailableCredit(wallet, *wtx_to_spend), 0 * COIN); } // Now the bad case: // 1) Make db always fail // 2) Try to add a transaction that spends the previously created transaction and // verify that we are not moving forward if the wallet cannot store it GetMockableDatabase(wallet).m_pass = false; mtx.vin.clear(); mtx.vin.emplace_back(good_tx_id, 0); BOOST_CHECK_EXCEPTION(wallet.transactionAddedToMempool(MakeTransactionRef(mtx)), std::runtime_error, HasReason("DB error adding transaction to wallet, write failed")); } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/coinselector_tests.cpp
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/amount.h> #include <node/context.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <random.h> #include <test/util/setup_common.h> #include <util/translation.h> #include <wallet/coincontrol.h> #include <wallet/coinselection.h> #include <wallet/spend.h> #include <wallet/test/util.h> #include <wallet/test/wallet_test_fixture.h> #include <wallet/wallet.h> #include <algorithm> #include <boost/test/unit_test.hpp> #include <random> namespace wallet { BOOST_FIXTURE_TEST_SUITE(coinselector_tests, WalletTestingSetup) // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles #define RUN_TESTS 100 // some tests fail 1% of the time due to bad luck. // we repeat those tests this many times and only complain if all iterations of the test fail #define RANDOM_REPEATS 5 typedef std::set<std::shared_ptr<COutput>> CoinSet; static const CoinEligibilityFilter filter_standard(1, 6, 0); static const CoinEligibilityFilter filter_confirmed(1, 1, 0); static const CoinEligibilityFilter filter_standard_extra(6, 6, 0); static int nextLockTime = 0; static void add_coin(const CAmount& nValue, int nInput, std::vector<COutput>& set) { CMutableTransaction tx; tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; tx.nLockTime = nextLockTime++; // so all transactions get different hashes set.emplace_back(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0); } static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result) { CMutableTransaction tx; tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; tx.nLockTime = nextLockTime++; // so all transactions get different hashes COutput output(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0); OutputGroup group; group.Insert(std::make_shared<COutput>(output), /*ancestors=*/ 0, /*descendants=*/ 0); result.AddInput(group); } static void add_coin(const CAmount& nValue, int nInput, SelectionResult& result, CAmount fee, CAmount long_term_fee) { CMutableTransaction tx; tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; tx.nLockTime = nextLockTime++; // so all transactions get different hashes std::shared_ptr<COutput> coin = std::make_shared<COutput>(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ 148, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, fee); OutputGroup group; group.Insert(coin, /*ancestors=*/ 0, /*descendants=*/ 0); coin->long_term_fee = long_term_fee; // group.Insert() will modify long_term_fee, so we need to set it afterwards result.AddInput(group); } static void add_coin(CoinsResult& available_coins, CWallet& wallet, const CAmount& nValue, CFeeRate feerate = CFeeRate(0), int nAge = 6*24, bool fIsFromMe = false, int nInput =0, bool spendable = false, int custom_size = 0) { CMutableTransaction tx; tx.nLockTime = nextLockTime++; // so all transactions get different hashes tx.vout.resize(nInput + 1); tx.vout[nInput].nValue = nValue; if (spendable) { tx.vout[nInput].scriptPubKey = GetScriptForDestination(*Assert(wallet.GetNewDestination(OutputType::BECH32, ""))); } uint256 txid = tx.GetHash(); LOCK(wallet.cs_wallet); auto ret = wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid), std::forward_as_tuple(MakeTransactionRef(std::move(tx)), TxStateInactive{})); assert(ret.second); CWalletTx& wtx = (*ret.first).second; const auto& txout = wtx.tx->vout.at(nInput); available_coins.Add(OutputType::BECH32, {COutPoint(wtx.GetHash(), nInput), txout, nAge, custom_size == 0 ? CalculateMaximumSignedInputSize(txout, &wallet, /*coin_control=*/nullptr) : custom_size, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, wtx.GetTxTime(), fIsFromMe, feerate}); } // Helpers std::optional<SelectionResult> KnapsackSolver(std::vector<OutputGroup>& groups, const CAmount& nTargetValue, CAmount change_target, FastRandomContext& rng) { auto res{KnapsackSolver(groups, nTargetValue, change_target, rng, MAX_STANDARD_TX_WEIGHT)}; return res ? std::optional<SelectionResult>(*res) : std::nullopt; } std::optional<SelectionResult> SelectCoinsBnB(std::vector<OutputGroup>& utxo_pool, const CAmount& selection_target, const CAmount& cost_of_change) { auto res{SelectCoinsBnB(utxo_pool, selection_target, cost_of_change, MAX_STANDARD_TX_WEIGHT)}; return res ? std::optional<SelectionResult>(*res) : std::nullopt; } /** Check if SelectionResult a is equivalent to SelectionResult b. * Equivalent means same input values, but maybe different inputs (i.e. same value, different prevout) */ static bool EquivalentResult(const SelectionResult& a, const SelectionResult& b) { std::vector<CAmount> a_amts; std::vector<CAmount> b_amts; for (const auto& coin : a.GetInputSet()) { a_amts.push_back(coin->txout.nValue); } for (const auto& coin : b.GetInputSet()) { b_amts.push_back(coin->txout.nValue); } std::sort(a_amts.begin(), a_amts.end()); std::sort(b_amts.begin(), b_amts.end()); std::pair<std::vector<CAmount>::iterator, std::vector<CAmount>::iterator> ret = std::mismatch(a_amts.begin(), a_amts.end(), b_amts.begin()); return ret.first == a_amts.end() && ret.second == b_amts.end(); } /** Check if this selection is equal to another one. Equal means same inputs (i.e same value and prevout) */ static bool EqualResult(const SelectionResult& a, const SelectionResult& b) { std::pair<CoinSet::iterator, CoinSet::iterator> ret = std::mismatch(a.GetInputSet().begin(), a.GetInputSet().end(), b.GetInputSet().begin(), [](const std::shared_ptr<COutput>& a, const std::shared_ptr<COutput>& b) { return a->outpoint == b->outpoint; }); return ret.first == a.GetInputSet().end() && ret.second == b.GetInputSet().end(); } static CAmount make_hard_case(int utxos, std::vector<COutput>& utxo_pool) { utxo_pool.clear(); CAmount target = 0; for (int i = 0; i < utxos; ++i) { target += CAmount{1} << (utxos+i); add_coin(CAmount{1} << (utxos+i), 2*i, utxo_pool); add_coin((CAmount{1} << (utxos+i)) + (CAmount{1} << (utxos-1-i)), 2*i + 1, utxo_pool); } return target; } inline std::vector<OutputGroup>& GroupCoins(const std::vector<COutput>& available_coins, bool subtract_fee_outputs = false) { static std::vector<OutputGroup> static_groups; static_groups.clear(); for (auto& coin : available_coins) { static_groups.emplace_back(); OutputGroup& group = static_groups.back(); group.Insert(std::make_shared<COutput>(coin), /*ancestors=*/ 0, /*descendants=*/ 0); group.m_subtract_fee_outputs = subtract_fee_outputs; } return static_groups; } inline std::vector<OutputGroup>& KnapsackGroupOutputs(const CoinsResult& available_coins, CWallet& wallet, const CoinEligibilityFilter& filter) { FastRandomContext rand{}; CoinSelectionParams coin_selection_params{ rand, /*change_output_size=*/ 0, /*change_spend_size=*/ 0, /*min_change_target=*/ CENT, /*effective_feerate=*/ CFeeRate(0), /*long_term_feerate=*/ CFeeRate(0), /*discard_feerate=*/ CFeeRate(0), /*tx_noinputs_size=*/ 0, /*avoid_partial=*/ false, }; static OutputGroupTypeMap static_groups; static_groups = GroupOutputs(wallet, available_coins, coin_selection_params, {{filter}})[filter]; return static_groups.all_groups.mixed_group; } static std::unique_ptr<CWallet> NewWallet(const node::NodeContext& m_node, const std::string& wallet_name = "") { std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), wallet_name, CreateMockableWalletDatabase()); BOOST_CHECK(wallet->LoadWallet() == DBErrors::LOAD_OK); LOCK(wallet->cs_wallet); wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet->SetupDescriptorScriptPubKeyMans(); return wallet; } // Branch and bound coin selection tests BOOST_AUTO_TEST_CASE(bnb_search_test) { FastRandomContext rand{}; // Setup std::vector<COutput> utxo_pool; SelectionResult expected_result(CAmount(0), SelectionAlgorithm::BNB); ///////////////////////// // Known Outcome tests // ///////////////////////// // Empty utxo pool BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT)); // Add utxos add_coin(1 * CENT, 1, utxo_pool); add_coin(2 * CENT, 2, utxo_pool); add_coin(3 * CENT, 3, utxo_pool); add_coin(4 * CENT, 4, utxo_pool); // Select 1 Cent add_coin(1 * CENT, 1, expected_result); const auto result1 = SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 0.5 * CENT); BOOST_CHECK(result1); BOOST_CHECK(EquivalentResult(expected_result, *result1)); BOOST_CHECK_EQUAL(result1->GetSelectedValue(), 1 * CENT); expected_result.Clear(); // Select 2 Cent add_coin(2 * CENT, 2, expected_result); const auto result2 = SelectCoinsBnB(GroupCoins(utxo_pool), 2 * CENT, 0.5 * CENT); BOOST_CHECK(result2); BOOST_CHECK(EquivalentResult(expected_result, *result2)); BOOST_CHECK_EQUAL(result2->GetSelectedValue(), 2 * CENT); expected_result.Clear(); // Select 5 Cent add_coin(3 * CENT, 3, expected_result); add_coin(2 * CENT, 2, expected_result); const auto result3 = SelectCoinsBnB(GroupCoins(utxo_pool), 5 * CENT, 0.5 * CENT); BOOST_CHECK(result3); BOOST_CHECK(EquivalentResult(expected_result, *result3)); BOOST_CHECK_EQUAL(result3->GetSelectedValue(), 5 * CENT); expected_result.Clear(); // Select 11 Cent, not possible BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 11 * CENT, 0.5 * CENT)); expected_result.Clear(); // Cost of change is greater than the difference between target value and utxo sum add_coin(1 * CENT, 1, expected_result); const auto result4 = SelectCoinsBnB(GroupCoins(utxo_pool), 0.9 * CENT, 0.5 * CENT); BOOST_CHECK(result4); BOOST_CHECK_EQUAL(result4->GetSelectedValue(), 1 * CENT); BOOST_CHECK(EquivalentResult(expected_result, *result4)); expected_result.Clear(); // Cost of change is less than the difference between target value and utxo sum BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.9 * CENT, 0)); expected_result.Clear(); // Select 10 Cent add_coin(5 * CENT, 5, utxo_pool); add_coin(4 * CENT, 4, expected_result); add_coin(3 * CENT, 3, expected_result); add_coin(2 * CENT, 2, expected_result); add_coin(1 * CENT, 1, expected_result); const auto result5 = SelectCoinsBnB(GroupCoins(utxo_pool), 10 * CENT, 0.5 * CENT); BOOST_CHECK(result5); BOOST_CHECK(EquivalentResult(expected_result, *result5)); BOOST_CHECK_EQUAL(result5->GetSelectedValue(), 10 * CENT); expected_result.Clear(); // Select 0.25 Cent, not possible BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 0.25 * CENT, 0.5 * CENT)); expected_result.Clear(); // Iteration exhaustion test CAmount target = make_hard_case(17, utxo_pool); BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), target, 1)); // Should exhaust target = make_hard_case(14, utxo_pool); const auto result7 = SelectCoinsBnB(GroupCoins(utxo_pool), target, 1); // Should not exhaust BOOST_CHECK(result7); // Test same value early bailout optimization utxo_pool.clear(); add_coin(7 * CENT, 7, expected_result); add_coin(7 * CENT, 7, expected_result); add_coin(7 * CENT, 7, expected_result); add_coin(7 * CENT, 7, expected_result); add_coin(2 * CENT, 7, expected_result); add_coin(7 * CENT, 7, utxo_pool); add_coin(7 * CENT, 7, utxo_pool); add_coin(7 * CENT, 7, utxo_pool); add_coin(7 * CENT, 7, utxo_pool); add_coin(2 * CENT, 7, utxo_pool); for (int i = 0; i < 50000; ++i) { add_coin(5 * CENT, 7, utxo_pool); } const auto result8 = SelectCoinsBnB(GroupCoins(utxo_pool), 30 * CENT, 5000); BOOST_CHECK(result8); BOOST_CHECK_EQUAL(result8->GetSelectedValue(), 30 * CENT); BOOST_CHECK(EquivalentResult(expected_result, *result8)); //////////////////// // Behavior tests // //////////////////// // Select 1 Cent with pool of only greater than 5 Cent utxo_pool.clear(); for (int i = 5; i <= 20; ++i) { add_coin(i * CENT, i, utxo_pool); } // Run 100 times, to make sure it is never finding a solution for (int i = 0; i < 100; ++i) { BOOST_CHECK(!SelectCoinsBnB(GroupCoins(utxo_pool), 1 * CENT, 2 * CENT)); } // Make sure that effective value is working in AttemptSelection when BnB is used CoinSelectionParams coin_selection_params_bnb{ rand, /*change_output_size=*/ 31, /*change_spend_size=*/ 68, /*min_change_target=*/ 0, /*effective_feerate=*/ CFeeRate(3000), /*long_term_feerate=*/ CFeeRate(1000), /*discard_feerate=*/ CFeeRate(1000), /*tx_noinputs_size=*/ 0, /*avoid_partial=*/ false, }; coin_selection_params_bnb.m_change_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_output_size); coin_selection_params_bnb.m_cost_of_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size) + coin_selection_params_bnb.m_change_fee; coin_selection_params_bnb.min_viable_change = coin_selection_params_bnb.m_effective_feerate.GetFee(coin_selection_params_bnb.change_spend_size); { std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinsResult available_coins; add_coin(available_coins, *wallet, 1, coin_selection_params_bnb.m_effective_feerate); available_coins.All().at(0).input_bytes = 40; // Make sure that it has a negative effective value. The next check should assert if this somehow got through. Otherwise it will fail BOOST_CHECK(!SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change)); // Test fees subtracted from output: available_coins.Clear(); add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate); available_coins.All().at(0).input_bytes = 40; const auto result9 = SelectCoinsBnB(GroupCoins(available_coins.All()), 1 * CENT, coin_selection_params_bnb.m_cost_of_change); BOOST_CHECK(result9); BOOST_CHECK_EQUAL(result9->GetSelectedValue(), 1 * CENT); } { std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinsResult available_coins; coin_selection_params_bnb.m_effective_feerate = CFeeRate(0); add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 2 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); CCoinControl coin_control; coin_control.m_allow_other_inputs = true; COutput select_coin = available_coins.All().at(0); coin_control.Select(select_coin.outpoint); PreSelectedInputs selected_input; selected_input.Insert(select_coin, coin_selection_params_bnb.m_subtract_fee_outputs); available_coins.Erase({available_coins.coins[OutputType::BECH32].begin()->outpoint}); LOCK(wallet->cs_wallet); const auto result10 = SelectCoins(*wallet, available_coins, selected_input, 10 * CENT, coin_control, coin_selection_params_bnb); BOOST_CHECK(result10); } { std::unique_ptr<CWallet> wallet = NewWallet(m_node); LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it CoinsResult available_coins; // single coin should be selected when effective fee > long term fee coin_selection_params_bnb.m_effective_feerate = CFeeRate(5000); coin_selection_params_bnb.m_long_term_feerate = CFeeRate(3000); // Add selectable outputs, increasing their raw amounts by their input fee to make the effective value equal to the raw amount CAmount input_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(/*num_bytes=*/68); // bech32 input size (default test output type) add_coin(available_coins, *wallet, 10 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 9 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 1 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); expected_result.Clear(); add_coin(10 * CENT + input_fee, 2, expected_result); CCoinControl coin_control; const auto result11 = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, 10 * CENT, coin_control, coin_selection_params_bnb); BOOST_CHECK(EquivalentResult(expected_result, *result11)); available_coins.Clear(); // more coins should be selected when effective fee < long term fee coin_selection_params_bnb.m_effective_feerate = CFeeRate(3000); coin_selection_params_bnb.m_long_term_feerate = CFeeRate(5000); // Add selectable outputs, increasing their raw amounts by their input fee to make the effective value equal to the raw amount input_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(/*num_bytes=*/68); // bech32 input size (default test output type) add_coin(available_coins, *wallet, 10 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 9 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 1 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); expected_result.Clear(); add_coin(9 * CENT + input_fee, 2, expected_result); add_coin(1 * CENT + input_fee, 2, expected_result); const auto result12 = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, 10 * CENT, coin_control, coin_selection_params_bnb); BOOST_CHECK(EquivalentResult(expected_result, *result12)); available_coins.Clear(); // pre selected coin should be selected even if disadvantageous coin_selection_params_bnb.m_effective_feerate = CFeeRate(5000); coin_selection_params_bnb.m_long_term_feerate = CFeeRate(3000); // Add selectable outputs, increasing their raw amounts by their input fee to make the effective value equal to the raw amount input_fee = coin_selection_params_bnb.m_effective_feerate.GetFee(/*num_bytes=*/68); // bech32 input size (default test output type) add_coin(available_coins, *wallet, 10 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 9 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 1 * CENT + input_fee, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); expected_result.Clear(); add_coin(9 * CENT + input_fee, 2, expected_result); add_coin(1 * CENT + input_fee, 2, expected_result); coin_control.m_allow_other_inputs = true; COutput select_coin = available_coins.All().at(1); // pre select 9 coin coin_control.Select(select_coin.outpoint); PreSelectedInputs selected_input; selected_input.Insert(select_coin, coin_selection_params_bnb.m_subtract_fee_outputs); available_coins.Erase({(++available_coins.coins[OutputType::BECH32].begin())->outpoint}); const auto result13 = SelectCoins(*wallet, available_coins, selected_input, 10 * CENT, coin_control, coin_selection_params_bnb); BOOST_CHECK(EquivalentResult(expected_result, *result13)); } { // Test bnb max weight exceeded // Inputs set [10, 9, 8, 5, 3, 1], Selection Target = 16 and coin 5 exceeding the max weight. std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinsResult available_coins; add_coin(available_coins, *wallet, 10 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 9 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 8 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true, /*custom_size=*/MAX_STANDARD_TX_WEIGHT); add_coin(available_coins, *wallet, 3 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); add_coin(available_coins, *wallet, 1 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); CAmount selection_target = 16 * CENT; const auto& no_res = SelectCoinsBnB(GroupCoins(available_coins.All(), /*subtract_fee_outputs*/true), selection_target, /*cost_of_change=*/0, MAX_STANDARD_TX_WEIGHT); BOOST_REQUIRE(!no_res); BOOST_CHECK(util::ErrorString(no_res).original.find("The inputs size exceeds the maximum weight") != std::string::npos); // Now add same coin value with a good size and check that it gets selected add_coin(available_coins, *wallet, 5 * CENT, coin_selection_params_bnb.m_effective_feerate, 6 * 24, false, 0, true); const auto& res = SelectCoinsBnB(GroupCoins(available_coins.All(), /*subtract_fee_outputs*/true), selection_target, /*cost_of_change=*/0); expected_result.Clear(); add_coin(8 * CENT, 2, expected_result); add_coin(5 * CENT, 2, expected_result); add_coin(3 * CENT, 2, expected_result); BOOST_CHECK(EquivalentResult(expected_result, *res)); } } BOOST_AUTO_TEST_CASE(bnb_sffo_restriction) { // Verify the coin selection process does not produce a BnB solution when SFFO is enabled. // This is currently problematic because it could require a change output. And BnB is specialized on changeless solutions. std::unique_ptr<CWallet> wallet = NewWallet(m_node); WITH_LOCK(wallet->cs_wallet, wallet->SetLastBlockProcessed(300, uint256{})); // set a high block so internal UTXOs are selectable FastRandomContext rand{}; CoinSelectionParams params{ rand, /*change_output_size=*/ 31, // unused value, p2wpkh output size (wallet default change type) /*change_spend_size=*/ 68, // unused value, p2wpkh input size (high-r signature) /*min_change_target=*/ 0, // dummy, set later /*effective_feerate=*/ CFeeRate(3000), /*long_term_feerate=*/ CFeeRate(1000), /*discard_feerate=*/ CFeeRate(1000), /*tx_noinputs_size=*/ 0, /*avoid_partial=*/ false, }; params.m_subtract_fee_outputs = true; params.m_change_fee = params.m_effective_feerate.GetFee(params.change_output_size); params.m_cost_of_change = params.m_discard_feerate.GetFee(params.change_spend_size) + params.m_change_fee; params.m_min_change_target = params.m_cost_of_change + 1; // Add spendable coin at the BnB selection upper bound CoinsResult available_coins; add_coin(available_coins, *wallet, COIN + params.m_cost_of_change, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true); add_coin(available_coins, *wallet, 0.5 * COIN + params.m_cost_of_change, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true); add_coin(available_coins, *wallet, 0.5 * COIN, /*feerate=*/params.m_effective_feerate, /*nAge=*/6, /*fIsFromMe=*/true, /*nInput=*/0, /*spendable=*/true); // Knapsack will only find a changeless solution on an exact match to the satoshi, SRD doesn’t look for changeless // If BnB were run, it would produce a single input solution with the best waste score auto result = WITH_LOCK(wallet->cs_wallet, return SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, COIN, /*coin_control=*/{}, params)); BOOST_CHECK(result.has_value()); BOOST_CHECK_NE(result->GetAlgo(), SelectionAlgorithm::BNB); BOOST_CHECK(result->GetInputSet().size() == 2); // We have only considered BnB, SRD, and Knapsack. Test needs to be reevaluated if new algo is added BOOST_CHECK(result->GetAlgo() == SelectionAlgorithm::SRD || result->GetAlgo() == SelectionAlgorithm::KNAPSACK); } BOOST_AUTO_TEST_CASE(knapsack_solver_test) { FastRandomContext rand{}; const auto temp1{[&rand](std::vector<OutputGroup>& g, const CAmount& v, CAmount c) { return KnapsackSolver(g, v, c, rand); }}; const auto KnapsackSolver{temp1}; std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinsResult available_coins; // test multiple times to allow for differences in the shuffle order for (int i = 0; i < RUN_TESTS; i++) { available_coins.Clear(); // with an empty wallet we can't even pay one cent BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1 * CENT, CENT)); add_coin(available_coins, *wallet, 1*CENT, CFeeRate(0), 4); // add a new 1 cent coin // with a new 1 cent coin, we still can't find a mature 1 cent BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1 * CENT, CENT)); // but we can find a new 1 cent const auto result1 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT); BOOST_CHECK(result1); BOOST_CHECK_EQUAL(result1->GetSelectedValue(), 1 * CENT); add_coin(available_coins, *wallet, 2*CENT); // add a mature 2 cent coin // we can't make 3 cents of mature coins BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 3 * CENT, CENT)); // we can make 3 cents of new coins const auto result2 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 3 * CENT, CENT); BOOST_CHECK(result2); BOOST_CHECK_EQUAL(result2->GetSelectedValue(), 3 * CENT); add_coin(available_coins, *wallet, 5*CENT); // add a mature 5 cent coin, add_coin(available_coins, *wallet, 10*CENT, CFeeRate(0), 3, true); // a new 10 cent coin sent from one of our own addresses add_coin(available_coins, *wallet, 20*CENT); // and a mature 20 cent coin // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38 // we can't make 38 cents only if we disallow new coins: BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 38 * CENT, CENT)); // we can't even make 37 cents if we don't allow new coins even if they're from us BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard_extra), 38 * CENT, CENT)); // but we can make 37 cents if we accept new coins from ourself const auto result3 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 37 * CENT, CENT); BOOST_CHECK(result3); BOOST_CHECK_EQUAL(result3->GetSelectedValue(), 37 * CENT); // and we can make 38 cents if we accept all new coins const auto result4 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 38 * CENT, CENT); BOOST_CHECK(result4); BOOST_CHECK_EQUAL(result4->GetSelectedValue(), 38 * CENT); // try making 34 cents from 1,2,5,10,20 - we can't do it exactly const auto result5 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 34 * CENT, CENT); BOOST_CHECK(result5); BOOST_CHECK_EQUAL(result5->GetSelectedValue(), 35 * CENT); // but 35 cents is closest BOOST_CHECK_EQUAL(result5->GetInputSet().size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible) // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5 const auto result6 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 7 * CENT, CENT); BOOST_CHECK(result6); BOOST_CHECK_EQUAL(result6->GetSelectedValue(), 7 * CENT); BOOST_CHECK_EQUAL(result6->GetInputSet().size(), 2U); // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough. const auto result7 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 8 * CENT, CENT); BOOST_CHECK(result7); BOOST_CHECK(result7->GetSelectedValue() == 8 * CENT); BOOST_CHECK_EQUAL(result7->GetInputSet().size(), 3U); // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10) const auto result8 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 9 * CENT, CENT); BOOST_CHECK(result8); BOOST_CHECK_EQUAL(result8->GetSelectedValue(), 10 * CENT); BOOST_CHECK_EQUAL(result8->GetInputSet().size(), 1U); // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin available_coins.Clear(); add_coin(available_coins, *wallet, 6*CENT); add_coin(available_coins, *wallet, 7*CENT); add_coin(available_coins, *wallet, 8*CENT); add_coin(available_coins, *wallet, 20*CENT); add_coin(available_coins, *wallet, 30*CENT); // now we have 6+7+8+20+30 = 71 cents total // check that we have 71 and not 72 const auto result9 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 71 * CENT, CENT); BOOST_CHECK(result9); BOOST_CHECK(!KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 72 * CENT, CENT)); // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20 const auto result10 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT); BOOST_CHECK(result10); BOOST_CHECK_EQUAL(result10->GetSelectedValue(), 20 * CENT); // we should get 20 in one coin BOOST_CHECK_EQUAL(result10->GetInputSet().size(), 1U); add_coin(available_coins, *wallet, 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20 const auto result11 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT); BOOST_CHECK(result11); BOOST_CHECK_EQUAL(result11->GetSelectedValue(), 18 * CENT); // we should get 18 in 3 coins BOOST_CHECK_EQUAL(result11->GetInputSet().size(), 3U); add_coin(available_coins, *wallet, 18*CENT); // now we have 5+6+7+8+18+20+30 // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18 const auto result12 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 16 * CENT, CENT); BOOST_CHECK(result12); BOOST_CHECK_EQUAL(result12->GetSelectedValue(), 18 * CENT); // we should get 18 in 1 coin BOOST_CHECK_EQUAL(result12->GetInputSet().size(), 1U); // because in the event of a tie, the biggest coin wins // now try making 11 cents. we should get 5+6 const auto result13 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 11 * CENT, CENT); BOOST_CHECK(result13); BOOST_CHECK_EQUAL(result13->GetSelectedValue(), 11 * CENT); BOOST_CHECK_EQUAL(result13->GetInputSet().size(), 2U); // check that the smallest bigger coin is used add_coin(available_coins, *wallet, 1*COIN); add_coin(available_coins, *wallet, 2*COIN); add_coin(available_coins, *wallet, 3*COIN); add_coin(available_coins, *wallet, 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents const auto result14 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 95 * CENT, CENT); BOOST_CHECK(result14); BOOST_CHECK_EQUAL(result14->GetSelectedValue(), 1 * COIN); // we should get 1 BTC in 1 coin BOOST_CHECK_EQUAL(result14->GetInputSet().size(), 1U); const auto result15 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 195 * CENT, CENT); BOOST_CHECK(result15); BOOST_CHECK_EQUAL(result15->GetSelectedValue(), 2 * COIN); // we should get 2 BTC in 1 coin BOOST_CHECK_EQUAL(result15->GetInputSet().size(), 1U); // empty the wallet and start again, now with fractions of a cent, to test small change avoidance available_coins.Clear(); add_coin(available_coins, *wallet, CENT * 1 / 10); add_coin(available_coins, *wallet, CENT * 2 / 10); add_coin(available_coins, *wallet, CENT * 3 / 10); add_coin(available_coins, *wallet, CENT * 4 / 10); add_coin(available_coins, *wallet, CENT * 5 / 10); // try making 1 * CENT from the 1.5 * CENT // we'll get change smaller than CENT whatever happens, so can expect CENT exactly const auto result16 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT); BOOST_CHECK(result16); BOOST_CHECK_EQUAL(result16->GetSelectedValue(), CENT); // but if we add a bigger coin, small change is avoided add_coin(available_coins, *wallet, 1111*CENT); // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5 const auto result17 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT); BOOST_CHECK(result17); BOOST_CHECK_EQUAL(result17->GetSelectedValue(), 1 * CENT); // we should get the exact amount // if we add more small coins: add_coin(available_coins, *wallet, CENT * 6 / 10); add_coin(available_coins, *wallet, CENT * 7 / 10); // and try again to make 1.0 * CENT const auto result18 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT); BOOST_CHECK(result18); BOOST_CHECK_EQUAL(result18->GetSelectedValue(), 1 * CENT); // we should get the exact amount // run the 'mtgox' test (see https://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf) // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change available_coins.Clear(); for (int j = 0; j < 20; j++) add_coin(available_coins, *wallet, 50000 * COIN); const auto result19 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 500000 * COIN, CENT); BOOST_CHECK(result19); BOOST_CHECK_EQUAL(result19->GetSelectedValue(), 500000 * COIN); // we should get the exact amount BOOST_CHECK_EQUAL(result19->GetInputSet().size(), 10U); // in ten coins // if there's not enough in the smaller coins to make at least 1 * CENT change (0.5+0.6+0.7 < 1.0+1.0), // we need to try finding an exact subset anyway // sometimes it will fail, and so we use the next biggest coin: available_coins.Clear(); add_coin(available_coins, *wallet, CENT * 5 / 10); add_coin(available_coins, *wallet, CENT * 6 / 10); add_coin(available_coins, *wallet, CENT * 7 / 10); add_coin(available_coins, *wallet, 1111 * CENT); const auto result20 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 1 * CENT, CENT); BOOST_CHECK(result20); BOOST_CHECK_EQUAL(result20->GetSelectedValue(), 1111 * CENT); // we get the bigger coin BOOST_CHECK_EQUAL(result20->GetInputSet().size(), 1U); // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0) available_coins.Clear(); add_coin(available_coins, *wallet, CENT * 4 / 10); add_coin(available_coins, *wallet, CENT * 6 / 10); add_coin(available_coins, *wallet, CENT * 8 / 10); add_coin(available_coins, *wallet, 1111 * CENT); const auto result21 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT, CENT); BOOST_CHECK(result21); BOOST_CHECK_EQUAL(result21->GetSelectedValue(), CENT); // we should get the exact amount BOOST_CHECK_EQUAL(result21->GetInputSet().size(), 2U); // in two coins 0.4+0.6 // test avoiding small change available_coins.Clear(); add_coin(available_coins, *wallet, CENT * 5 / 100); add_coin(available_coins, *wallet, CENT * 1); add_coin(available_coins, *wallet, CENT * 100); // trying to make 100.01 from these three coins const auto result22 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 10001 / 100, CENT); BOOST_CHECK(result22); BOOST_CHECK_EQUAL(result22->GetSelectedValue(), CENT * 10105 / 100); // we should get all coins BOOST_CHECK_EQUAL(result22->GetInputSet().size(), 3U); // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change const auto result23 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), CENT * 9990 / 100, CENT); BOOST_CHECK(result23); BOOST_CHECK_EQUAL(result23->GetSelectedValue(), 101 * CENT); BOOST_CHECK_EQUAL(result23->GetInputSet().size(), 2U); } // test with many inputs for (CAmount amt=1500; amt < COIN; amt*=10) { available_coins.Clear(); // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input) for (uint16_t j = 0; j < 676; j++) add_coin(available_coins, *wallet, amt); // We only create the wallet once to save time, but we still run the coin selection RUN_TESTS times. for (int i = 0; i < RUN_TESTS; i++) { const auto result24 = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_confirmed), 2000, CENT); BOOST_CHECK(result24); if (amt - 2000 < CENT) { // needs more than one input: uint16_t returnSize = std::ceil((2000.0 + CENT)/amt); CAmount returnValue = amt * returnSize; BOOST_CHECK_EQUAL(result24->GetSelectedValue(), returnValue); BOOST_CHECK_EQUAL(result24->GetInputSet().size(), returnSize); } else { // one input is sufficient: BOOST_CHECK_EQUAL(result24->GetSelectedValue(), amt); BOOST_CHECK_EQUAL(result24->GetInputSet().size(), 1U); } } } // test randomness { available_coins.Clear(); for (int i2 = 0; i2 < 100; i2++) add_coin(available_coins, *wallet, COIN); // Again, we only create the wallet once to save time, but we still run the coin selection RUN_TESTS times. for (int i = 0; i < RUN_TESTS; i++) { // picking 50 from 100 coins doesn't depend on the shuffle, // but does depend on randomness in the stochastic approximation code const auto result25 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT); BOOST_CHECK(result25); const auto result26 = KnapsackSolver(GroupCoins(available_coins.All()), 50 * COIN, CENT); BOOST_CHECK(result26); BOOST_CHECK(!EqualResult(*result25, *result26)); int fails = 0; for (int j = 0; j < RANDOM_REPEATS; j++) { // Test that the KnapsackSolver selects randomly from equivalent coins (same value and same input size). // When choosing 1 from 100 identical coins, 1% of the time, this test will choose the same coin twice // which will cause it to fail. // To avoid that issue, run the test RANDOM_REPEATS times and only complain if all of them fail const auto result27 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT); BOOST_CHECK(result27); const auto result28 = KnapsackSolver(GroupCoins(available_coins.All()), COIN, CENT); BOOST_CHECK(result28); if (EqualResult(*result27, *result28)) fails++; } BOOST_CHECK_NE(fails, RANDOM_REPEATS); } // add 75 cents in small change. not enough to make 90 cents, // then try making 90 cents. there are multiple competing "smallest bigger" coins, // one of which should be picked at random add_coin(available_coins, *wallet, 5 * CENT); add_coin(available_coins, *wallet, 10 * CENT); add_coin(available_coins, *wallet, 15 * CENT); add_coin(available_coins, *wallet, 20 * CENT); add_coin(available_coins, *wallet, 25 * CENT); for (int i = 0; i < RUN_TESTS; i++) { int fails = 0; for (int j = 0; j < RANDOM_REPEATS; j++) { const auto result29 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT); BOOST_CHECK(result29); const auto result30 = KnapsackSolver(GroupCoins(available_coins.All()), 90 * CENT, CENT); BOOST_CHECK(result30); if (EqualResult(*result29, *result30)) fails++; } BOOST_CHECK_NE(fails, RANDOM_REPEATS); } } } BOOST_AUTO_TEST_CASE(ApproximateBestSubset) { FastRandomContext rand{}; std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinsResult available_coins; // Test vValue sort order for (int i = 0; i < 1000; i++) add_coin(available_coins, *wallet, 1000 * COIN); add_coin(available_coins, *wallet, 3 * COIN); const auto result = KnapsackSolver(KnapsackGroupOutputs(available_coins, *wallet, filter_standard), 1003 * COIN, CENT, rand); BOOST_CHECK(result); BOOST_CHECK_EQUAL(result->GetSelectedValue(), 1003 * COIN); BOOST_CHECK_EQUAL(result->GetInputSet().size(), 2U); } // Tests that with the ideal conditions, the coin selector will always be able to find a solution that can pay the target value BOOST_AUTO_TEST_CASE(SelectCoins_test) { std::unique_ptr<CWallet> wallet = NewWallet(m_node); LOCK(wallet->cs_wallet); // Every 'SelectCoins' call requires it // Random generator stuff std::default_random_engine generator; std::exponential_distribution<double> distribution (100); FastRandomContext rand; // Run this test 100 times for (int i = 0; i < 100; ++i) { CoinsResult available_coins; CAmount balance{0}; // Make a wallet with 1000 exponentially distributed random inputs for (int j = 0; j < 1000; ++j) { CAmount val = distribution(generator)*10000000; add_coin(available_coins, *wallet, val); balance += val; } // Generate a random fee rate in the range of 100 - 400 CFeeRate rate(rand.randrange(300) + 100); // Generate a random target value between 1000 and wallet balance CAmount target = rand.randrange(balance - 1000) + 1000; // Perform selection CoinSelectionParams cs_params{ rand, /*change_output_size=*/ 34, /*change_spend_size=*/ 148, /*min_change_target=*/ CENT, /*effective_feerate=*/ CFeeRate(0), /*long_term_feerate=*/ CFeeRate(0), /*discard_feerate=*/ CFeeRate(0), /*tx_noinputs_size=*/ 0, /*avoid_partial=*/ false, }; cs_params.m_cost_of_change = 1; cs_params.min_viable_change = 1; CCoinControl cc; const auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/{}, target, cc, cs_params); BOOST_CHECK(result); BOOST_CHECK_GE(result->GetSelectedValue(), target); } } BOOST_AUTO_TEST_CASE(waste_test) { const CAmount fee{100}; const CAmount change_cost{125}; const CAmount fee_diff{40}; const CAmount in_amt{3 * COIN}; const CAmount target{2 * COIN}; const CAmount excess{in_amt - fee * 2 - target}; // The following tests that the waste is calculated correctly in various scenarios. // ComputeAndSetWaste will first determine the size of the change output. We don't really // care about the change and just want to use the variant that always includes the change_cost, // so min_viable_change and change_fee are set to 0 to ensure that. { // Waste with change is the change cost and difference between fee and long term fee SelectionResult selection1{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection1, fee, fee - fee_diff); add_coin(2 * COIN, 2, selection1, fee, fee - fee_diff); selection1.ComputeAndSetWaste(/*min_viable_change=*/0, change_cost, /*change_fee=*/0); BOOST_CHECK_EQUAL(fee_diff * 2 + change_cost, selection1.GetWaste()); // Waste will be greater when fee is greater, but long term fee is the same SelectionResult selection2{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection2, fee * 2, fee - fee_diff); add_coin(2 * COIN, 2, selection2, fee * 2, fee - fee_diff); selection2.ComputeAndSetWaste(/*min_viable_change=*/0, change_cost, /*change_fee=*/0); BOOST_CHECK_GT(selection2.GetWaste(), selection1.GetWaste()); // Waste with change is the change cost and difference between fee and long term fee // With long term fee greater than fee, waste should be less than when long term fee is less than fee SelectionResult selection3{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection3, fee, fee + fee_diff); add_coin(2 * COIN, 2, selection3, fee, fee + fee_diff); selection3.ComputeAndSetWaste(/*min_viable_change=*/0, change_cost, /*change_fee=*/0); BOOST_CHECK_EQUAL(fee_diff * -2 + change_cost, selection3.GetWaste()); BOOST_CHECK_LT(selection3.GetWaste(), selection1.GetWaste()); } { // Waste without change is the excess and difference between fee and long term fee SelectionResult selection_nochange1{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection_nochange1, fee, fee - fee_diff); add_coin(2 * COIN, 2, selection_nochange1, fee, fee - fee_diff); selection_nochange1.ComputeAndSetWaste(/*min_viable_change=*/0, /*change_cost=*/0, /*change_fee=*/0); BOOST_CHECK_EQUAL(fee_diff * 2 + excess, selection_nochange1.GetWaste()); // Waste without change is the excess and difference between fee and long term fee // With long term fee greater than fee, waste should be less than when long term fee is less than fee SelectionResult selection_nochange2{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection_nochange2, fee, fee + fee_diff); add_coin(2 * COIN, 2, selection_nochange2, fee, fee + fee_diff); selection_nochange2.ComputeAndSetWaste(/*min_viable_change=*/0, /*change_cost=*/0, /*change_fee=*/0); BOOST_CHECK_EQUAL(fee_diff * -2 + excess, selection_nochange2.GetWaste()); BOOST_CHECK_LT(selection_nochange2.GetWaste(), selection_nochange1.GetWaste()); } { // Waste with change and fee == long term fee is just cost of change SelectionResult selection{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection, fee, fee); add_coin(2 * COIN, 2, selection, fee, fee); selection.ComputeAndSetWaste(/*min_viable_change=*/0, change_cost, /*change_fee=*/0); BOOST_CHECK_EQUAL(change_cost, selection.GetWaste()); } { // Waste without change and fee == long term fee is just the excess SelectionResult selection{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection, fee, fee); add_coin(2 * COIN, 2, selection, fee, fee); selection.ComputeAndSetWaste(/*min_viable_change=*/0, /*change_cost=*/0, /*change_fee=*/0); BOOST_CHECK_EQUAL(excess, selection.GetWaste()); } { // No Waste when fee == long_term_fee, no change, and no excess const CAmount exact_target{in_amt - fee * 2}; SelectionResult selection{exact_target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection, fee, fee); add_coin(2 * COIN, 2, selection, fee, fee); selection.ComputeAndSetWaste(/*min_viable_change=*/0, /*change_cost=*/0, /*change_fee=*/0); BOOST_CHECK_EQUAL(0, selection.GetWaste()); } { // No Waste when (fee - long_term_fee) == (-cost_of_change), and no excess SelectionResult selection{target, SelectionAlgorithm::MANUAL}; const CAmount new_change_cost{fee_diff * 2}; add_coin(1 * COIN, 1, selection, fee, fee + fee_diff); add_coin(2 * COIN, 2, selection, fee, fee + fee_diff); selection.ComputeAndSetWaste(/*min_viable_change=*/0, new_change_cost, /*change_fee=*/0); BOOST_CHECK_EQUAL(0, selection.GetWaste()); } { // No Waste when (fee - long_term_fee) == (-excess), no change cost const CAmount new_target{in_amt - fee * 2 - fee_diff * 2}; SelectionResult selection{new_target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection, fee, fee + fee_diff); add_coin(2 * COIN, 2, selection, fee, fee + fee_diff); selection.ComputeAndSetWaste(/*min_viable_change=*/0, /*change_cost=*/0, /*change_fee=*/0); BOOST_CHECK_EQUAL(0, selection.GetWaste()); } { // Negative waste when the long term fee is greater than the current fee and the selected value == target const CAmount exact_target{3 * COIN - 2 * fee}; SelectionResult selection{exact_target, SelectionAlgorithm::MANUAL}; const CAmount target_waste1{-2 * fee_diff}; // = (2 * fee) - (2 * (fee + fee_diff)) add_coin(1 * COIN, 1, selection, fee, fee + fee_diff); add_coin(2 * COIN, 2, selection, fee, fee + fee_diff); selection.ComputeAndSetWaste(/*min_viable_change=*/0, /*change_cost=*/0, /*change_fee=*/0); BOOST_CHECK_EQUAL(target_waste1, selection.GetWaste()); } { // Negative waste when the long term fee is greater than the current fee and change_cost < - (inputs * (fee - long_term_fee)) SelectionResult selection{target, SelectionAlgorithm::MANUAL}; const CAmount large_fee_diff{90}; const CAmount target_waste2{-2 * large_fee_diff + change_cost}; // = (2 * fee) - (2 * (fee + large_fee_diff)) + change_cost add_coin(1 * COIN, 1, selection, fee, fee + large_fee_diff); add_coin(2 * COIN, 2, selection, fee, fee + large_fee_diff); selection.ComputeAndSetWaste(/*min_viable_change=*/0, change_cost, /*change_fee=*/0); BOOST_CHECK_EQUAL(target_waste2, selection.GetWaste()); } } BOOST_AUTO_TEST_CASE(bump_fee_test) { const CAmount fee{100}; const CAmount min_viable_change{200}; const CAmount change_cost{125}; const CAmount change_fee{35}; const CAmount fee_diff{40}; const CAmount target{2 * COIN}; { SelectionResult selection{target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection, /*fee=*/fee, /*long_term_fee=*/fee + fee_diff); add_coin(2 * COIN, 2, selection, fee, fee + fee_diff); const std::vector<std::shared_ptr<COutput>> inputs = selection.GetShuffledInputVector(); for (size_t i = 0; i < inputs.size(); ++i) { inputs[i]->ApplyBumpFee(20*(i+1)); } selection.ComputeAndSetWaste(min_viable_change, change_cost, change_fee); CAmount expected_waste = fee_diff * -2 + change_cost + /*bump_fees=*/60; BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste()); selection.SetBumpFeeDiscount(30); selection.ComputeAndSetWaste(min_viable_change, change_cost, change_fee); expected_waste = fee_diff * -2 + change_cost + /*bump_fees=*/60 - /*group_discount=*/30; BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste()); } { // Test with changeless transaction // // Bump fees and excess both contribute fully to the waste score, // therefore, a bump fee group discount will not change the waste // score as long as we do not create change in both instances. CAmount changeless_target = 3 * COIN - 2 * fee - 100; SelectionResult selection{changeless_target, SelectionAlgorithm::MANUAL}; add_coin(1 * COIN, 1, selection, /*fee=*/fee, /*long_term_fee=*/fee + fee_diff); add_coin(2 * COIN, 2, selection, fee, fee + fee_diff); const std::vector<std::shared_ptr<COutput>> inputs = selection.GetShuffledInputVector(); for (size_t i = 0; i < inputs.size(); ++i) { inputs[i]->ApplyBumpFee(20*(i+1)); } selection.ComputeAndSetWaste(min_viable_change, change_cost, change_fee); CAmount expected_waste = fee_diff * -2 + /*bump_fees=*/60 + /*excess = 100 - bump_fees*/40; BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste()); selection.SetBumpFeeDiscount(30); selection.ComputeAndSetWaste(min_viable_change, change_cost, change_fee); expected_waste = fee_diff * -2 + /*bump_fees=*/60 - /*group_discount=*/30 + /*excess = 100 - bump_fees + group_discount*/70; BOOST_CHECK_EQUAL(expected_waste, selection.GetWaste()); } } BOOST_AUTO_TEST_CASE(effective_value_test) { const int input_bytes = 148; const CFeeRate feerate(1000); const CAmount nValue = 10000; const int nInput = 0; CMutableTransaction tx; tx.vout.resize(1); tx.vout[nInput].nValue = nValue; // standard case, pass feerate in constructor COutput output1(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, feerate); const CAmount expected_ev1 = 9852; // 10000 - 148 BOOST_CHECK_EQUAL(output1.GetEffectiveValue(), expected_ev1); // input bytes unknown (input_bytes = -1), pass feerate in constructor COutput output2(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, feerate); BOOST_CHECK_EQUAL(output2.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1 // negative effective value, pass feerate in constructor COutput output3(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, CFeeRate(100000)); const CAmount expected_ev3 = -4800; // 10000 - 14800 BOOST_CHECK_EQUAL(output3.GetEffectiveValue(), expected_ev3); // standard case, pass fees in constructor const CAmount fees = 148; COutput output4(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, input_bytes, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, fees); BOOST_CHECK_EQUAL(output4.GetEffectiveValue(), expected_ev1); // input bytes unknown (input_bytes = -1), pass fees in constructor COutput output5(COutPoint(tx.GetHash(), nInput), tx.vout.at(nInput), /*depth=*/ 1, /*input_bytes=*/ -1, /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, /*time=*/ 0, /*from_me=*/ false, /*fees=*/ 0); BOOST_CHECK_EQUAL(output5.GetEffectiveValue(), nValue); // The effective value should be equal to the absolute value if input_bytes is -1 } static util::Result<SelectionResult> SelectCoinsSRD(const CAmount& target, const CoinSelectionParams& cs_params, const node::NodeContext& m_node, int max_weight, std::function<CoinsResult(CWallet&)> coin_setup) { std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinEligibilityFilter filter(0, 0, 0); // accept all coins without ancestors Groups group = GroupOutputs(*wallet, coin_setup(*wallet), cs_params, {{filter}})[filter].all_groups; return SelectCoinsSRD(group.positive_group, target, cs_params.m_change_fee, cs_params.rng_fast, max_weight); } BOOST_AUTO_TEST_CASE(srd_tests) { // Test SRD: // 1) Insufficient funds, select all provided coins and fail. // 2) Exceeded max weight, coin selection always surpasses the max allowed weight. // 3) Select coins without surpassing the max weight (some coins surpasses the max allowed weight, some others not) FastRandomContext rand; CoinSelectionParams dummy_params{ // Only used to provide the 'avoid_partial' flag. rand, /*change_output_size=*/34, /*change_spend_size=*/68, /*min_change_target=*/CENT, /*effective_feerate=*/CFeeRate(0), /*long_term_feerate=*/CFeeRate(0), /*discard_feerate=*/CFeeRate(0), /*tx_noinputs_size=*/10 + 34, // static header size + output size /*avoid_partial=*/false, }; { // ######################################################### // 1) Insufficient funds, select all provided coins and fail // ######################################################### CAmount target = 49.5L * COIN; int max_weight = 10000; // high enough to not fail for this reason. const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_weight, [&](CWallet& wallet) { CoinsResult available_coins; for (int j = 0; j < 10; ++j) { add_coin(available_coins, wallet, CAmount(1 * COIN)); add_coin(available_coins, wallet, CAmount(2 * COIN)); } return available_coins; }); BOOST_CHECK(!res); BOOST_CHECK(util::ErrorString(res).empty()); // empty means "insufficient funds" } { // ########################### // 2) Test max weight exceeded // ########################### CAmount target = 49.5L * COIN; int max_weight = 3000; const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_weight, [&](CWallet& wallet) { CoinsResult available_coins; for (int j = 0; j < 10; ++j) { add_coin(available_coins, wallet, CAmount(1 * COIN), CFeeRate(0), 144, false, 0, true); add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(0), 144, false, 0, true); } return available_coins; }); BOOST_CHECK(!res); BOOST_CHECK(util::ErrorString(res).original.find("The inputs size exceeds the maximum weight") != std::string::npos); } { // ################################################################################################################ // 3) Test selection when some coins surpass the max allowed weight while others not. --> must find a good solution // ################################################################################################################ CAmount target = 25.33L * COIN; int max_weight = 10000; // WU const auto& res = SelectCoinsSRD(target, dummy_params, m_node, max_weight, [&](CWallet& wallet) { CoinsResult available_coins; for (int j = 0; j < 60; ++j) { // 60 UTXO --> 19,8 BTC total --> 60 × 272 WU = 16320 WU add_coin(available_coins, wallet, CAmount(0.33 * COIN), CFeeRate(0), 144, false, 0, true); } for (int i = 0; i < 10; i++) { // 10 UTXO --> 20 BTC total --> 10 × 272 WU = 2720 WU add_coin(available_coins, wallet, CAmount(2 * COIN), CFeeRate(0), 144, false, 0, true); } return available_coins; }); BOOST_CHECK(res); } } static util::Result<SelectionResult> select_coins(const CAmount& target, const CoinSelectionParams& cs_params, const CCoinControl& cc, std::function<CoinsResult(CWallet&)> coin_setup, const node::NodeContext& m_node) { std::unique_ptr<CWallet> wallet = NewWallet(m_node); auto available_coins = coin_setup(*wallet); LOCK(wallet->cs_wallet); auto result = SelectCoins(*wallet, available_coins, /*pre_set_inputs=*/ {}, target, cc, cs_params); if (result) { const auto signedTxSize = 10 + 34 + 68 * result->GetInputSet().size(); // static header size + output size + inputs size (P2WPKH) BOOST_CHECK_LE(signedTxSize * WITNESS_SCALE_FACTOR, MAX_STANDARD_TX_WEIGHT); BOOST_CHECK_GE(result->GetSelectedValue(), target); } return result; } static bool has_coin(const CoinSet& set, CAmount amount) { return std::any_of(set.begin(), set.end(), [&](const auto& coin) { return coin->GetEffectiveValue() == amount; }); } BOOST_AUTO_TEST_CASE(check_max_weight) { const CAmount target = 49.5L * COIN; CCoinControl cc; FastRandomContext rand; CoinSelectionParams cs_params{ rand, /*change_output_size=*/34, /*change_spend_size=*/68, /*min_change_target=*/CENT, /*effective_feerate=*/CFeeRate(0), /*long_term_feerate=*/CFeeRate(0), /*discard_feerate=*/CFeeRate(0), /*tx_noinputs_size=*/10 + 34, // static header size + output size /*avoid_partial=*/false, }; { // Scenario 1: // The actor starts with 1x 50.0 BTC and 1515x 0.033 BTC (~100.0 BTC total) unspent outputs // Then tries to spend 49.5 BTC // The 50.0 BTC output should be selected, because the transaction would otherwise be too large // Perform selection const auto result = select_coins( target, cs_params, cc, [&](CWallet& wallet) { CoinsResult available_coins; for (int j = 0; j < 1515; ++j) { add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true); } add_coin(available_coins, wallet, CAmount(50 * COIN), CFeeRate(0), 144, false, 0, true); return available_coins; }, m_node); BOOST_CHECK(result); // Verify that only the 50 BTC UTXO was selected const auto& selection_res = result->GetInputSet(); BOOST_CHECK(selection_res.size() == 1); BOOST_CHECK((*selection_res.begin())->GetEffectiveValue() == 50 * COIN); } { // Scenario 2: // The actor starts with 400x 0.0625 BTC and 2000x 0.025 BTC (75.0 BTC total) unspent outputs // Then tries to spend 49.5 BTC // A combination of coins should be selected, such that the created transaction is not too large // Perform selection const auto result = select_coins( target, cs_params, cc, [&](CWallet& wallet) { CoinsResult available_coins; for (int j = 0; j < 400; ++j) { add_coin(available_coins, wallet, CAmount(0.0625 * COIN), CFeeRate(0), 144, false, 0, true); } for (int j = 0; j < 2000; ++j) { add_coin(available_coins, wallet, CAmount(0.025 * COIN), CFeeRate(0), 144, false, 0, true); } return available_coins; }, m_node); BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.0625 * COIN))); BOOST_CHECK(has_coin(result->GetInputSet(), CAmount(0.025 * COIN))); } { // Scenario 3: // The actor starts with 1515x 0.033 BTC (49.995 BTC total) unspent outputs // No results should be returned, because the transaction would be too large // Perform selection const auto result = select_coins( target, cs_params, cc, [&](CWallet& wallet) { CoinsResult available_coins; for (int j = 0; j < 1515; ++j) { add_coin(available_coins, wallet, CAmount(0.033 * COIN), CFeeRate(0), 144, false, 0, true); } return available_coins; }, m_node); // No results // 1515 inputs * 68 bytes = 103,020 bytes // 103,020 bytes * 4 = 412,080 weight, which is above the MAX_STANDARD_TX_WEIGHT of 400,000 BOOST_CHECK(!result); } } BOOST_AUTO_TEST_CASE(SelectCoins_effective_value_test) { // Test that the effective value is used to check whether preset inputs provide sufficient funds when subtract_fee_outputs is not used. // This test creates a coin whose value is higher than the target but whose effective value is lower than the target. // The coin is selected using coin control, with m_allow_other_inputs = false. SelectCoins should fail due to insufficient funds. std::unique_ptr<CWallet> wallet = NewWallet(m_node); CoinsResult available_coins; { std::unique_ptr<CWallet> dummyWallet = NewWallet(m_node, /*wallet_name=*/"dummy"); add_coin(available_coins, *dummyWallet, 100000); // 0.001 BTC } CAmount target{99900}; // 0.000999 BTC FastRandomContext rand; CoinSelectionParams cs_params{ rand, /*change_output_size=*/34, /*change_spend_size=*/148, /*min_change_target=*/1000, /*effective_feerate=*/CFeeRate(3000), /*long_term_feerate=*/CFeeRate(1000), /*discard_feerate=*/CFeeRate(1000), /*tx_noinputs_size=*/0, /*avoid_partial=*/false, }; CCoinControl cc; cc.m_allow_other_inputs = false; COutput output = available_coins.All().at(0); cc.SetInputWeight(output.outpoint, 148); cc.Select(output.outpoint).SetTxOut(output.txout); LOCK(wallet->cs_wallet); const auto preset_inputs = *Assert(FetchSelectedInputs(*wallet, cc, cs_params)); available_coins.Erase({available_coins.coins[OutputType::BECH32].begin()->outpoint}); const auto result = SelectCoins(*wallet, available_coins, preset_inputs, target, cc, cs_params); BOOST_CHECK(!result); } BOOST_FIXTURE_TEST_CASE(wallet_coinsresult_test, BasicTestingSetup) { // Test case to verify CoinsResult object sanity. CoinsResult available_coins; { std::unique_ptr<CWallet> dummyWallet = NewWallet(m_node, /*wallet_name=*/"dummy"); // Add some coins to 'available_coins' for (int i=0; i<10; i++) { add_coin(available_coins, *dummyWallet, 1 * COIN); } } { // First test case, check that 'CoinsResult::Erase' function works as expected. // By trying to erase two elements from the 'available_coins' object. std::unordered_set<COutPoint, SaltedOutpointHasher> outs_to_remove; const auto& coins = available_coins.All(); for (int i = 0; i < 2; i++) { outs_to_remove.emplace(coins[i].outpoint); } available_coins.Erase(outs_to_remove); // Check that the elements were actually removed. const auto& updated_coins = available_coins.All(); for (const auto& out: outs_to_remove) { auto it = std::find_if(updated_coins.begin(), updated_coins.end(), [&out](const COutput &coin) { return coin.outpoint == out; }); BOOST_CHECK(it == updated_coins.end()); } // And verify that no extra element were removed BOOST_CHECK_EQUAL(available_coins.Size(), 8); } } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/init_tests.cpp
// Copyright (c) 2018-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include <common/args.h> #include <noui.h> #include <test/util/logging.h> #include <test/util/setup_common.h> #include <wallet/test/init_test_fixture.h> namespace wallet { BOOST_FIXTURE_TEST_SUITE(init_tests, InitWalletDirTestingSetup) BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_default) { SetWalletDir(m_walletdir_path_cases["default"]); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == true); fs::path walletdir = m_args.GetPathArg("-walletdir"); fs::path expected_path = fs::canonical(m_walletdir_path_cases["default"]); BOOST_CHECK_EQUAL(walletdir, expected_path); } BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_custom) { SetWalletDir(m_walletdir_path_cases["custom"]); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == true); fs::path walletdir = m_args.GetPathArg("-walletdir"); fs::path expected_path = fs::canonical(m_walletdir_path_cases["custom"]); BOOST_CHECK_EQUAL(walletdir, expected_path); } BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_does_not_exist) { SetWalletDir(m_walletdir_path_cases["nonexistent"]); { ASSERT_DEBUG_LOG("does not exist"); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == false); } } BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_is_not_directory) { SetWalletDir(m_walletdir_path_cases["file"]); { ASSERT_DEBUG_LOG("is not a directory"); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == false); } } BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_is_not_relative) { SetWalletDir(m_walletdir_path_cases["relative"]); { ASSERT_DEBUG_LOG("is a relative path"); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == false); } } BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_no_trailing) { SetWalletDir(m_walletdir_path_cases["trailing"]); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == true); fs::path walletdir = m_args.GetPathArg("-walletdir"); fs::path expected_path = fs::canonical(m_walletdir_path_cases["default"]); BOOST_CHECK_EQUAL(walletdir, expected_path); } BOOST_AUTO_TEST_CASE(walletinit_verify_walletdir_no_trailing2) { SetWalletDir(m_walletdir_path_cases["trailing2"]); bool result = m_wallet_loader->verify(); BOOST_CHECK(result == true); fs::path walletdir = m_args.GetPathArg("-walletdir"); fs::path expected_path = fs::canonical(m_walletdir_path_cases["default"]); BOOST_CHECK_EQUAL(walletdir, expected_path); } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/spend_tests.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/amount.h> #include <policy/fees.h> #include <script/solver.h> #include <validation.h> #include <wallet/coincontrol.h> #include <wallet/spend.h> #include <wallet/test/util.h> #include <wallet/test/wallet_test_fixture.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_FIXTURE_TEST_SUITE(spend_tests, WalletTestingSetup) BOOST_FIXTURE_TEST_CASE(SubtractFee, TestChain100Setup) { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); auto wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey); // Check that a subtract-from-recipient transaction slightly less than the // coinbase input amount does not create a change output (because it would // be uneconomical to add and spend the output), and make sure it pays the // leftover input amount which would have been change to the recipient // instead of the miner. auto check_tx = [&wallet](CAmount leftover_input_amount) { CRecipient recipient{PubKeyDestination({}), 50 * COIN - leftover_input_amount, /*subtract_fee=*/true}; CCoinControl coin_control; coin_control.m_feerate.emplace(10000); coin_control.fOverrideFeeRate = true; // We need to use a change type with high cost of change so that the leftover amount will be dropped to fee instead of added as a change output coin_control.m_change_type = OutputType::LEGACY; auto res = CreateTransaction(*wallet, {recipient}, /*change_pos=*/std::nullopt, coin_control); BOOST_CHECK(res); const auto& txr = *res; BOOST_CHECK_EQUAL(txr.tx->vout.size(), 1); BOOST_CHECK_EQUAL(txr.tx->vout[0].nValue, recipient.nAmount + leftover_input_amount - txr.fee); BOOST_CHECK_GT(txr.fee, 0); return txr.fee; }; // Send full input amount to recipient, check that only nonzero fee is // subtracted (to_reduce == fee). const CAmount fee{check_tx(0)}; // Send slightly less than full input amount to recipient, check leftover // input amount is paid to recipient not the miner (to_reduce == fee - 123) BOOST_CHECK_EQUAL(fee, check_tx(123)); // Send full input minus fee amount to recipient, check leftover input // amount is paid to recipient not the miner (to_reduce == 0) BOOST_CHECK_EQUAL(fee, check_tx(fee)); // Send full input minus more than the fee amount to recipient, check // leftover input amount is paid to recipient not the miner (to_reduce == // -123). This overpays the recipient instead of overpaying the miner more // than double the necessary fee. BOOST_CHECK_EQUAL(fee, check_tx(fee + 123)); } BOOST_FIXTURE_TEST_CASE(wallet_duplicated_preset_inputs_test, TestChain100Setup) { // Verify that the wallet's Coin Selection process does not include pre-selected inputs twice in a transaction. // Add 4 spendable UTXO, 50 BTC each, to the wallet (total balance 200 BTC) for (int i = 0; i < 4; i++) CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); auto wallet = CreateSyncedWallet(*m_node.chain, WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain()), coinbaseKey); LOCK(wallet->cs_wallet); auto available_coins = AvailableCoins(*wallet); std::vector<COutput> coins = available_coins.All(); // Preselect the first 3 UTXO (150 BTC total) std::set<COutPoint> preset_inputs = {coins[0].outpoint, coins[1].outpoint, coins[2].outpoint}; // Try to create a tx that spends more than what preset inputs + wallet selected inputs are covering for. // The wallet can cover up to 200 BTC, and the tx target is 299 BTC. std::vector<CRecipient> recipients{{*Assert(wallet->GetNewDestination(OutputType::BECH32, "dummy")), /*nAmount=*/299 * COIN, /*fSubtractFeeFromAmount=*/true}}; CCoinControl coin_control; coin_control.m_allow_other_inputs = true; for (const auto& outpoint : preset_inputs) { coin_control.Select(outpoint); } // Attempt to send 299 BTC from a wallet that only has 200 BTC. The wallet should exclude // the preset inputs from the pool of available coins, realize that there is not enough // money to fund the 299 BTC payment, and fail with "Insufficient funds". // // Even with SFFO, the wallet can only afford to send 200 BTC. // If the wallet does not properly exclude preset inputs from the pool of available coins // prior to coin selection, it may create a transaction that does not fund the full payment // amount or, through SFFO, incorrectly reduce the recipient's amount by the difference // between the original target and the wrongly counted inputs (in this case 99 BTC) // so that the recipient's amount is no longer equal to the user's selected target of 299 BTC. // First case, use 'subtract_fee_from_outputs=true' util::Result<CreatedTransactionResult> res_tx = CreateTransaction(*wallet, recipients, /*change_pos=*/std::nullopt, coin_control); BOOST_CHECK(!res_tx.has_value()); // Second case, don't use 'subtract_fee_from_outputs'. recipients[0].fSubtractFeeFromAmount = false; res_tx = CreateTransaction(*wallet, recipients, /*change_pos=*/std::nullopt, coin_control); BOOST_CHECK(!res_tx.has_value()); } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/group_outputs_tests.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include <test/util/setup_common.h> #include <wallet/coinselection.h> #include <wallet/spend.h> #include <wallet/test/util.h> #include <wallet/wallet.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_FIXTURE_TEST_SUITE(group_outputs_tests, TestingSetup) static int nextLockTime = 0; static std::shared_ptr<CWallet> NewWallet(const node::NodeContext& m_node) { std::unique_ptr<CWallet> wallet = std::make_unique<CWallet>(m_node.chain.get(), "", CreateMockableWalletDatabase()); wallet->LoadWallet(); LOCK(wallet->cs_wallet); wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet->SetupDescriptorScriptPubKeyMans(); return wallet; } static void addCoin(CoinsResult& coins, CWallet& wallet, const CTxDestination& dest, const CAmount& nValue, bool is_from_me, CFeeRate fee_rate = CFeeRate(0), int depth = 6) { CMutableTransaction tx; tx.nLockTime = nextLockTime++; // so all transactions get different hashes tx.vout.resize(1); tx.vout[0].nValue = nValue; tx.vout[0].scriptPubKey = GetScriptForDestination(dest); const auto txid{tx.GetHash().ToUint256()}; LOCK(wallet.cs_wallet); auto ret = wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(txid), std::forward_as_tuple(MakeTransactionRef(std::move(tx)), TxStateInactive{})); assert(ret.second); CWalletTx& wtx = (*ret.first).second; const auto& txout = wtx.tx->vout.at(0); coins.Add(*Assert(OutputTypeFromDestination(dest)), {COutPoint(wtx.GetHash(), 0), txout, depth, CalculateMaximumSignedInputSize(txout, &wallet, /*coin_control=*/nullptr), /*spendable=*/ true, /*solvable=*/ true, /*safe=*/ true, wtx.GetTxTime(), is_from_me, fee_rate}); } CoinSelectionParams makeSelectionParams(FastRandomContext& rand, bool avoid_partial_spends) { return CoinSelectionParams{ rand, /*change_output_size=*/ 0, /*change_spend_size=*/ 0, /*min_change_target=*/ CENT, /*effective_feerate=*/ CFeeRate(0), /*long_term_feerate=*/ CFeeRate(0), /*discard_feerate=*/ CFeeRate(0), /*tx_noinputs_size=*/ 0, /*avoid_partial=*/ avoid_partial_spends, }; } class GroupVerifier { public: std::shared_ptr<CWallet> wallet{nullptr}; CoinsResult coins_pool; FastRandomContext rand; void GroupVerify(const OutputType type, const CoinEligibilityFilter& filter, bool avoid_partial_spends, bool positive_only, int expected_size) { OutputGroupTypeMap groups = GroupOutputs(*wallet, coins_pool, makeSelectionParams(rand, avoid_partial_spends), {{filter}})[filter]; std::vector<OutputGroup>& groups_out = positive_only ? groups.groups_by_type[type].positive_group : groups.groups_by_type[type].mixed_group; BOOST_CHECK_EQUAL(groups_out.size(), expected_size); } void GroupAndVerify(const OutputType type, const CoinEligibilityFilter& filter, int expected_with_partial_spends_size, int expected_without_partial_spends_size, bool positive_only) { // First avoid partial spends GroupVerify(type, filter, /*avoid_partial_spends=*/false, positive_only, expected_with_partial_spends_size); // Second don't avoid partial spends GroupVerify(type, filter, /*avoid_partial_spends=*/true, positive_only, expected_without_partial_spends_size); } }; BOOST_AUTO_TEST_CASE(outputs_grouping_tests) { const auto& wallet = NewWallet(m_node); GroupVerifier group_verifier; group_verifier.wallet = wallet; const CoinEligibilityFilter& BASIC_FILTER{1, 6, 0}; // ################################################################################# // 10 outputs from different txs going to the same script // 1) if partial spends is enabled --> must not be grouped // 2) if partial spends is not enabled --> must be grouped into a single OutputGroup // ################################################################################# unsigned long GROUP_SIZE = 10; const CTxDestination dest = *Assert(wallet->GetNewDestination(OutputType::BECH32, "")); for (unsigned long i = 0; i < GROUP_SIZE; i++) { addCoin(group_verifier.coins_pool, *wallet, dest, 10 * COIN, /*is_from_me=*/true); } group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ GROUP_SIZE, /*expected_without_partial_spends_size=*/ 1, /*positive_only=*/ true); // #################################################################################### // 3) 10 more UTXO are added with a different script --> must be grouped into a single // group for avoid partial spends and 10 different output groups for partial spends // #################################################################################### const CTxDestination dest2 = *Assert(wallet->GetNewDestination(OutputType::BECH32, "")); for (unsigned long i = 0; i < GROUP_SIZE; i++) { addCoin(group_verifier.coins_pool, *wallet, dest2, 5 * COIN, /*is_from_me=*/true); } group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ GROUP_SIZE * 2, /*expected_without_partial_spends_size=*/ 2, /*positive_only=*/ true); // ################################################################################ // 4) Now add a negative output --> which will be skipped if "positive_only" is set // ################################################################################ const CTxDestination dest3 = *Assert(wallet->GetNewDestination(OutputType::BECH32, "")); addCoin(group_verifier.coins_pool, *wallet, dest3, 1, true, CFeeRate(100)); BOOST_CHECK(group_verifier.coins_pool.coins[OutputType::BECH32].back().GetEffectiveValue() <= 0); // First expect no changes with "positive_only" enabled group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ GROUP_SIZE * 2, /*expected_without_partial_spends_size=*/ 2, /*positive_only=*/ true); // Then expect changes with "positive_only" disabled group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ GROUP_SIZE * 2 + 1, /*expected_without_partial_spends_size=*/ 3, /*positive_only=*/ false); // ############################################################################## // 5) Try to add a non-eligible UTXO (due not fulfilling the min depth target for // "not mine" UTXOs) --> it must not be added to any group // ############################################################################## const CTxDestination dest4 = *Assert(wallet->GetNewDestination(OutputType::BECH32, "")); addCoin(group_verifier.coins_pool, *wallet, dest4, 6 * COIN, /*is_from_me=*/false, CFeeRate(0), /*depth=*/5); // Expect no changes from this round and the previous one (point 4) group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ GROUP_SIZE * 2 + 1, /*expected_without_partial_spends_size=*/ 3, /*positive_only=*/ false); // ############################################################################## // 6) Try to add a non-eligible UTXO (due not fulfilling the min depth target for // "mine" UTXOs) --> it must not be added to any group // ############################################################################## const CTxDestination dest5 = *Assert(wallet->GetNewDestination(OutputType::BECH32, "")); addCoin(group_verifier.coins_pool, *wallet, dest5, 6 * COIN, /*is_from_me=*/true, CFeeRate(0), /*depth=*/0); // Expect no changes from this round and the previous one (point 5) group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ GROUP_SIZE * 2 + 1, /*expected_without_partial_spends_size=*/ 3, /*positive_only=*/ false); // ########################################################################################### // 7) Surpass the OUTPUT_GROUP_MAX_ENTRIES and verify that a second partial group gets created // ########################################################################################### const CTxDestination dest7 = *Assert(wallet->GetNewDestination(OutputType::BECH32, "")); uint16_t NUM_SINGLE_ENTRIES = 101; for (unsigned long i = 0; i < NUM_SINGLE_ENTRIES; i++) { // OUTPUT_GROUP_MAX_ENTRIES{100} addCoin(group_verifier.coins_pool, *wallet, dest7, 9 * COIN, /*is_from_me=*/true); } // Exclude partial groups only adds one more group to the previous test case (point 6) int PREVIOUS_ROUND_COUNT = GROUP_SIZE * 2 + 1; group_verifier.GroupAndVerify(OutputType::BECH32, BASIC_FILTER, /*expected_with_partial_spends_size=*/ PREVIOUS_ROUND_COUNT + NUM_SINGLE_ENTRIES, /*expected_without_partial_spends_size=*/ 4, /*positive_only=*/ false); // Include partial groups should add one more group inside the "avoid partial spends" count const CoinEligibilityFilter& avoid_partial_groups_filter{1, 6, 0, 0, /*include_partial=*/ true}; group_verifier.GroupAndVerify(OutputType::BECH32, avoid_partial_groups_filter, /*expected_with_partial_spends_size=*/ PREVIOUS_ROUND_COUNT + NUM_SINGLE_ENTRIES, /*expected_without_partial_spends_size=*/ 5, /*positive_only=*/ false); } BOOST_AUTO_TEST_SUITE_END() } // end namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/util.h
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_TEST_UTIL_H #define BITCOIN_WALLET_TEST_UTIL_H #include <addresstype.h> #include <wallet/db.h> #include <memory> class ArgsManager; class CChain; class CKey; enum class OutputType; namespace interfaces { class Chain; } // namespace interfaces namespace wallet { class CWallet; class WalletDatabase; struct WalletContext; static const DatabaseFormat DATABASE_FORMATS[] = { #ifdef USE_SQLITE DatabaseFormat::SQLITE, #endif #ifdef USE_BDB DatabaseFormat::BERKELEY, #endif }; const std::string ADDRESS_BCRT1_UNSPENDABLE = "bcrt1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xueyj"; std::unique_ptr<CWallet> CreateSyncedWallet(interfaces::Chain& chain, CChain& cchain, const CKey& key); std::shared_ptr<CWallet> TestLoadWallet(WalletContext& context); std::shared_ptr<CWallet> TestLoadWallet(std::unique_ptr<WalletDatabase> database, WalletContext& context, uint64_t create_flags); void TestUnloadWallet(std::shared_ptr<CWallet>&& wallet); // Creates a copy of the provided database std::unique_ptr<WalletDatabase> DuplicateMockDatabase(WalletDatabase& database); /** Returns a new encoded destination from the wallet (hardcoded to BECH32) */ std::string getnewaddress(CWallet& w); /** Returns a new destination, of an specific type, from the wallet */ CTxDestination getNewDestination(CWallet& w, OutputType output_type); using MockableData = std::map<SerializeData, SerializeData, std::less<>>; class MockableCursor: public DatabaseCursor { public: MockableData::const_iterator m_cursor; MockableData::const_iterator m_cursor_end; bool m_pass; explicit MockableCursor(const MockableData& records, bool pass) : m_cursor(records.begin()), m_cursor_end(records.end()), m_pass(pass) {} MockableCursor(const MockableData& records, bool pass, Span<const std::byte> prefix); ~MockableCursor() {} Status Next(DataStream& key, DataStream& value) override; }; class MockableBatch : public DatabaseBatch { private: MockableData& m_records; bool m_pass; bool ReadKey(DataStream&& key, DataStream& value) override; bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite=true) override; bool EraseKey(DataStream&& key) override; bool HasKey(DataStream&& key) override; bool ErasePrefix(Span<const std::byte> prefix) override; public: explicit MockableBatch(MockableData& records, bool pass) : m_records(records), m_pass(pass) {} ~MockableBatch() {} void Flush() override {} void Close() override {} std::unique_ptr<DatabaseCursor> GetNewCursor() override { return std::make_unique<MockableCursor>(m_records, m_pass); } std::unique_ptr<DatabaseCursor> GetNewPrefixCursor(Span<const std::byte> prefix) override { return std::make_unique<MockableCursor>(m_records, m_pass, prefix); } bool TxnBegin() override { return m_pass; } bool TxnCommit() override { return m_pass; } bool TxnAbort() override { return m_pass; } }; /** A WalletDatabase whose contents and return values can be modified as needed for testing **/ class MockableDatabase : public WalletDatabase { public: MockableData m_records; bool m_pass{true}; MockableDatabase(MockableData records = {}) : WalletDatabase(), m_records(records) {} ~MockableDatabase() {}; void Open() override {} void AddRef() override {} void RemoveRef() override {} bool Rewrite(const char* pszSkip=nullptr) override { return m_pass; } bool Backup(const std::string& strDest) const override { return m_pass; } void Flush() override {} void Close() override {} bool PeriodicFlush() override { return m_pass; } void IncrementUpdateCounter() override {} void ReloadDbEnv() override {} std::string Filename() override { return "mockable"; } std::string Format() override { return "mock"; } std::unique_ptr<DatabaseBatch> MakeBatch(bool flush_on_close = true) override { return std::make_unique<MockableBatch>(m_records, m_pass); } }; std::unique_ptr<WalletDatabase> CreateMockableWalletDatabase(MockableData records = {}); MockableDatabase& GetMockableDatabase(CWallet& wallet); } // namespace wallet #endif // BITCOIN_WALLET_TEST_UTIL_H
0
bitcoin/src/wallet
bitcoin/src/wallet/test/rpc_util_tests.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/rpc/util.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_AUTO_TEST_SUITE(wallet_util_tests) BOOST_AUTO_TEST_CASE(util_ParseISO8601DateTime) { BOOST_CHECK_EQUAL(ParseISO8601DateTime("1970-01-01T00:00:00Z"), 0); BOOST_CHECK_EQUAL(ParseISO8601DateTime("1960-01-01T00:00:00Z"), 0); BOOST_CHECK_EQUAL(ParseISO8601DateTime("2000-01-01T00:00:01Z"), 946684801); BOOST_CHECK_EQUAL(ParseISO8601DateTime("2011-09-30T23:36:17Z"), 1317425777); BOOST_CHECK_EQUAL(ParseISO8601DateTime("2100-12-31T23:59:59Z"), 4133980799); } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/walletload_tests.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include <wallet/test/util.h> #include <wallet/wallet.h> #include <test/util/logging.h> #include <test/util/setup_common.h> #include <boost/test/unit_test.hpp> namespace wallet { BOOST_AUTO_TEST_SUITE(walletload_tests) class DummyDescriptor final : public Descriptor { private: std::string desc; public: explicit DummyDescriptor(const std::string& descriptor) : desc(descriptor) {}; ~DummyDescriptor() = default; std::string ToString(bool compat_format) const override { return desc; } std::optional<OutputType> GetOutputType() const override { return OutputType::UNKNOWN; } bool IsRange() const override { return false; } bool IsSolvable() const override { return false; } bool IsSingleType() const override { return true; } bool ToPrivateString(const SigningProvider& provider, std::string& out) const override { return false; } bool ToNormalizedString(const SigningProvider& provider, std::string& out, const DescriptorCache* cache = nullptr) const override { return false; } bool Expand(int pos, const SigningProvider& provider, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache = nullptr) const override { return false; }; bool ExpandFromCache(int pos, const DescriptorCache& read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out) const override { return false; } void ExpandPrivate(int pos, const SigningProvider& provider, FlatSigningProvider& out) const override {} std::optional<int64_t> ScriptSize() const override { return {}; } std::optional<int64_t> MaxSatisfactionWeight(bool) const override { return {}; } std::optional<int64_t> MaxSatisfactionElems() const override { return {}; } }; BOOST_FIXTURE_TEST_CASE(wallet_load_descriptors, TestingSetup) { std::unique_ptr<WalletDatabase> database = CreateMockableWalletDatabase(); { // Write unknown active descriptor WalletBatch batch(*database, false); std::string unknown_desc = "trx(tpubD6NzVbkrYhZ4Y4S7m6Y5s9GD8FqEMBy56AGphZXuagajudVZEnYyBahZMgHNCTJc2at82YX6s8JiL1Lohu5A3v1Ur76qguNH4QVQ7qYrBQx/86'/1'/0'/0/*)#8pn8tzdt"; WalletDescriptor wallet_descriptor(std::make_shared<DummyDescriptor>(unknown_desc), 0, 0, 0, 0); BOOST_CHECK(batch.WriteDescriptor(uint256(), wallet_descriptor)); BOOST_CHECK(batch.WriteActiveScriptPubKeyMan(static_cast<uint8_t>(OutputType::UNKNOWN), uint256(), false)); } { // Now try to load the wallet and verify the error. const std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(database))); BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::UNKNOWN_DESCRIPTOR); } // Test 2 // Now write a valid descriptor with an invalid ID. // As the software produces another ID for the descriptor, the loading process must be aborted. database = CreateMockableWalletDatabase(); // Verify the error bool found = false; DebugLogHelper logHelper("The descriptor ID calculated by the wallet differs from the one in DB", [&](const std::string* s) { found = true; return false; }); { // Write valid descriptor with invalid ID WalletBatch batch(*database, false); std::string desc = "wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu"; WalletDescriptor wallet_descriptor(std::make_shared<DummyDescriptor>(desc), 0, 0, 0, 0); BOOST_CHECK(batch.WriteDescriptor(uint256::ONE, wallet_descriptor)); } { // Now try to load the wallet and verify the error. const std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", std::move(database))); BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT); BOOST_CHECK(found); // The error must be logged } } bool HasAnyRecordOfType(WalletDatabase& db, const std::string& key) { std::unique_ptr<DatabaseBatch> batch = db.MakeBatch(false); BOOST_CHECK(batch); std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor(); BOOST_CHECK(cursor); while (true) { DataStream ssKey{}; DataStream ssValue{}; DatabaseCursor::Status status = cursor->Next(ssKey, ssValue); assert(status != DatabaseCursor::Status::FAIL); if (status == DatabaseCursor::Status::DONE) break; std::string type; ssKey >> type; if (type == key) return true; } return false; } template<typename... Args> SerializeData MakeSerializeData(const Args&... args) { DataStream s{}; SerializeMany(s, args...); return {s.begin(), s.end()}; } BOOST_FIXTURE_TEST_CASE(wallet_load_ckey, TestingSetup) { SerializeData ckey_record_key; SerializeData ckey_record_value; MockableData records; { // Context setup. // Create and encrypt legacy wallet std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase())); LOCK(wallet->cs_wallet); auto legacy_spkm = wallet->GetOrCreateLegacyScriptPubKeyMan(); BOOST_CHECK(legacy_spkm->SetupGeneration(true)); // Retrieve a key CTxDestination dest = *Assert(legacy_spkm->GetNewDestination(OutputType::LEGACY)); CKeyID key_id = GetKeyForDestination(*legacy_spkm, dest); CKey first_key; BOOST_CHECK(legacy_spkm->GetKey(key_id, first_key)); // Encrypt the wallet BOOST_CHECK(wallet->EncryptWallet("encrypt")); wallet->Flush(); // Store a copy of all the records records = GetMockableDatabase(*wallet).m_records; // Get the record for the retrieved key ckey_record_key = MakeSerializeData(DBKeys::CRYPTED_KEY, first_key.GetPubKey()); ckey_record_value = records.at(ckey_record_key); } { // First test case: // Erase all the crypted keys from db and unlock the wallet. // The wallet will only re-write the crypted keys to db if any checksum is missing at load time. // So, if any 'ckey' record re-appears on db, then the checksums were not properly calculated, and we are re-writing // the records every time that 'CWallet::Unlock' gets called, which is not good. // Load the wallet and check that is encrypted std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records))); BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK); BOOST_CHECK(wallet->IsCrypted()); BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY)); // Now delete all records and check that the 'Unlock' function doesn't re-write them BOOST_CHECK(wallet->GetLegacyScriptPubKeyMan()->DeleteRecords()); BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY)); BOOST_CHECK(wallet->Unlock("encrypt")); BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY)); } { // Second test case: // Verify that loading up a 'ckey' with no checksum triggers a complete re-write of the crypted keys. // Cut off the 32 byte checksum from a ckey record records[ckey_record_key].resize(ckey_record_value.size() - 32); // Load the wallet and check that is encrypted std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records))); BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::LOAD_OK); BOOST_CHECK(wallet->IsCrypted()); BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY)); // Now delete all ckey records and check that the 'Unlock' function re-writes them // (this is because the wallet, at load time, found a ckey record with no checksum) BOOST_CHECK(wallet->GetLegacyScriptPubKeyMan()->DeleteRecords()); BOOST_CHECK(!HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY)); BOOST_CHECK(wallet->Unlock("encrypt")); BOOST_CHECK(HasAnyRecordOfType(wallet->GetDatabase(), DBKeys::CRYPTED_KEY)); } { // Third test case: // Verify that loading up a 'ckey' with an invalid checksum throws an error. // Cut off the 32 byte checksum from a ckey record records[ckey_record_key].resize(ckey_record_value.size() - 32); // Fill in the checksum space with 0s records[ckey_record_key].resize(ckey_record_value.size()); std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records))); BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT); } { // Fourth test case: // Verify that loading up a 'ckey' with an invalid pubkey throws an error CPubKey invalid_key; BOOST_CHECK(!invalid_key.IsValid()); SerializeData key = MakeSerializeData(DBKeys::CRYPTED_KEY, invalid_key); records[key] = ckey_record_value; std::shared_ptr<CWallet> wallet(new CWallet(m_node.chain.get(), "", CreateMockableWalletDatabase(records))); BOOST_CHECK_EQUAL(wallet->LoadWallet(), DBErrors::CORRUPT); } } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/init_test_fixture.h
// Copyright (c) 2018-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_TEST_INIT_TEST_FIXTURE_H #define BITCOIN_WALLET_TEST_INIT_TEST_FIXTURE_H #include <interfaces/chain.h> #include <interfaces/wallet.h> #include <node/context.h> #include <test/util/setup_common.h> #include <util/chaintype.h> namespace wallet { struct InitWalletDirTestingSetup: public BasicTestingSetup { explicit InitWalletDirTestingSetup(const ChainType chain_type = ChainType::MAIN); ~InitWalletDirTestingSetup(); void SetWalletDir(const fs::path& walletdir_path); fs::path m_datadir; fs::path m_cwd; std::map<std::string, fs::path> m_walletdir_path_cases; std::unique_ptr<interfaces::WalletLoader> m_wallet_loader; }; #endif // BITCOIN_WALLET_TEST_INIT_TEST_FIXTURE_H } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/test/psbt_wallet_tests.cpp
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key_io.h> #include <util/bip32.h> #include <util/strencodings.h> #include <wallet/wallet.h> #include <boost/test/unit_test.hpp> #include <test/util/setup_common.h> #include <wallet/test/wallet_test_fixture.h> namespace wallet { BOOST_FIXTURE_TEST_SUITE(psbt_wallet_tests, WalletTestingSetup) static void import_descriptor(CWallet& wallet, const std::string& descriptor) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { AssertLockHeld(wallet.cs_wallet); FlatSigningProvider provider; std::string error; std::unique_ptr<Descriptor> desc = Parse(descriptor, provider, error, /* require_checksum=*/ false); assert(desc); WalletDescriptor w_desc(std::move(desc), 0, 0, 10, 0); wallet.AddWalletDescriptor(w_desc, provider, "", false); } BOOST_AUTO_TEST_CASE(psbt_updater_test) { LOCK(m_wallet.cs_wallet); m_wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); // Create prevtxs and add to wallet DataStream s_prev_tx1{ ParseHex("0200000000010158e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd7501000000171600145f275f436b09a8cc9a2eb2a2f528485c68a56323feffffff02d8231f1b0100000017a914aed962d6654f9a2b36608eb9d64d2b260db4f1118700c2eb0b0000000017a914b7f5faf40e3d40a5a459b1db3535f2b72fa921e88702483045022100a22edcc6e5bc511af4cc4ae0de0fcd75c7e04d8c1c3a8aa9d820ed4b967384ec02200642963597b9b1bc22c75e9f3e117284a962188bf5e8a74c895089046a20ad770121035509a48eb623e10aace8bfd0212fdb8a8e5af3c94b0b133b95e114cab89e4f7965000000"), }; CTransactionRef prev_tx1; s_prev_tx1 >> TX_WITH_WITNESS(prev_tx1); m_wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(prev_tx1->GetHash()), std::forward_as_tuple(prev_tx1, TxStateInactive{})); DataStream s_prev_tx2{ ParseHex("0200000001aad73931018bd25f84ae400b68848be09db706eac2ac18298babee71ab656f8b0000000048473044022058f6fc7c6a33e1b31548d481c826c015bd30135aad42cd67790dab66d2ad243b02204a1ced2604c6735b6393e5b41691dd78b00f0c5942fb9f751856faa938157dba01feffffff0280f0fa020000000017a9140fb9463421696b82c833af241c78c17ddbde493487d0f20a270100000017a91429ca74f8a08f81999428185c97b5d852e4063f618765000000"), }; CTransactionRef prev_tx2; s_prev_tx2 >> TX_WITH_WITNESS(prev_tx2); m_wallet.mapWallet.emplace(std::piecewise_construct, std::forward_as_tuple(prev_tx2->GetHash()), std::forward_as_tuple(prev_tx2, TxStateInactive{})); // Import descriptors for keys and scripts import_descriptor(m_wallet, "sh(multi(2,xprv9s21ZrQH143K2LE7W4Xf3jATf9jECxSb7wj91ZnmY4qEJrS66Qru9RFqq8xbkgT32ya6HqYJweFdJUEDf5Q6JFV7jMiUws7kQfe6Tv4RbfN/0h/0h/0h,xprv9s21ZrQH143K2LE7W4Xf3jATf9jECxSb7wj91ZnmY4qEJrS66Qru9RFqq8xbkgT32ya6HqYJweFdJUEDf5Q6JFV7jMiUws7kQfe6Tv4RbfN/0h/0h/1h))"); import_descriptor(m_wallet, "sh(wsh(multi(2,xprv9s21ZrQH143K2LE7W4Xf3jATf9jECxSb7wj91ZnmY4qEJrS66Qru9RFqq8xbkgT32ya6HqYJweFdJUEDf5Q6JFV7jMiUws7kQfe6Tv4RbfN/0h/0h/2h,xprv9s21ZrQH143K2LE7W4Xf3jATf9jECxSb7wj91ZnmY4qEJrS66Qru9RFqq8xbkgT32ya6HqYJweFdJUEDf5Q6JFV7jMiUws7kQfe6Tv4RbfN/0h/0h/3h)))"); import_descriptor(m_wallet, "wpkh(xprv9s21ZrQH143K2LE7W4Xf3jATf9jECxSb7wj91ZnmY4qEJrS66Qru9RFqq8xbkgT32ya6HqYJweFdJUEDf5Q6JFV7jMiUws7kQfe6Tv4RbfN/0h/0h/*h)"); // Call FillPSBT PartiallySignedTransaction psbtx; DataStream ssData{ ParseHex("70736274ff01009a020000000258e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd750000000000ffffffff838d0427d0ec650a68aa46bb0b098aea4422c071b2ca78352a077959d07cea1d0100000000ffffffff0270aaf00800000000160014d85c2b71d0060b09c9886aeb815e50991dda124d00e1f5050000000016001400aea9a2e5f0f876a588df5546e8742d1d87008f000000000000000000"), }; ssData >> psbtx; // Fill transaction with our data bool complete = true; BOOST_REQUIRE_EQUAL(TransactionError::OK, m_wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, false, true)); // Get the final tx DataStream ssTx{}; ssTx << psbtx; std::string final_hex = HexStr(ssTx); BOOST_CHECK_EQUAL(final_hex, "70736274ff01009a020000000258e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd750000000000ffffffff838d0427d0ec650a68aa46bb0b098aea4422c071b2ca78352a077959d07cea1d0100000000ffffffff0270aaf00800000000160014d85c2b71d0060b09c9886aeb815e50991dda124d00e1f5050000000016001400aea9a2e5f0f876a588df5546e8742d1d87008f00000000000100bb0200000001aad73931018bd25f84ae400b68848be09db706eac2ac18298babee71ab656f8b0000000048473044022058f6fc7c6a33e1b31548d481c826c015bd30135aad42cd67790dab66d2ad243b02204a1ced2604c6735b6393e5b41691dd78b00f0c5942fb9f751856faa938157dba01feffffff0280f0fa020000000017a9140fb9463421696b82c833af241c78c17ddbde493487d0f20a270100000017a91429ca74f8a08f81999428185c97b5d852e4063f6187650000000104475221029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f2102dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d752ae2206029583bf39ae0a609747ad199addd634fa6108559d6c5cd39b4c2183f1ab96e07f10d90c6a4f000000800000008000000080220602dab61ff49a14db6a7d02b0cd1fbb78fc4b18312b5b4e54dae4dba2fbfef536d710d90c6a4f0000008000000080010000800001008a020000000158e87a21b56daf0c23be8e7070456c336f7cbaa5c8757924f545887bb2abdd7501000000171600145f275f436b09a8cc9a2eb2a2f528485c68a56323feffffff02d8231f1b0100000017a914aed962d6654f9a2b36608eb9d64d2b260db4f1118700c2eb0b0000000017a914b7f5faf40e3d40a5a459b1db3535f2b72fa921e8876500000001012000c2eb0b0000000017a914b7f5faf40e3d40a5a459b1db3535f2b72fa921e88701042200208c2353173743b595dfb4a07b72ba8e42e3797da74e87fe7d9d7497e3b2028903010547522103089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc21023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7352ae2206023add904f3d6dcf59ddb906b0dee23529b7ffb9ed50e5e86151926860221f0e7310d90c6a4f000000800000008003000080220603089dc10c7ac6db54f91329af617333db388cead0c231f723379d1b99030b02dc10d90c6a4f00000080000000800200008000220203a9a4c37f5996d3aa25dbac6b570af0650394492942460b354753ed9eeca5877110d90c6a4f000000800000008004000080002202027f6399757d2eff55a136ad02c684b1838b6556e5f1b6b34282a94b6b5005109610d90c6a4f00000080000000800500008000"); // Mutate the transaction so that one of the inputs is invalid psbtx.tx->vin[0].prevout.n = 2; // Try to sign the mutated input SignatureData sigdata; BOOST_CHECK(m_wallet.FillPSBT(psbtx, complete, SIGHASH_ALL, true, true) != TransactionError::OK); } BOOST_AUTO_TEST_CASE(parse_hd_keypath) { std::vector<uint32_t> keypath; BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1", keypath)); BOOST_CHECK(!ParseHDKeypath("///////////////////////////", keypath)); BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1'/1", keypath)); BOOST_CHECK(!ParseHDKeypath("//////////////////////////'/", keypath)); BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/", keypath)); BOOST_CHECK(!ParseHDKeypath("1///////////////////////////", keypath)); BOOST_CHECK(ParseHDKeypath("1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1/1'/", keypath)); BOOST_CHECK(!ParseHDKeypath("1/'//////////////////////////", keypath)); BOOST_CHECK(ParseHDKeypath("", keypath)); BOOST_CHECK(!ParseHDKeypath(" ", keypath)); BOOST_CHECK(ParseHDKeypath("0", keypath)); BOOST_CHECK(!ParseHDKeypath("O", keypath)); BOOST_CHECK(ParseHDKeypath("0000'/0000'/0000'", keypath)); BOOST_CHECK(!ParseHDKeypath("0000,/0000,/0000,", keypath)); BOOST_CHECK(ParseHDKeypath("01234", keypath)); BOOST_CHECK(!ParseHDKeypath("0x1234", keypath)); BOOST_CHECK(ParseHDKeypath("1", keypath)); BOOST_CHECK(!ParseHDKeypath(" 1", keypath)); BOOST_CHECK(ParseHDKeypath("42", keypath)); BOOST_CHECK(!ParseHDKeypath("m42", keypath)); BOOST_CHECK(ParseHDKeypath("4294967295", keypath)); // 4294967295 == 0xFFFFFFFF (uint32_t max) BOOST_CHECK(!ParseHDKeypath("4294967296", keypath)); // 4294967296 == 0xFFFFFFFF (uint32_t max) + 1 BOOST_CHECK(ParseHDKeypath("m", keypath)); BOOST_CHECK(!ParseHDKeypath("n", keypath)); BOOST_CHECK(ParseHDKeypath("m/", keypath)); BOOST_CHECK(!ParseHDKeypath("n/", keypath)); BOOST_CHECK(ParseHDKeypath("m/0", keypath)); BOOST_CHECK(!ParseHDKeypath("n/0", keypath)); BOOST_CHECK(ParseHDKeypath("m/0'", keypath)); BOOST_CHECK(!ParseHDKeypath("m/0''", keypath)); BOOST_CHECK(ParseHDKeypath("m/0'/0'", keypath)); BOOST_CHECK(!ParseHDKeypath("m/'0/0'", keypath)); BOOST_CHECK(ParseHDKeypath("m/0/0", keypath)); BOOST_CHECK(!ParseHDKeypath("n/0/0", keypath)); BOOST_CHECK(ParseHDKeypath("m/0/0/00", keypath)); BOOST_CHECK(!ParseHDKeypath("m/0/0/f00", keypath)); BOOST_CHECK(ParseHDKeypath("m/0/0/000000000000000000000000000000000000000000000000000000000000000000000000000000000000", keypath)); BOOST_CHECK(!ParseHDKeypath("m/1/1/111111111111111111111111111111111111111111111111111111111111111111111111111111111111", keypath)); BOOST_CHECK(ParseHDKeypath("m/0/00/0", keypath)); BOOST_CHECK(!ParseHDKeypath("m/0'/00/'0", keypath)); BOOST_CHECK(ParseHDKeypath("m/1/", keypath)); BOOST_CHECK(!ParseHDKeypath("m/1//", keypath)); BOOST_CHECK(ParseHDKeypath("m/0/4294967295", keypath)); // 4294967295 == 0xFFFFFFFF (uint32_t max) BOOST_CHECK(!ParseHDKeypath("m/0/4294967296", keypath)); // 4294967296 == 0xFFFFFFFF (uint32_t max) + 1 BOOST_CHECK(ParseHDKeypath("m/4294967295", keypath)); // 4294967295 == 0xFFFFFFFF (uint32_t max) BOOST_CHECK(!ParseHDKeypath("m/4294967296", keypath)); // 4294967296 == 0xFFFFFFFF (uint32_t max) + 1 } BOOST_AUTO_TEST_SUITE_END() } // namespace wallet
0
bitcoin/src/wallet/test
bitcoin/src/wallet/test/fuzz/scriptpubkeyman.cpp
// Copyright (c) 2023-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <addresstype.h> #include <chainparams.h> #include <coins.h> #include <key.h> #include <primitives/transaction.h> #include <psbt.h> #include <script/descriptor.h> #include <script/interpreter.h> #include <script/script.h> #include <script/signingprovider.h> #include <sync.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/fuzz/util/descriptor.h> #include <test/util/setup_common.h> #include <util/check.h> #include <util/translation.h> #include <validation.h> #include <wallet/scriptpubkeyman.h> #include <wallet/test/util.h> #include <wallet/types.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> #include <map> #include <memory> #include <optional> #include <string> #include <utility> #include <variant> namespace wallet { namespace { const TestingSetup* g_setup; //! The converter of mocked descriptors, needs to be initialized when the target is. MockedDescriptorConverter MOCKED_DESC_CONVERTER; void initialize_spkm() { static const auto testing_setup{MakeNoLogFileContext<const TestingSetup>()}; g_setup = testing_setup.get(); SelectParams(ChainType::MAIN); MOCKED_DESC_CONVERTER.Init(); } static std::optional<std::pair<WalletDescriptor, FlatSigningProvider>> CreateWalletDescriptor(FuzzedDataProvider& fuzzed_data_provider) { const std::string mocked_descriptor{fuzzed_data_provider.ConsumeRandomLengthString()}; const auto desc_str{MOCKED_DESC_CONVERTER.GetDescriptor(mocked_descriptor)}; if (!desc_str.has_value()) return std::nullopt; FlatSigningProvider keys; std::string error; std::unique_ptr<Descriptor> parsed_desc{Parse(desc_str.value(), keys, error, false)}; if (!parsed_desc) return std::nullopt; WalletDescriptor w_desc{std::move(parsed_desc), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/1}; return std::make_pair(w_desc, keys); } static DescriptorScriptPubKeyMan* CreateDescriptor(WalletDescriptor& wallet_desc, FlatSigningProvider& keys, CWallet& keystore) { LOCK(keystore.cs_wallet); keystore.AddWalletDescriptor(wallet_desc, keys, /*label=*/"", /*internal=*/false); return keystore.GetDescriptorScriptPubKeyMan(wallet_desc); }; FUZZ_TARGET(scriptpubkeyman, .init = initialize_spkm) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const auto& node{g_setup->m_node}; Chainstate& chainstate{node.chainman->ActiveChainstate()}; std::unique_ptr<CWallet> wallet_ptr{std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase())}; CWallet& wallet{*wallet_ptr}; { LOCK(wallet.cs_wallet); wallet.SetWalletFlag(WALLET_FLAG_DESCRIPTORS); wallet.SetLastBlockProcessed(chainstate.m_chain.Height(), chainstate.m_chain.Tip()->GetBlockHash()); } auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)}; if (!wallet_desc.has_value()) return; auto spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)}; if (spk_manager == nullptr) return; bool good_data{true}; LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 300) { CallOneOf( fuzzed_data_provider, [&] { auto wallet_desc{CreateWalletDescriptor(fuzzed_data_provider)}; if (!wallet_desc.has_value()) { good_data = false; return; } std::string error; if (spk_manager->CanUpdateToWalletDescriptor(wallet_desc->first, error)) { auto new_spk_manager{CreateDescriptor(wallet_desc->first, wallet_desc->second, wallet)}; if (new_spk_manager != nullptr) spk_manager = new_spk_manager; } }, [&] { const CScript script{ConsumeScript(fuzzed_data_provider)}; auto is_mine{spk_manager->IsMine(script)}; if (is_mine == isminetype::ISMINE_SPENDABLE) { assert(spk_manager->GetScriptPubKeys().count(script)); } }, [&] { auto spks{spk_manager->GetScriptPubKeys()}; for (const CScript& spk : spks) { assert(spk_manager->IsMine(spk) == ISMINE_SPENDABLE); CTxDestination dest; bool extract_dest{ExtractDestination(spk, dest)}; if (extract_dest) { const std::string msg{fuzzed_data_provider.ConsumeRandomLengthString()}; PKHash pk_hash{std::get_if<PKHash>(&dest) && fuzzed_data_provider.ConsumeBool() ? *std::get_if<PKHash>(&dest) : PKHash{ConsumeUInt160(fuzzed_data_provider)}}; std::string str_sig; (void)spk_manager->SignMessage(msg, pk_hash, str_sig); } } }, [&] { CKey key{ConsumePrivateKey(fuzzed_data_provider, /*compressed=*/fuzzed_data_provider.ConsumeBool())}; if (!key.IsValid()) { good_data = false; return; } spk_manager->AddDescriptorKey(key, key.GetPubKey()); spk_manager->TopUp(); }, [&] { std::string descriptor; (void)spk_manager->GetDescriptorString(descriptor, /*priv=*/fuzzed_data_provider.ConsumeBool()); }, [&] { LOCK(spk_manager->cs_desc_man); auto wallet_desc{spk_manager->GetWalletDescriptor()}; if (wallet_desc.descriptor->IsSingleType()) { auto output_type{wallet_desc.descriptor->GetOutputType()}; if (output_type.has_value()) { auto dest{spk_manager->GetNewDestination(*output_type)}; if (dest) { assert(IsValidDestination(*dest)); assert(spk_manager->IsHDEnabled()); } } } }, [&] { CMutableTransaction tx_to; const std::optional<CMutableTransaction> opt_tx_to{ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS)}; if (!opt_tx_to) { good_data = false; return; } tx_to = *opt_tx_to; std::map<COutPoint, Coin> coins{ConsumeCoins(fuzzed_data_provider)}; const int sighash{fuzzed_data_provider.ConsumeIntegral<int>()}; std::map<int, bilingual_str> input_errors; (void)spk_manager->SignTransaction(tx_to, coins, sighash, input_errors); }, [&] { std::optional<PartiallySignedTransaction> opt_psbt{ConsumeDeserializable<PartiallySignedTransaction>(fuzzed_data_provider)}; if (!opt_psbt) { good_data = false; return; } auto psbt{*opt_psbt}; const PrecomputedTransactionData txdata{PrecomputePSBTData(psbt)}; const int sighash_type{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 150)}; (void)spk_manager->FillPSBT(psbt, txdata, sighash_type, fuzzed_data_provider.ConsumeBool(), fuzzed_data_provider.ConsumeBool(), nullptr, fuzzed_data_provider.ConsumeBool()); } ); } } } // namespace } // namespace wallet
0
bitcoin/src/wallet/test
bitcoin/src/wallet/test/fuzz/parse_iso8601.cpp
// Copyright (c) 2019-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <util/time.h> #include <wallet/rpc/util.h> #include <cassert> #include <cstdint> #include <string> #include <vector> FUZZ_TARGET(parse_iso8601) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const int64_t random_time = fuzzed_data_provider.ConsumeIntegral<int32_t>(); const std::string random_string = fuzzed_data_provider.ConsumeRemainingBytesAsString(); const std::string iso8601_datetime = FormatISO8601DateTime(random_time); (void)FormatISO8601Date(random_time); const int64_t parsed_time_1 = wallet::ParseISO8601DateTime(iso8601_datetime); if (random_time >= 0) { assert(parsed_time_1 >= 0); if (iso8601_datetime.length() == 20) { assert(parsed_time_1 == random_time); } } const int64_t parsed_time_2 = wallet::ParseISO8601DateTime(random_string); assert(parsed_time_2 >= 0); }
0
bitcoin/src/wallet/test
bitcoin/src/wallet/test/fuzz/notifications.cpp
// Copyright (c) 2021-present The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <addresstype.h> #include <common/args.h> #include <consensus/amount.h> #include <interfaces/chain.h> #include <kernel/chain.h> #include <outputtype.h> #include <policy/feerate.h> #include <policy/policy.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <script/descriptor.h> #include <script/script.h> #include <script/signingprovider.h> #include <sync.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <tinyformat.h> #include <uint256.h> #include <util/check.h> #include <util/result.h> #include <util/translation.h> #include <wallet/coincontrol.h> #include <wallet/context.h> #include <wallet/fees.h> #include <wallet/receive.h> #include <wallet/spend.h> #include <wallet/test/util.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> #include <cstddef> #include <cstdint> #include <limits> #include <numeric> #include <set> #include <string> #include <tuple> #include <utility> #include <vector> namespace wallet { namespace { const TestingSetup* g_setup; void initialize_setup() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); } void ImportDescriptors(CWallet& wallet, const std::string& seed_insecure) { const std::vector<std::string> DESCS{ "pkh(%s/%s/*)", "sh(wpkh(%s/%s/*))", "tr(%s/%s/*)", "wpkh(%s/%s/*)", }; for (const std::string& desc_fmt : DESCS) { for (bool internal : {true, false}) { const auto descriptor{(strprintf)(desc_fmt, "[5aa9973a/66h/4h/2h]" + seed_insecure, int{internal})}; FlatSigningProvider keys; std::string error; auto parsed_desc = Parse(descriptor, keys, error, /*require_checksum=*/false); assert(parsed_desc); assert(error.empty()); assert(parsed_desc->IsRange()); assert(parsed_desc->IsSingleType()); assert(!keys.keys.empty()); WalletDescriptor w_desc{std::move(parsed_desc), /*creation_time=*/0, /*range_start=*/0, /*range_end=*/1, /*next_index=*/0}; assert(!wallet.GetDescriptorScriptPubKeyMan(w_desc)); LOCK(wallet.cs_wallet); auto spk_manager{wallet.AddWalletDescriptor(w_desc, keys, /*label=*/"", internal)}; assert(spk_manager); wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *Assert(w_desc.descriptor->GetOutputType()), internal); } } } /** * Wraps a descriptor wallet for fuzzing. */ struct FuzzedWallet { ArgsManager args; WalletContext context; std::shared_ptr<CWallet> wallet; FuzzedWallet(const std::string& name, const std::string& seed_insecure) { auto& chain{*Assert(g_setup->m_node.chain)}; wallet = std::make_shared<CWallet>(&chain, name, CreateMockableWalletDatabase()); { LOCK(wallet->cs_wallet); wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS); auto height{*Assert(chain.getHeight())}; wallet->SetLastBlockProcessed(height, chain.getBlockHash(height)); } wallet->m_keypool_size = 1; // Avoid timeout in TopUp() assert(wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)); ImportDescriptors(*wallet, seed_insecure); } CTxDestination GetDestination(FuzzedDataProvider& fuzzed_data_provider) { auto type{fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)}; util::Result<CTxDestination> op_dest{util::Error{}}; if (fuzzed_data_provider.ConsumeBool()) { op_dest = wallet->GetNewDestination(type, ""); } else { op_dest = wallet->GetNewChangeDestination(type); } return *Assert(op_dest); } CScript GetScriptPubKey(FuzzedDataProvider& fuzzed_data_provider) { return GetScriptForDestination(GetDestination(fuzzed_data_provider)); } void FundTx(FuzzedDataProvider& fuzzed_data_provider, CMutableTransaction tx) { // The fee of "tx" is 0, so this is the total input and output amount const CAmount total_amt{ std::accumulate(tx.vout.begin(), tx.vout.end(), CAmount{}, [](CAmount t, const CTxOut& out) { return t + out.nValue; })}; const uint32_t tx_size(GetVirtualTransactionSize(CTransaction{tx})); std::set<int> subtract_fee_from_outputs; if (fuzzed_data_provider.ConsumeBool()) { for (size_t i{}; i < tx.vout.size(); ++i) { if (fuzzed_data_provider.ConsumeBool()) { subtract_fee_from_outputs.insert(i); } } } CCoinControl coin_control; coin_control.m_allow_other_inputs = fuzzed_data_provider.ConsumeBool(); CallOneOf( fuzzed_data_provider, [&] { coin_control.destChange = GetDestination(fuzzed_data_provider); }, [&] { coin_control.m_change_type.emplace(fuzzed_data_provider.PickValueInArray(OUTPUT_TYPES)); }, [&] { /* no op (leave uninitialized) */ }); coin_control.fAllowWatchOnly = fuzzed_data_provider.ConsumeBool(); coin_control.m_include_unsafe_inputs = fuzzed_data_provider.ConsumeBool(); { auto& r{coin_control.m_signal_bip125_rbf}; CallOneOf( fuzzed_data_provider, [&] { r = true; }, [&] { r = false; }, [&] { r = std::nullopt; }); } coin_control.m_feerate = CFeeRate{ // A fee of this range should cover all cases fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, 2 * total_amt), tx_size, }; if (fuzzed_data_provider.ConsumeBool()) { *coin_control.m_feerate += GetMinimumFeeRate(*wallet, coin_control, nullptr); } coin_control.fOverrideFeeRate = fuzzed_data_provider.ConsumeBool(); // Add solving data (m_external_provider and SelectExternal)? int change_position{fuzzed_data_provider.ConsumeIntegralInRange<int>(-1, tx.vout.size() - 1)}; bilingual_str error; (void)FundTransaction(*wallet, tx, change_position, /*lockUnspents=*/false, subtract_fee_from_outputs, coin_control); } }; FUZZ_TARGET(wallet_notifications, .init = initialize_setup) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; // The total amount, to be distributed to the wallets a and b in txs // without fee. Thus, the balance of the wallets should always equal the // total amount. const auto total_amount{ConsumeMoney(fuzzed_data_provider, /*max=*/MAX_MONEY / 100000)}; FuzzedWallet a{ "fuzzed_wallet_a", "tprv8ZgxMBicQKsPd1QwsGgzfu2pcPYbBosZhJknqreRHgsWx32nNEhMjGQX2cgFL8n6wz9xdDYwLcs78N4nsCo32cxEX8RBtwGsEGgybLiQJfk", }; FuzzedWallet b{ "fuzzed_wallet_b", "tprv8ZgxMBicQKsPfCunYTF18sEmEyjz8TfhGnZ3BoVAhkqLv7PLkQgmoG2Ecsp4JuqciWnkopuEwShit7st743fdmB9cMD4tznUkcs33vK51K9", }; // Keep track of all coins in this test. // Each tuple in the chain represents the coins and the block created with // those coins. Once the block is mined, the next tuple will have an empty // block and the freshly mined coins. using Coins = std::set<std::tuple<CAmount, COutPoint>>; std::vector<std::tuple<Coins, CBlock>> chain; { // Add the initial entry chain.emplace_back(); auto& [coins, block]{chain.back()}; coins.emplace(total_amount, COutPoint{Txid::FromUint256(uint256::ONE), 1}); } LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 200) { CallOneOf( fuzzed_data_provider, [&] { auto& [coins_orig, block]{chain.back()}; // Copy the coins for this block and consume all of them Coins coins = coins_orig; while (!coins.empty()) { // Create a new tx CMutableTransaction tx{}; // Add some coins as inputs to it auto num_inputs{fuzzed_data_provider.ConsumeIntegralInRange<int>(1, coins.size())}; CAmount in{0}; while (num_inputs-- > 0) { const auto& [coin_amt, coin_outpoint]{*coins.begin()}; in += coin_amt; tx.vin.emplace_back(coin_outpoint); coins.erase(coins.begin()); } // Create some outputs spending all inputs, without fee LIMITED_WHILE(in > 0 && fuzzed_data_provider.ConsumeBool(), 10) { const auto out_value{ConsumeMoney(fuzzed_data_provider, in)}; in -= out_value; auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b}; tx.vout.emplace_back(out_value, wallet.GetScriptPubKey(fuzzed_data_provider)); } // Spend the remaining input value, if any auto& wallet{fuzzed_data_provider.ConsumeBool() ? a : b}; tx.vout.emplace_back(in, wallet.GetScriptPubKey(fuzzed_data_provider)); // Add tx to block block.vtx.emplace_back(MakeTransactionRef(tx)); // Check that funding the tx doesn't crash the wallet a.FundTx(fuzzed_data_provider, tx); b.FundTx(fuzzed_data_provider, tx); } // Mine block const uint256& hash = block.GetHash(); interfaces::BlockInfo info{hash}; info.prev_hash = &block.hashPrevBlock; info.height = chain.size(); info.data = &block; // Ensure that no blocks are skipped by the wallet by setting the chain's accumulated // time to the maximum value. This ensures that the wallet's birth time is always // earlier than this maximum time. info.chain_time_max = std::numeric_limits<unsigned int>::max(); a.wallet->blockConnected(ChainstateRole::NORMAL, info); b.wallet->blockConnected(ChainstateRole::NORMAL, info); // Store the coins for the next block Coins coins_new; for (const auto& tx : block.vtx) { uint32_t i{0}; for (const auto& out : tx->vout) { coins_new.emplace(out.nValue, COutPoint{tx->GetHash(), i++}); } } chain.emplace_back(coins_new, CBlock{}); }, [&] { if (chain.size() <= 1) return; // The first entry can't be removed auto& [coins, block]{chain.back()}; if (block.vtx.empty()) return; // Can only disconnect if the block was submitted first // Disconnect block const uint256& hash = block.GetHash(); interfaces::BlockInfo info{hash}; info.prev_hash = &block.hashPrevBlock; info.height = chain.size() - 1; info.data = &block; a.wallet->blockDisconnected(info); b.wallet->blockDisconnected(info); chain.pop_back(); }); auto& [coins, first_block]{chain.front()}; if (!first_block.vtx.empty()) { // Only check balance when at least one block was submitted const auto bal_a{GetBalance(*a.wallet).m_mine_trusted}; const auto bal_b{GetBalance(*b.wallet).m_mine_trusted}; assert(total_amount == bal_a + bal_b); } } } } // namespace } // namespace wallet
0
bitcoin/src/wallet/test
bitcoin/src/wallet/test/fuzz/coincontrol.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <wallet/coincontrol.h> #include <wallet/test/util.h> namespace wallet { namespace { const TestingSetup* g_setup; void initialize_coincontrol() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); } FUZZ_TARGET(coincontrol, .init = initialize_coincontrol) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const auto& node = g_setup->m_node; ArgsManager& args = *node.args; // for GetBoolArg to return true sometimes args.ForceSetArg("-avoidpartialspends", fuzzed_data_provider.ConsumeBool()?"1":"0"); CCoinControl coin_control; COutPoint out_point; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { CallOneOf( fuzzed_data_provider, [&] { std::optional<COutPoint> optional_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider); if (!optional_out_point) { return; } out_point = *optional_out_point; }, [&] { (void)coin_control.HasSelected(); }, [&] { (void)coin_control.IsSelected(out_point); }, [&] { (void)coin_control.IsExternalSelected(out_point); }, [&] { (void)coin_control.GetExternalOutput(out_point); }, [&] { (void)coin_control.Select(out_point); }, [&] { const CTxOut tx_out{ConsumeMoney(fuzzed_data_provider), ConsumeScript(fuzzed_data_provider)}; (void)coin_control.Select(out_point).SetTxOut(tx_out); }, [&] { (void)coin_control.UnSelect(out_point); }, [&] { (void)coin_control.UnSelectAll(); }, [&] { (void)coin_control.ListSelected(); }, [&] { int64_t weight{fuzzed_data_provider.ConsumeIntegral<int64_t>()}; (void)coin_control.SetInputWeight(out_point, weight); }, [&] { (void)coin_control.GetInputWeight(out_point); }); } } } // namespace } // namespace wallet
0
bitcoin/src/wallet/test
bitcoin/src/wallet/test/fuzz/fees.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <wallet/coincontrol.h> #include <wallet/fees.h> #include <wallet/wallet.h> #include <wallet/test/util.h> #include <validation.h> namespace wallet { namespace { const TestingSetup* g_setup; static std::unique_ptr<CWallet> g_wallet_ptr; void initialize_setup() { static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); g_setup = testing_setup.get(); const auto& node{g_setup->m_node}; g_wallet_ptr = std::make_unique<CWallet>(node.chain.get(), "", CreateMockableWalletDatabase()); } FUZZ_TARGET(wallet_fees, .init = initialize_setup) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; const auto& node{g_setup->m_node}; Chainstate* chainstate = &node.chainman->ActiveChainstate(); CWallet& wallet = *g_wallet_ptr; { LOCK(wallet.cs_wallet); wallet.SetLastBlockProcessed(chainstate->m_chain.Height(), chainstate->m_chain.Tip()->GetBlockHash()); } if (fuzzed_data_provider.ConsumeBool()) { wallet.m_discard_rate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; } (void)GetDiscardRate(wallet); const auto tx_bytes{fuzzed_data_provider.ConsumeIntegral<unsigned int>()}; if (fuzzed_data_provider.ConsumeBool()) { wallet.m_pay_tx_fee = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; wallet.m_min_fee = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; } (void)GetRequiredFee(wallet, tx_bytes); (void)GetRequiredFeeRate(wallet); CCoinControl coin_control; if (fuzzed_data_provider.ConsumeBool()) { coin_control.m_feerate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; } if (fuzzed_data_provider.ConsumeBool()) { coin_control.m_confirm_target = fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(0, 999'000); } FeeCalculation fee_calculation; FeeCalculation* maybe_fee_calculation{fuzzed_data_provider.ConsumeBool() ? nullptr : &fee_calculation}; (void)GetMinimumFeeRate(wallet, coin_control, maybe_fee_calculation); (void)GetMinimumFee(wallet, tx_bytes, coin_control, maybe_fee_calculation); } } // namespace } // namespace wallet
0
bitcoin/src/wallet/test
bitcoin/src/wallet/test/fuzz/coinselection.cpp
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <policy/feerate.h> #include <policy/policy.h> #include <primitives/transaction.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/setup_common.h> #include <wallet/coinselection.h> #include <vector> namespace wallet { static void AddCoin(const CAmount& value, int n_input, int n_input_bytes, int locktime, std::vector<COutput>& coins, CFeeRate fee_rate) { CMutableTransaction tx; tx.vout.resize(n_input + 1); tx.vout[n_input].nValue = value; tx.nLockTime = locktime; // all transactions get different hashes coins.emplace_back(COutPoint(tx.GetHash(), n_input), tx.vout.at(n_input), /*depth=*/0, n_input_bytes, /*spendable=*/true, /*solvable=*/true, /*safe=*/true, /*time=*/0, /*from_me=*/true, fee_rate); } // Randomly distribute coins to instances of OutputGroup static void GroupCoins(FuzzedDataProvider& fuzzed_data_provider, const std::vector<COutput>& coins, const CoinSelectionParams& coin_params, bool positive_only, std::vector<OutputGroup>& output_groups) { auto output_group = OutputGroup(coin_params); bool valid_outputgroup{false}; for (auto& coin : coins) { if (!positive_only || (positive_only && coin.GetEffectiveValue() > 0)) { output_group.Insert(std::make_shared<COutput>(coin), /*ancestors=*/0, /*descendants=*/0); } // If positive_only was specified, nothing was inserted, leading to an empty output group // that would be invalid for the BnB algorithm valid_outputgroup = !positive_only || output_group.GetSelectionAmount() > 0; if (valid_outputgroup && fuzzed_data_provider.ConsumeBool()) { output_groups.push_back(output_group); output_group = OutputGroup(coin_params); valid_outputgroup = false; } } if (valid_outputgroup) output_groups.push_back(output_group); } static CAmount CreateCoins(FuzzedDataProvider& fuzzed_data_provider, std::vector<COutput>& utxo_pool, CoinSelectionParams& coin_params, int& next_locktime) { CAmount total_balance{0}; LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) { const int n_input{fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 10)}; const int n_input_bytes{fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 10000)}; const CAmount amount{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)}; if (total_balance + amount >= MAX_MONEY) { break; } AddCoin(amount, n_input, n_input_bytes, ++next_locktime, utxo_pool, coin_params.m_effective_feerate); total_balance += amount; } return total_balance; } static SelectionResult ManualSelection(std::vector<COutput>& utxos, const CAmount& total_amount, const bool& subtract_fee_outputs) { SelectionResult result(total_amount, SelectionAlgorithm::MANUAL); std::set<std::shared_ptr<COutput>> utxo_pool; for (const auto& utxo : utxos) { utxo_pool.insert(std::make_shared<COutput>(utxo)); } result.AddInputs(utxo_pool, subtract_fee_outputs); return result; } // Returns true if the result contains an error and the message is not empty static bool HasErrorMsg(const util::Result<SelectionResult>& res) { return !util::ErrorString(res).empty(); } FUZZ_TARGET(coinselection) { FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()}; std::vector<COutput> utxo_pool; const CFeeRate long_term_fee_rate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; const CFeeRate effective_fee_rate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)}; // Discard feerate must be at least dust relay feerate const CFeeRate discard_fee_rate{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(DUST_RELAY_TX_FEE, COIN)}; const CAmount target{fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(1, MAX_MONEY)}; const bool subtract_fee_outputs{fuzzed_data_provider.ConsumeBool()}; FastRandomContext fast_random_context{ConsumeUInt256(fuzzed_data_provider)}; CoinSelectionParams coin_params{fast_random_context}; coin_params.m_subtract_fee_outputs = subtract_fee_outputs; coin_params.m_long_term_feerate = long_term_fee_rate; coin_params.m_effective_feerate = effective_fee_rate; coin_params.change_output_size = fuzzed_data_provider.ConsumeIntegralInRange(1, MAX_SCRIPT_SIZE); coin_params.m_change_fee = effective_fee_rate.GetFee(coin_params.change_output_size); coin_params.m_discard_feerate = discard_fee_rate; coin_params.change_spend_size = fuzzed_data_provider.ConsumeIntegralInRange<int>(41, 1000); const auto change_spend_fee{coin_params.m_discard_feerate.GetFee(coin_params.change_spend_size)}; coin_params.m_cost_of_change = coin_params.m_change_fee + change_spend_fee; CScript change_out_script = CScript() << std::vector<unsigned char>(coin_params.change_output_size, OP_TRUE); const auto dust{GetDustThreshold(CTxOut{/*nValueIn=*/0, change_out_script}, coin_params.m_discard_feerate)}; coin_params.min_viable_change = std::max(change_spend_fee + 1, dust); int next_locktime{0}; CAmount total_balance{CreateCoins(fuzzed_data_provider, utxo_pool, coin_params, next_locktime)}; std::vector<OutputGroup> group_pos; GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/true, group_pos); std::vector<OutputGroup> group_all; GroupCoins(fuzzed_data_provider, utxo_pool, coin_params, /*positive_only=*/false, group_all); for (const OutputGroup& group : group_all) { const CoinEligibilityFilter filter(fuzzed_data_provider.ConsumeIntegral<int>(), fuzzed_data_provider.ConsumeIntegral<int>(), fuzzed_data_provider.ConsumeIntegral<uint64_t>()); (void)group.EligibleForSpending(filter); } // Run coinselection algorithms auto result_bnb = coin_params.m_subtract_fee_outputs ? util::Error{Untranslated("BnB disabled when SFFO is enabled")} : SelectCoinsBnB(group_pos, target, coin_params.m_cost_of_change, MAX_STANDARD_TX_WEIGHT); if (result_bnb) { assert(result_bnb->GetChange(coin_params.min_viable_change, coin_params.m_change_fee) == 0); assert(result_bnb->GetSelectedValue() >= target); (void)result_bnb->GetShuffledInputVector(); (void)result_bnb->GetInputSet(); } auto result_srd = SelectCoinsSRD(group_pos, target, coin_params.m_change_fee, fast_random_context, MAX_STANDARD_TX_WEIGHT); if (result_srd) { assert(result_srd->GetSelectedValue() >= target); assert(result_srd->GetChange(CHANGE_LOWER, coin_params.m_change_fee) > 0); // Demonstrate that SRD creates change of at least CHANGE_LOWER result_srd->ComputeAndSetWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee); (void)result_srd->GetShuffledInputVector(); (void)result_srd->GetInputSet(); } CAmount change_target{GenerateChangeTarget(target, coin_params.m_change_fee, fast_random_context)}; auto result_knapsack = KnapsackSolver(group_all, target, change_target, fast_random_context, MAX_STANDARD_TX_WEIGHT); if (result_knapsack) { assert(result_knapsack->GetSelectedValue() >= target); result_knapsack->ComputeAndSetWaste(coin_params.min_viable_change, coin_params.m_cost_of_change, coin_params.m_change_fee); (void)result_knapsack->GetShuffledInputVector(); (void)result_knapsack->GetInputSet(); } // If the total balance is sufficient for the target and we are not using // effective values, Knapsack should always find a solution (unless the selection exceeded the max tx weight). if (total_balance >= target && subtract_fee_outputs && !HasErrorMsg(result_knapsack)) { assert(result_knapsack); } std::vector<COutput> utxos; std::vector<util::Result<SelectionResult>> results{result_srd, result_knapsack, result_bnb}; CAmount new_total_balance{CreateCoins(fuzzed_data_provider, utxos, coin_params, next_locktime)}; if (new_total_balance > 0) { std::set<std::shared_ptr<COutput>> new_utxo_pool; for (const auto& utxo : utxos) { new_utxo_pool.insert(std::make_shared<COutput>(utxo)); } for (auto& result : results) { if (!result) continue; const auto weight{result->GetWeight()}; result->AddInputs(new_utxo_pool, subtract_fee_outputs); assert(result->GetWeight() > weight); } } std::vector<COutput> manual_inputs; CAmount manual_balance{CreateCoins(fuzzed_data_provider, manual_inputs, coin_params, next_locktime)}; if (manual_balance == 0) return; auto manual_selection{ManualSelection(manual_inputs, manual_balance, coin_params.m_subtract_fee_outputs)}; for (auto& result : results) { if (!result) continue; const CAmount old_target{result->GetTarget()}; const std::set<std::shared_ptr<COutput>> input_set{result->GetInputSet()}; const int old_weight{result->GetWeight()}; result->Merge(manual_selection); assert(result->GetInputSet().size() == input_set.size() + manual_inputs.size()); assert(result->GetTarget() == old_target + manual_selection.GetTarget()); assert(result->GetWeight() == old_weight + manual_selection.GetWeight()); } } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/addresses.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <key_io.h> #include <rpc/util.h> #include <script/script.h> #include <script/solver.h> #include <util/bip32.h> #include <util/translation.h> #include <wallet/receive.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> #include <univalue.h> namespace wallet { RPCHelpMan getnewaddress() { return RPCHelpMan{"getnewaddress", "\nReturns a new Bitcoin address for receiving payments.\n" "If 'label' is specified, it is added to the address book \n" "so payments received with the address will be associated with 'label'.\n", { {"label", RPCArg::Type::STR, RPCArg::Default{""}, "The label name for the address to be linked to. It can also be set to the empty string \"\" to represent the default label. The label does not need to exist, it will be created if there is no label by the given name."}, {"address_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -addresstype"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."}, }, RPCResult{ RPCResult::Type::STR, "address", "The new bitcoin address" }, RPCExamples{ HelpExampleCli("getnewaddress", "") + HelpExampleRpc("getnewaddress", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); if (!pwallet->CanGetAddresses()) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys"); } // Parse the label first so we don't generate a key if there's an error const std::string label{LabelFromValue(request.params[0])}; OutputType output_type = pwallet->m_default_address_type; if (!request.params[1].isNull()) { std::optional<OutputType> parsed = ParseOutputType(request.params[1].get_str()); if (!parsed) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[1].get_str())); } else if (parsed.value() == OutputType::BECH32M && pwallet->GetLegacyScriptPubKeyMan()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Legacy wallets cannot provide bech32m addresses"); } output_type = parsed.value(); } auto op_dest = pwallet->GetNewDestination(output_type, label); if (!op_dest) { throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, util::ErrorString(op_dest).original); } return EncodeDestination(*op_dest); }, }; } RPCHelpMan getrawchangeaddress() { return RPCHelpMan{"getrawchangeaddress", "\nReturns a new Bitcoin address, for receiving change.\n" "This is for use with raw transactions, NOT normal use.\n", { {"address_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."}, }, RPCResult{ RPCResult::Type::STR, "address", "The address" }, RPCExamples{ HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); if (!pwallet->CanGetAddresses(true)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys"); } OutputType output_type = pwallet->m_default_change_type.value_or(pwallet->m_default_address_type); if (!request.params[0].isNull()) { std::optional<OutputType> parsed = ParseOutputType(request.params[0].get_str()); if (!parsed) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str())); } else if (parsed.value() == OutputType::BECH32M && pwallet->GetLegacyScriptPubKeyMan()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Legacy wallets cannot provide bech32m addresses"); } output_type = parsed.value(); } auto op_dest = pwallet->GetNewChangeDestination(output_type); if (!op_dest) { throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, util::ErrorString(op_dest).original); } return EncodeDestination(*op_dest); }, }; } RPCHelpMan setlabel() { return RPCHelpMan{"setlabel", "\nSets the label associated with the given address.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to be associated with a label."}, {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label to assign to the address."}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("setlabel", "\"" + EXAMPLE_ADDRESS[0] + "\" \"tabby\"") + HelpExampleRpc("setlabel", "\"" + EXAMPLE_ADDRESS[0] + "\", \"tabby\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); CTxDestination dest = DecodeDestination(request.params[0].get_str()); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); } const std::string label{LabelFromValue(request.params[1])}; if (pwallet->IsMine(dest)) { pwallet->SetAddressBook(dest, label, AddressPurpose::RECEIVE); } else { pwallet->SetAddressBook(dest, label, AddressPurpose::SEND); } return UniValue::VNULL; }, }; } RPCHelpMan listaddressgroupings() { return RPCHelpMan{"listaddressgroupings", "\nLists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions\n", {}, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::ARR, "", "", { {RPCResult::Type::ARR_FIXED, "", "", { {RPCResult::Type::STR, "address", "The bitcoin address"}, {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT}, {RPCResult::Type::STR, "label", /*optional=*/true, "The label"}, }}, }}, } }, RPCExamples{ HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); UniValue jsonGroupings(UniValue::VARR); std::map<CTxDestination, CAmount> balances = GetAddressBalances(*pwallet); for (const std::set<CTxDestination>& grouping : GetAddressGroupings(*pwallet)) { UniValue jsonGrouping(UniValue::VARR); for (const CTxDestination& address : grouping) { UniValue addressInfo(UniValue::VARR); addressInfo.push_back(EncodeDestination(address)); addressInfo.push_back(ValueFromAmount(balances[address])); { const auto* address_book_entry = pwallet->FindAddressBookEntry(address); if (address_book_entry) { addressInfo.push_back(address_book_entry->GetLabel()); } } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; }, }; } RPCHelpMan addmultisigaddress() { return RPCHelpMan{"addmultisigaddress", "\nAdd an nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n" "Each key is a Bitcoin address or hex-encoded public key.\n" "This functionality is only intended for use with non-watchonly addresses.\n" "See `importaddress` for watchonly p2sh address support.\n" "If 'label' is specified, assign address to that label.\n" "Note: This command is only compatible with legacy wallets.\n", { {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys or addresses."}, {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The bitcoin addresses or hex-encoded public keys", { {"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "bitcoin address or hex-encoded public key"}, }, }, {"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A label to assign the addresses to."}, {"address_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -addresstype"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "address", "The value of the new multisig address"}, {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script"}, {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Any warnings resulting from the creation of this multisig", { {RPCResult::Type::STR, "", ""}, }}, } }, RPCExamples{ "\nAdd a multisig address from 2 addresses\n" + HelpExampleCli("addmultisigaddress", "2 \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet); LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore); const std::string label{LabelFromValue(request.params[2])}; int required = request.params[0].getInt<int>(); // Get the public keys const UniValue& keys_or_addrs = request.params[1].get_array(); std::vector<CPubKey> pubkeys; for (unsigned int i = 0; i < keys_or_addrs.size(); ++i) { if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) { pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str())); } else { pubkeys.push_back(AddrToPubKey(spk_man, keys_or_addrs[i].get_str())); } } OutputType output_type = pwallet->m_default_address_type; if (!request.params[3].isNull()) { std::optional<OutputType> parsed = ParseOutputType(request.params[3].get_str()); if (!parsed) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[3].get_str())); } else if (parsed.value() == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m multisig addresses cannot be created with legacy wallets"); } output_type = parsed.value(); } // Construct using pay-to-script-hash: CScript inner; CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, spk_man, inner); pwallet->SetAddressBook(dest, label, AddressPurpose::SEND); // Make the descriptor std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), spk_man); UniValue result(UniValue::VOBJ); result.pushKV("address", EncodeDestination(dest)); result.pushKV("redeemScript", HexStr(inner)); result.pushKV("descriptor", descriptor->ToString()); UniValue warnings(UniValue::VARR); if (descriptor->GetOutputType() != output_type) { // Only warns if the user has explicitly chosen an address type we cannot generate warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present."); } PushWarnings(warnings, result); return result; }, }; } RPCHelpMan keypoolrefill() { return RPCHelpMan{"keypoolrefill", "\nFills the keypool."+ HELP_REQUIRING_PASSPHRASE, { {"newsize", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%u, or as set by -keypool", DEFAULT_KEYPOOL_SIZE)}, "The new keypool size"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (pwallet->IsLegacy() && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet"); } LOCK(pwallet->cs_wallet); // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool unsigned int kpSize = 0; if (!request.params[0].isNull()) { if (request.params[0].getInt<int>() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size."); kpSize = (unsigned int)request.params[0].getInt<int>(); } EnsureWalletIsUnlocked(*pwallet); pwallet->TopUpKeyPool(kpSize); if (pwallet->GetKeyPoolSize() < kpSize) { throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); } return UniValue::VNULL; }, }; } RPCHelpMan newkeypool() { return RPCHelpMan{"newkeypool", "\nEntirely clears and refills the keypool.\n" "WARNING: On non-HD wallets, this will require a new backup immediately, to include the new keys.\n" "When restoring a backup of an HD wallet created before the newkeypool command is run, funds received to\n" "new addresses may not appear automatically. They have not been lost, but the wallet may not find them.\n" "This can be fixed by running the newkeypool command on the backup and then rescanning, so the wallet\n" "re-generates the required keys." + HELP_REQUIRING_PASSPHRASE, {}, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("newkeypool", "") + HelpExampleRpc("newkeypool", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet, true); spk_man.NewKeyPool(); return UniValue::VNULL; }, }; } class DescribeWalletAddressVisitor { public: const SigningProvider * const provider; void ProcessSubScript(const CScript& subscript, UniValue& obj) const { // Always present: script type and redeemscript std::vector<std::vector<unsigned char>> solutions_data; TxoutType which_type = Solver(subscript, solutions_data); obj.pushKV("script", GetTxnOutputType(which_type)); obj.pushKV("hex", HexStr(subscript)); CTxDestination embedded; if (ExtractDestination(subscript, embedded)) { // Only when the script corresponds to an address. UniValue subobj(UniValue::VOBJ); UniValue detail = DescribeAddress(embedded); subobj.pushKVs(detail); UniValue wallet_detail = std::visit(*this, embedded); subobj.pushKVs(wallet_detail); subobj.pushKV("address", EncodeDestination(embedded)); subobj.pushKV("scriptPubKey", HexStr(subscript)); // Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works. if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]); obj.pushKV("embedded", std::move(subobj)); } else if (which_type == TxoutType::MULTISIG) { // Also report some information on multisig scripts (which do not have a corresponding address). obj.pushKV("sigsrequired", solutions_data[0][0]); UniValue pubkeys(UniValue::VARR); for (size_t i = 1; i < solutions_data.size() - 1; ++i) { CPubKey key(solutions_data[i].begin(), solutions_data[i].end()); pubkeys.push_back(HexStr(key)); } obj.pushKV("pubkeys", std::move(pubkeys)); } } explicit DescribeWalletAddressVisitor(const SigningProvider* _provider) : provider(_provider) {} UniValue operator()(const CNoDestination& dest) const { return UniValue(UniValue::VOBJ); } UniValue operator()(const PubKeyDestination& dest) const { return UniValue(UniValue::VOBJ); } UniValue operator()(const PKHash& pkhash) const { CKeyID keyID{ToKeyID(pkhash)}; UniValue obj(UniValue::VOBJ); CPubKey vchPubKey; if (provider && provider->GetPubKey(keyID, vchPubKey)) { obj.pushKV("pubkey", HexStr(vchPubKey)); obj.pushKV("iscompressed", vchPubKey.IsCompressed()); } return obj; } UniValue operator()(const ScriptHash& scripthash) const { UniValue obj(UniValue::VOBJ); CScript subscript; if (provider && provider->GetCScript(ToScriptID(scripthash), subscript)) { ProcessSubScript(subscript, obj); } return obj; } UniValue operator()(const WitnessV0KeyHash& id) const { UniValue obj(UniValue::VOBJ); CPubKey pubkey; if (provider && provider->GetPubKey(ToKeyID(id), pubkey)) { obj.pushKV("pubkey", HexStr(pubkey)); } return obj; } UniValue operator()(const WitnessV0ScriptHash& id) const { UniValue obj(UniValue::VOBJ); CScript subscript; CRIPEMD160 hasher; uint160 hash; hasher.Write(id.begin(), 32).Finalize(hash.begin()); if (provider && provider->GetCScript(CScriptID(hash), subscript)) { ProcessSubScript(subscript, obj); } return obj; } UniValue operator()(const WitnessV1Taproot& id) const { return UniValue(UniValue::VOBJ); } UniValue operator()(const WitnessUnknown& id) const { return UniValue(UniValue::VOBJ); } }; static UniValue DescribeWalletAddress(const CWallet& wallet, const CTxDestination& dest) { UniValue ret(UniValue::VOBJ); UniValue detail = DescribeAddress(dest); CScript script = GetScriptForDestination(dest); std::unique_ptr<SigningProvider> provider = nullptr; provider = wallet.GetSolvingProvider(script); ret.pushKVs(detail); ret.pushKVs(std::visit(DescribeWalletAddressVisitor(provider.get()), dest)); return ret; } RPCHelpMan getaddressinfo() { return RPCHelpMan{"getaddressinfo", "\nReturn information about the given bitcoin address.\n" "Some of the information will only be present if the address is in the active wallet.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for which to get information."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "address", "The bitcoin address validated."}, {RPCResult::Type::STR_HEX, "scriptPubKey", "The hex-encoded scriptPubKey generated by the address."}, {RPCResult::Type::BOOL, "ismine", "If the address is yours."}, {RPCResult::Type::BOOL, "iswatchonly", "If the address is watchonly."}, {RPCResult::Type::BOOL, "solvable", "If we know how to spend coins sent to this address, ignoring the possible lack of private keys."}, {RPCResult::Type::STR, "desc", /*optional=*/true, "A descriptor for spending coins sent to this address (only when solvable)."}, {RPCResult::Type::STR, "parent_desc", /*optional=*/true, "The descriptor used to derive this address if this is a descriptor wallet"}, {RPCResult::Type::BOOL, "isscript", "If the key is a script."}, {RPCResult::Type::BOOL, "ischange", "If the address was used for change output."}, {RPCResult::Type::BOOL, "iswitness", "If the address is a witness address."}, {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program."}, {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program."}, {RPCResult::Type::STR, "script", /*optional=*/true, "The output script type. Only if isscript is true and the redeemscript is known. Possible\n" "types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash,\n" "witness_v0_scripthash, witness_unknown."}, {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The redeemscript for the p2sh address."}, {RPCResult::Type::ARR, "pubkeys", /*optional=*/true, "Array of pubkeys associated with the known redeemscript (only if script is multisig).", { {RPCResult::Type::STR, "pubkey", ""}, }}, {RPCResult::Type::NUM, "sigsrequired", /*optional=*/true, "The number of signatures required to spend multisig output (only if script is multisig)."}, {RPCResult::Type::STR_HEX, "pubkey", /*optional=*/true, "The hex value of the raw public key for single-key addresses (possibly embedded in P2SH or P2WSH)."}, {RPCResult::Type::OBJ, "embedded", /*optional=*/true, "Information about the address embedded in P2SH or P2WSH, if relevant and known.", { {RPCResult::Type::ELISION, "", "Includes all getaddressinfo output fields for the embedded address, excluding metadata (timestamp, hdkeypath, hdseedid)\n" "and relation to the wallet (ismine, iswatchonly)."}, }}, {RPCResult::Type::BOOL, "iscompressed", /*optional=*/true, "If the pubkey is compressed."}, {RPCResult::Type::NUM_TIME, "timestamp", /*optional=*/true, "The creation time of the key, if available, expressed in " + UNIX_EPOCH_TIME + "."}, {RPCResult::Type::STR, "hdkeypath", /*optional=*/true, "The HD keypath, if the key is HD and available."}, {RPCResult::Type::STR_HEX, "hdseedid", /*optional=*/true, "The Hash160 of the HD seed."}, {RPCResult::Type::STR_HEX, "hdmasterfingerprint", /*optional=*/true, "The fingerprint of the master key."}, {RPCResult::Type::ARR, "labels", "Array of labels associated with the address. Currently limited to one label but returned\n" "as an array to keep the API stable if multiple labels are enabled in the future.", { {RPCResult::Type::STR, "label name", "Label name (defaults to \"\")."}, }}, } }, RPCExamples{ HelpExampleCli("getaddressinfo", "\"" + EXAMPLE_ADDRESS[0] + "\"") + HelpExampleRpc("getaddressinfo", "\"" + EXAMPLE_ADDRESS[0] + "\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); std::string error_msg; CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg); // Make sure the destination is valid if (!IsValidDestination(dest)) { // Set generic error message in case 'DecodeDestination' didn't set it if (error_msg.empty()) error_msg = "Invalid address"; throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error_msg); } UniValue ret(UniValue::VOBJ); std::string currentAddress = EncodeDestination(dest); ret.pushKV("address", currentAddress); CScript scriptPubKey = GetScriptForDestination(dest); ret.pushKV("scriptPubKey", HexStr(scriptPubKey)); std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey); isminetype mine = pwallet->IsMine(dest); ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE)); if (provider) { auto inferred = InferDescriptor(scriptPubKey, *provider); bool solvable = inferred->IsSolvable(); ret.pushKV("solvable", solvable); if (solvable) { ret.pushKV("desc", inferred->ToString()); } } else { ret.pushKV("solvable", false); } const auto& spk_mans = pwallet->GetScriptPubKeyMans(scriptPubKey); // In most cases there is only one matching ScriptPubKey manager and we can't resolve ambiguity in a better way ScriptPubKeyMan* spk_man{nullptr}; if (spk_mans.size()) spk_man = *spk_mans.begin(); DescriptorScriptPubKeyMan* desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man); if (desc_spk_man) { std::string desc_str; if (desc_spk_man->GetDescriptorString(desc_str, /*priv=*/false)) { ret.pushKV("parent_desc", desc_str); } } ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY)); UniValue detail = DescribeWalletAddress(*pwallet, dest); ret.pushKVs(detail); ret.pushKV("ischange", ScriptIsChange(*pwallet, scriptPubKey)); if (spk_man) { if (const std::unique_ptr<CKeyMetadata> meta = spk_man->GetMetadata(dest)) { ret.pushKV("timestamp", meta->nCreateTime); if (meta->has_key_origin) { // In legacy wallets hdkeypath has always used an apostrophe for // hardened derivation. Perhaps some external tool depends on that. ret.pushKV("hdkeypath", WriteHDKeypath(meta->key_origin.path, /*apostrophe=*/!desc_spk_man)); ret.pushKV("hdseedid", meta->hd_seed_id.GetHex()); ret.pushKV("hdmasterfingerprint", HexStr(meta->key_origin.fingerprint)); } } } // Return a `labels` array containing the label associated with the address, // equivalent to the `label` field above. Currently only one label can be // associated with an address, but we return an array so the API remains // stable if we allow multiple labels to be associated with an address in // the future. UniValue labels(UniValue::VARR); const auto* address_book_entry = pwallet->FindAddressBookEntry(dest); if (address_book_entry) { labels.push_back(address_book_entry->GetLabel()); } ret.pushKV("labels", std::move(labels)); return ret; }, }; } RPCHelpMan getaddressesbylabel() { return RPCHelpMan{"getaddressesbylabel", "\nReturns the list of addresses assigned the specified label.\n", { {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label."}, }, RPCResult{ RPCResult::Type::OBJ_DYN, "", "json object with addresses as keys", { {RPCResult::Type::OBJ, "address", "json object with information about address", { {RPCResult::Type::STR, "purpose", "Purpose of address (\"send\" for sending address, \"receive\" for receiving address)"}, }}, } }, RPCExamples{ HelpExampleCli("getaddressesbylabel", "\"tabby\"") + HelpExampleRpc("getaddressesbylabel", "\"tabby\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); const std::string label{LabelFromValue(request.params[0])}; // Find all addresses that have the given label UniValue ret(UniValue::VOBJ); std::set<std::string> addresses; pwallet->ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label, bool _is_change, const std::optional<AddressPurpose>& _purpose) { if (_is_change) return; if (_label == label) { std::string address = EncodeDestination(_dest); // CWallet::m_address_book is not expected to contain duplicate // address strings, but build a separate set as a precaution just in // case it does. bool unique = addresses.emplace(address).second; CHECK_NONFATAL(unique); // UniValue::pushKV checks if the key exists in O(N) // and since duplicate addresses are unexpected (checked with // std::set in O(log(N))), UniValue::pushKVEnd is used instead, // which currently is O(1). UniValue value(UniValue::VOBJ); value.pushKV("purpose", _purpose ? PurposeToString(*_purpose) : "unknown"); ret.pushKVEnd(address, value); } }); if (ret.empty()) { throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, std::string("No addresses with label " + label)); } return ret; }, }; } RPCHelpMan listlabels() { return RPCHelpMan{"listlabels", "\nReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.\n", { {"purpose", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Address purpose to list labels for ('send','receive'). An empty string is the same as not providing this argument."}, }, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::STR, "label", "Label name"}, } }, RPCExamples{ "\nList all labels\n" + HelpExampleCli("listlabels", "") + "\nList labels that have receiving addresses\n" + HelpExampleCli("listlabels", "receive") + "\nList labels that have sending addresses\n" + HelpExampleCli("listlabels", "send") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("listlabels", "receive") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); std::optional<AddressPurpose> purpose; if (!request.params[0].isNull()) { std::string purpose_str = request.params[0].get_str(); if (!purpose_str.empty()) { purpose = PurposeFromString(purpose_str); if (!purpose) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid 'purpose' argument, must be a known purpose string, typically 'send', or 'receive'."); } } } // Add to a set to sort by label name, then insert into Univalue array std::set<std::string> label_set = pwallet->ListAddrBookLabels(purpose); UniValue ret(UniValue::VARR); for (const std::string& name : label_set) { ret.push_back(name); } return ret; }, }; } #ifdef ENABLE_EXTERNAL_SIGNER RPCHelpMan walletdisplayaddress() { return RPCHelpMan{ "walletdisplayaddress", "Display address on an external signer for verification.", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "bitcoin address to display"}, }, RPCResult{ RPCResult::Type::OBJ,"","", { {RPCResult::Type::STR, "address", "The address as confirmed by the signer"}, } }, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return UniValue::VNULL; CWallet* const pwallet = wallet.get(); LOCK(pwallet->cs_wallet); CTxDestination dest = DecodeDestination(request.params[0].get_str()); // Make sure the destination is valid if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address"); } if (!pwallet->DisplayAddress(dest)) { throw JSONRPCError(RPC_MISC_ERROR, "Failed to display address"); } UniValue result(UniValue::VOBJ); result.pushKV("address", request.params[0].get_str()); return result; } }; } #endif // ENABLE_EXTERNAL_SIGNER } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/util.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/rpc/util.h> #include <common/url.h> #include <rpc/util.h> #include <util/any.h> #include <util/translation.h> #include <wallet/context.h> #include <wallet/wallet.h> #include <univalue.h> #include <boost/date_time/posix_time/posix_time.hpp> namespace wallet { static const std::string WALLET_ENDPOINT_BASE = "/wallet/"; const std::string HELP_REQUIRING_PASSPHRASE{"\nRequires wallet passphrase to be set with walletpassphrase call if wallet is encrypted.\n"}; int64_t ParseISO8601DateTime(const std::string& str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time() || epoch > ptime) return 0; return (ptime - epoch).total_seconds(); } bool GetAvoidReuseFlag(const CWallet& wallet, const UniValue& param) { bool can_avoid_reuse = wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE); bool avoid_reuse = param.isNull() ? can_avoid_reuse : param.get_bool(); if (avoid_reuse && !can_avoid_reuse) { throw JSONRPCError(RPC_WALLET_ERROR, "wallet does not have the \"avoid reuse\" feature enabled"); } return avoid_reuse; } /** Used by RPC commands that have an include_watchonly parameter. * We default to true for watchonly wallets if include_watchonly isn't * explicitly set. */ bool ParseIncludeWatchonly(const UniValue& include_watchonly, const CWallet& wallet) { if (include_watchonly.isNull()) { // if include_watchonly isn't explicitly set, then check if we have a watchonly wallet return wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); } // otherwise return whatever include_watchonly was set to return include_watchonly.get_bool(); } bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest& request, std::string& wallet_name) { if (URL_DECODE && request.URI.substr(0, WALLET_ENDPOINT_BASE.size()) == WALLET_ENDPOINT_BASE) { // wallet endpoint was used wallet_name = URL_DECODE(request.URI.substr(WALLET_ENDPOINT_BASE.size())); return true; } return false; } std::shared_ptr<CWallet> GetWalletForJSONRPCRequest(const JSONRPCRequest& request) { CHECK_NONFATAL(request.mode == JSONRPCRequest::EXECUTE); WalletContext& context = EnsureWalletContext(request.context); std::string wallet_name; if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) { std::shared_ptr<CWallet> pwallet = GetWallet(context, wallet_name); if (!pwallet) throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded"); return pwallet; } size_t count{0}; auto wallet = GetDefaultWallet(context, count); if (wallet) return wallet; if (count == 0) { throw JSONRPCError( RPC_WALLET_NOT_FOUND, "No wallet is loaded. Load a wallet using loadwallet or create a new one with createwallet. (Note: A default wallet is no longer automatically created)"); } throw JSONRPCError(RPC_WALLET_NOT_SPECIFIED, "Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path)."); } void EnsureWalletIsUnlocked(const CWallet& wallet) { if (wallet.IsLocked()) { throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } } WalletContext& EnsureWalletContext(const std::any& context) { auto wallet_context = util::AnyPtr<WalletContext>(context); if (!wallet_context) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Wallet context not found"); } return *wallet_context; } // also_create should only be set to true only when the RPC is expected to add things to a blank wallet and make it no longer blank LegacyScriptPubKeyMan& EnsureLegacyScriptPubKeyMan(CWallet& wallet, bool also_create) { LegacyScriptPubKeyMan* spk_man = wallet.GetLegacyScriptPubKeyMan(); if (!spk_man && also_create) { spk_man = wallet.GetOrCreateLegacyScriptPubKeyMan(); } if (!spk_man) { throw JSONRPCError(RPC_WALLET_ERROR, "Only legacy wallets are supported by this command"); } return *spk_man; } const LegacyScriptPubKeyMan& EnsureConstLegacyScriptPubKeyMan(const CWallet& wallet) { const LegacyScriptPubKeyMan* spk_man = wallet.GetLegacyScriptPubKeyMan(); if (!spk_man) { throw JSONRPCError(RPC_WALLET_ERROR, "Only legacy wallets are supported by this command"); } return *spk_man; } std::string LabelFromValue(const UniValue& value) { static const std::string empty_string; if (value.isNull()) return empty_string; const std::string& label{value.get_str()}; if (label == "*") throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, "Invalid label name"); return label; } void PushParentDescriptors(const CWallet& wallet, const CScript& script_pubkey, UniValue& entry) { UniValue parent_descs(UniValue::VARR); for (const auto& desc: wallet.GetWalletDescriptors(script_pubkey)) { parent_descs.push_back(desc.descriptor->ToString()); } entry.pushKV("parent_descs", parent_descs); } void HandleWalletError(const std::shared_ptr<CWallet> wallet, DatabaseStatus& status, bilingual_str& error) { if (!wallet) { // Map bad format to not found, since bad format is returned when the // wallet directory exists, but doesn't contain a data file. RPCErrorCode code = RPC_WALLET_ERROR; switch (status) { case DatabaseStatus::FAILED_NOT_FOUND: case DatabaseStatus::FAILED_BAD_FORMAT: code = RPC_WALLET_NOT_FOUND; break; case DatabaseStatus::FAILED_ALREADY_LOADED: code = RPC_WALLET_ALREADY_LOADED; break; case DatabaseStatus::FAILED_ALREADY_EXISTS: code = RPC_WALLET_ALREADY_EXISTS; break; case DatabaseStatus::FAILED_INVALID_BACKUP_FILE: code = RPC_INVALID_PARAMETER; break; default: // RPC_WALLET_ERROR is returned for all other cases. break; } throw JSONRPCError(code, error.original); } } void AppendLastProcessedBlock(UniValue& entry, const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { AssertLockHeld(wallet.cs_wallet); UniValue lastprocessedblock{UniValue::VOBJ}; lastprocessedblock.pushKV("hash", wallet.GetLastBlockHash().GetHex()); lastprocessedblock.pushKV("height", wallet.GetLastBlockHeight()); entry.pushKV("lastprocessedblock", lastprocessedblock); } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/encrypt.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/util.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> namespace wallet { RPCHelpMan walletpassphrase() { return RPCHelpMan{"walletpassphrase", "\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "This is needed prior to performing transactions related to private keys such as sending bitcoins\n" "\nNote:\n" "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n" "time that overrides the old one.\n", { {"passphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet passphrase"}, {"timeout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The time to keep the decryption key in seconds; capped at 100000000 (~3 years)."}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nUnlock the wallet for 60 seconds\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") + "\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return UniValue::VNULL; CWallet* const pwallet = wallet.get(); int64_t nSleepTime; int64_t relock_time; // Prevent concurrent calls to walletpassphrase with the same wallet. LOCK(pwallet->m_unlock_mutex); { LOCK(pwallet->cs_wallet); if (!pwallet->IsCrypted()) { throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); } // Note that the walletpassphrase is stored in request.params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = std::string_view{request.params[0].get_str()}; // Get the timeout nSleepTime = request.params[1].getInt<int64_t>(); // Timeout cannot be negative, otherwise it will relock immediately if (nSleepTime < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Timeout cannot be negative."); } // Clamp timeout constexpr int64_t MAX_SLEEP_TIME = 100000000; // larger values trigger a macos/libevent bug? if (nSleepTime > MAX_SLEEP_TIME) { nSleepTime = MAX_SLEEP_TIME; } if (strWalletPass.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "passphrase cannot be empty"); } if (!pwallet->Unlock(strWalletPass)) { // Check if the passphrase has a null character (see #27067 for details) if (strWalletPass.find('\0') == std::string::npos) { throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else { throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered is incorrect. " "It contains a null character (ie - a zero byte). " "If the passphrase was set with a version of this software prior to 25.0, " "please try again with only the characters up to — but not including — " "the first null character. If this is successful, please set a new " "passphrase to avoid this issue in the future."); } } pwallet->TopUpKeyPool(); pwallet->nRelockTime = GetTime() + nSleepTime; relock_time = pwallet->nRelockTime; } // rpcRunLater must be called without cs_wallet held otherwise a deadlock // can occur. The deadlock would happen when RPCRunLater removes the // previous timer (and waits for the callback to finish if already running) // and the callback locks cs_wallet. AssertLockNotHeld(wallet->cs_wallet); // Keep a weak pointer to the wallet so that it is possible to unload the // wallet before the following callback is called. If a valid shared pointer // is acquired in the callback then the wallet is still loaded. std::weak_ptr<CWallet> weak_wallet = wallet; pwallet->chain().rpcRunLater(strprintf("lockwallet(%s)", pwallet->GetName()), [weak_wallet, relock_time] { if (auto shared_wallet = weak_wallet.lock()) { LOCK2(shared_wallet->m_relock_mutex, shared_wallet->cs_wallet); // Skip if this is not the most recent rpcRunLater callback. if (shared_wallet->nRelockTime != relock_time) return; shared_wallet->Lock(); shared_wallet->nRelockTime = 0; } }, nSleepTime); return UniValue::VNULL; }, }; } RPCHelpMan walletpassphrasechange() { return RPCHelpMan{"walletpassphrasechange", "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n", { {"oldpassphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The current passphrase"}, {"newpassphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The new passphrase"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (!pwallet->IsCrypted()) { throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); } if (pwallet->IsScanningWithPassphrase()) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: the wallet is currently being used to rescan the blockchain for related transactions. Please call `abortrescan` before changing the passphrase."); } LOCK2(pwallet->m_relock_mutex, pwallet->cs_wallet); SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = std::string_view{request.params[0].get_str()}; SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = std::string_view{request.params[1].get_str()}; if (strOldWalletPass.empty() || strNewWalletPass.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "passphrase cannot be empty"); } if (!pwallet->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) { // Check if the old passphrase had a null character (see #27067 for details) if (strOldWalletPass.find('\0') == std::string::npos) { throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else { throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The old wallet passphrase entered is incorrect. " "It contains a null character (ie - a zero byte). " "If the old passphrase was set with a version of this software prior to 25.0, " "please try again with only the characters up to — but not including — " "the first null character."); } } return UniValue::VNULL; }, }; } RPCHelpMan walletlock() { return RPCHelpMan{"walletlock", "\nRemoves the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked.\n", {}, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nSet the passphrase for 2 minutes to perform a transaction\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") + "\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 1.0") + "\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("walletlock", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (!pwallet->IsCrypted()) { throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); } if (pwallet->IsScanningWithPassphrase()) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: the wallet is currently being used to rescan the blockchain for related transactions. Please call `abortrescan` before locking the wallet."); } LOCK2(pwallet->m_relock_mutex, pwallet->cs_wallet); pwallet->Lock(); pwallet->nRelockTime = 0; return UniValue::VNULL; }, }; } RPCHelpMan encryptwallet() { return RPCHelpMan{"encryptwallet", "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "After this, any calls that interact with private keys such as sending or signing \n" "will require the passphrase to be set prior the making these calls.\n" "Use the walletpassphrase call for this, and then walletlock call.\n" "If the wallet is already encrypted, use the walletpassphrasechange call.\n" "** IMPORTANT **\n" "For security reasons, the encryption process will generate a new HD seed, resulting\n" "in the creation of a fresh set of active descriptors. Therefore, it is crucial to\n" "securely back up the newly generated wallet file using the backupwallet RPC.\n", { {"passphrase", RPCArg::Type::STR, RPCArg::Optional::NO, "The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long."}, }, RPCResult{RPCResult::Type::STR, "", "A string with further instructions"}, RPCExamples{ "\nEncrypt your wallet\n" + HelpExampleCli("encryptwallet", "\"my pass phrase\"") + "\nNow set the passphrase to use the wallet, such as for signing or sending bitcoin\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") + "\nNow we can do something like sign\n" + HelpExampleCli("signmessage", "\"address\" \"test message\"") + "\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: wallet does not contain private keys, nothing to encrypt."); } if (pwallet->IsCrypted()) { throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); } if (pwallet->IsScanningWithPassphrase()) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: the wallet is currently being used to rescan the blockchain for related transactions. Please call `abortrescan` before encrypting the wallet."); } LOCK2(pwallet->m_relock_mutex, pwallet->cs_wallet); SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = std::string_view{request.params[0].get_str()}; if (strWalletPass.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "passphrase cannot be empty"); } if (!pwallet->EncryptWallet(strWalletPass)) { throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); } return "wallet encrypted; The keypool has been flushed and a new HD seed was generated. You need to make a new backup with the backupwallet RPC."; }, }; } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/coins.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <hash.h> #include <key_io.h> #include <rpc/util.h> #include <script/script.h> #include <util/moneystr.h> #include <wallet/coincontrol.h> #include <wallet/receive.h> #include <wallet/rpc/util.h> #include <wallet/spend.h> #include <wallet/wallet.h> #include <univalue.h> namespace wallet { static CAmount GetReceived(const CWallet& wallet, const UniValue& params, bool by_label) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { std::vector<CTxDestination> addresses; if (by_label) { // Get the set of addresses assigned to label addresses = wallet.ListAddrBookAddresses(CWallet::AddrBookFilter{LabelFromValue(params[0])}); if (addresses.empty()) throw JSONRPCError(RPC_WALLET_ERROR, "Label not found in wallet"); } else { // Get the address CTxDestination dest = DecodeDestination(params[0].get_str()); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); } addresses.emplace_back(dest); } // Filter by own scripts only std::set<CScript> output_scripts; for (const auto& address : addresses) { auto output_script{GetScriptForDestination(address)}; if (wallet.IsMine(output_script)) { output_scripts.insert(output_script); } } if (output_scripts.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Address not found in wallet"); } // Minimum confirmations int min_depth = 1; if (!params[1].isNull()) min_depth = params[1].getInt<int>(); const bool include_immature_coinbase{params[2].isNull() ? false : params[2].get_bool()}; // Tally CAmount amount = 0; for (const std::pair<const uint256, CWalletTx>& wtx_pair : wallet.mapWallet) { const CWalletTx& wtx = wtx_pair.second; int depth{wallet.GetTxDepthInMainChain(wtx)}; if (depth < min_depth // Coinbase with less than 1 confirmation is no longer in the main chain || (wtx.IsCoinBase() && (depth < 1)) || (wallet.IsTxImmatureCoinBase(wtx) && !include_immature_coinbase)) { continue; } for (const CTxOut& txout : wtx.tx->vout) { if (output_scripts.count(txout.scriptPubKey) > 0) { amount += txout.nValue; } } } return amount; } RPCHelpMan getreceivedbyaddress() { return RPCHelpMan{"getreceivedbyaddress", "\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for transactions."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "Only include transactions confirmed at least this many times."}, {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."}, }, RPCResult{ RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received at this address." }, RPCExamples{ "\nThe amount from transactions with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") + "\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0") + "\nThe amount with at least 6 confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 6") + "\nThe amount with at least 6 confirmations including immature coinbase outputs\n" + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 6 true") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\", 6") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); return ValueFromAmount(GetReceived(*pwallet, request.params, /*by_label=*/false)); }, }; } RPCHelpMan getreceivedbylabel() { return RPCHelpMan{"getreceivedbylabel", "\nReturns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.\n", { {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The selected label, may be the default label using \"\"."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "Only include transactions confirmed at least this many times."}, {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."}, }, RPCResult{ RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received for this label." }, RPCExamples{ "\nAmount received by the default label with at least 1 confirmation\n" + HelpExampleCli("getreceivedbylabel", "\"\"") + "\nAmount received at the tabby label including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbylabel", "\"tabby\" 0") + "\nThe amount with at least 6 confirmations\n" + HelpExampleCli("getreceivedbylabel", "\"tabby\" 6") + "\nThe amount with at least 6 confirmations including immature coinbase outputs\n" + HelpExampleCli("getreceivedbylabel", "\"tabby\" 6 true") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("getreceivedbylabel", "\"tabby\", 6, true") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); return ValueFromAmount(GetReceived(*pwallet, request.params, /*by_label=*/true)); }, }; } RPCHelpMan getbalance() { return RPCHelpMan{"getbalance", "\nReturns the total available balance.\n" "The available balance is what the wallet considers currently spendable, and is\n" "thus affected by options which limit spendability such as -spendzeroconfchange.\n", { {"dummy", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Remains for backward compatibility. Must be excluded or set to \"*\"."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "Only include transactions confirmed at least this many times."}, {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also include balance in watch-only addresses (see 'importaddress')"}, {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{true}, "(only available if avoid_reuse wallet flag is set) Do not include balance in dirty outputs; addresses are considered dirty if they have previously been used in a transaction."}, }, RPCResult{ RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received for this wallet." }, RPCExamples{ "\nThe total amount in the wallet with 0 or more confirmations\n" + HelpExampleCli("getbalance", "") + "\nThe total amount in the wallet with at least 6 confirmations\n" + HelpExampleCli("getbalance", "\"*\" 6") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("getbalance", "\"*\", 6") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); const auto dummy_value{self.MaybeArg<std::string>(0)}; if (dummy_value && *dummy_value != "*") { throw JSONRPCError(RPC_METHOD_DEPRECATED, "dummy first argument must be excluded or set to \"*\"."); } int min_depth = 0; if (!request.params[1].isNull()) { min_depth = request.params[1].getInt<int>(); } bool include_watchonly = ParseIncludeWatchonly(request.params[2], *pwallet); bool avoid_reuse = GetAvoidReuseFlag(*pwallet, request.params[3]); const auto bal = GetBalance(*pwallet, min_depth, avoid_reuse); return ValueFromAmount(bal.m_mine_trusted + (include_watchonly ? bal.m_watchonly_trusted : 0)); }, }; } RPCHelpMan getunconfirmedbalance() { return RPCHelpMan{"getunconfirmedbalance", "DEPRECATED\nIdentical to getbalances().mine.untrusted_pending\n", {}, RPCResult{RPCResult::Type::NUM, "", "The balance"}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); return ValueFromAmount(GetBalance(*pwallet).m_mine_untrusted_pending); }, }; } RPCHelpMan lockunspent() { return RPCHelpMan{"lockunspent", "\nUpdates list of temporarily unspendable outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" "If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n" "A locked transaction output will not be chosen by automatic coin selection, when spending bitcoins.\n" "Manually selected coins are automatically unlocked.\n" "Locks are stored in memory only, unless persistent=true, in which case they will be written to the\n" "wallet database and loaded on node start. Unwritten (persistent=false) locks are always cleared\n" "(by virtue of process exit) when a node stops or fails. Unlocking will clear both persistent and not.\n" "Also see the listunspent call\n", { {"unlock", RPCArg::Type::BOOL, RPCArg::Optional::NO, "Whether to unlock (true) or lock (false) the specified transactions"}, {"transactions", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The transaction outputs and within each, the txid (string) vout (numeric).", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, }, }, }, }, {"persistent", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to write/erase this lock in the wallet database, or keep the change in memory only. Ignored for unlocking."}, }, RPCResult{ RPCResult::Type::BOOL, "", "Whether the command was successful or not" }, RPCExamples{ "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nLock the transaction persistently in the wallet database\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\" true") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); bool fUnlock = request.params[0].get_bool(); const bool persistent{request.params[2].isNull() ? false : request.params[2].get_bool()}; if (request.params[1].isNull()) { if (fUnlock) { if (!pwallet->UnlockAllCoins()) throw JSONRPCError(RPC_WALLET_ERROR, "Unlocking coins failed"); } return true; } const UniValue& output_params = request.params[1].get_array(); // Create and validate the COutPoints first. std::vector<COutPoint> outputs; outputs.reserve(output_params.size()); for (unsigned int idx = 0; idx < output_params.size(); idx++) { const UniValue& o = output_params[idx].get_obj(); RPCTypeCheckObj(o, { {"txid", UniValueType(UniValue::VSTR)}, {"vout", UniValueType(UniValue::VNUM)}, }); const Txid txid = Txid::FromUint256(ParseHashO(o, "txid")); const int nOutput = o.find_value("vout").getInt<int>(); if (nOutput < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative"); } const COutPoint outpt(txid, nOutput); const auto it = pwallet->mapWallet.find(outpt.hash); if (it == pwallet->mapWallet.end()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, unknown transaction"); } const CWalletTx& trans = it->second; if (outpt.n >= trans.tx->vout.size()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout index out of bounds"); } if (pwallet->IsSpent(outpt)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected unspent output"); } const bool is_locked = pwallet->IsLockedCoin(outpt); if (fUnlock && !is_locked) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected locked output"); } if (!fUnlock && is_locked && !persistent) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output already locked"); } outputs.push_back(outpt); } std::unique_ptr<WalletBatch> batch = nullptr; // Unlock is always persistent if (fUnlock || persistent) batch = std::make_unique<WalletBatch>(pwallet->GetDatabase()); // Atomically set (un)locked status for the outputs. for (const COutPoint& outpt : outputs) { if (fUnlock) { if (!pwallet->UnlockCoin(outpt, batch.get())) throw JSONRPCError(RPC_WALLET_ERROR, "Unlocking coin failed"); } else { if (!pwallet->LockCoin(outpt, batch.get())) throw JSONRPCError(RPC_WALLET_ERROR, "Locking coin failed"); } } return true; }, }; } RPCHelpMan listlockunspent() { return RPCHelpMan{"listlockunspent", "\nReturns list of temporarily unspendable outputs.\n" "See the lockunspent call to lock and unlock transactions for spending.\n", {}, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "txid", "The transaction id locked"}, {RPCResult::Type::NUM, "vout", "The vout value"}, }}, } }, RPCExamples{ "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("listlockunspent", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); std::vector<COutPoint> vOutpts; pwallet->ListLockedCoins(vOutpts); UniValue ret(UniValue::VARR); for (const COutPoint& outpt : vOutpts) { UniValue o(UniValue::VOBJ); o.pushKV("txid", outpt.hash.GetHex()); o.pushKV("vout", (int)outpt.n); ret.push_back(o); } return ret; }, }; } RPCHelpMan getbalances() { return RPCHelpMan{ "getbalances", "Returns an object with all balances in " + CURRENCY_UNIT + ".\n", {}, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::OBJ, "mine", "balances from outputs that the wallet can sign", { {RPCResult::Type::STR_AMOUNT, "trusted", "trusted balance (outputs created by the wallet or confirmed outputs)"}, {RPCResult::Type::STR_AMOUNT, "untrusted_pending", "untrusted pending balance (outputs created by others that are in the mempool)"}, {RPCResult::Type::STR_AMOUNT, "immature", "balance from immature coinbase outputs"}, {RPCResult::Type::STR_AMOUNT, "used", /*optional=*/true, "(only present if avoid_reuse is set) balance from coins sent to addresses that were previously spent from (potentially privacy violating)"}, }}, {RPCResult::Type::OBJ, "watchonly", /*optional=*/true, "watchonly balances (not present if wallet does not watch anything)", { {RPCResult::Type::STR_AMOUNT, "trusted", "trusted balance (outputs created by the wallet or confirmed outputs)"}, {RPCResult::Type::STR_AMOUNT, "untrusted_pending", "untrusted pending balance (outputs created by others that are in the mempool)"}, {RPCResult::Type::STR_AMOUNT, "immature", "balance from immature coinbase outputs"}, }}, RESULT_LAST_PROCESSED_BLOCK, } }, RPCExamples{ HelpExampleCli("getbalances", "") + HelpExampleRpc("getbalances", "")}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> rpc_wallet = GetWalletForJSONRPCRequest(request); if (!rpc_wallet) return UniValue::VNULL; const CWallet& wallet = *rpc_wallet; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); LOCK(wallet.cs_wallet); const auto bal = GetBalance(wallet); UniValue balances{UniValue::VOBJ}; { UniValue balances_mine{UniValue::VOBJ}; balances_mine.pushKV("trusted", ValueFromAmount(bal.m_mine_trusted)); balances_mine.pushKV("untrusted_pending", ValueFromAmount(bal.m_mine_untrusted_pending)); balances_mine.pushKV("immature", ValueFromAmount(bal.m_mine_immature)); if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) { // If the AVOID_REUSE flag is set, bal has been set to just the un-reused address balance. Get // the total balance, and then subtract bal to get the reused address balance. const auto full_bal = GetBalance(wallet, 0, false); balances_mine.pushKV("used", ValueFromAmount(full_bal.m_mine_trusted + full_bal.m_mine_untrusted_pending - bal.m_mine_trusted - bal.m_mine_untrusted_pending)); } balances.pushKV("mine", balances_mine); } auto spk_man = wallet.GetLegacyScriptPubKeyMan(); if (spk_man && spk_man->HaveWatchOnly()) { UniValue balances_watchonly{UniValue::VOBJ}; balances_watchonly.pushKV("trusted", ValueFromAmount(bal.m_watchonly_trusted)); balances_watchonly.pushKV("untrusted_pending", ValueFromAmount(bal.m_watchonly_untrusted_pending)); balances_watchonly.pushKV("immature", ValueFromAmount(bal.m_watchonly_immature)); balances.pushKV("watchonly", balances_watchonly); } AppendLastProcessedBlock(balances, wallet); return balances; }, }; } RPCHelpMan listunspent() { return RPCHelpMan{ "listunspent", "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n", { {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "The minimum confirmations to filter"}, {"maxconf", RPCArg::Type::NUM, RPCArg::Default{9999999}, "The maximum confirmations to filter"}, {"addresses", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The bitcoin addresses to filter", { {"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "bitcoin address"}, }, }, {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include outputs that are not safe to spend\n" "See description of \"safe\" attribute below."}, {"query_options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", { {"minimumAmount", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(0)}, "Minimum value of each UTXO in " + CURRENCY_UNIT + ""}, {"maximumAmount", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"unlimited"}, "Maximum value of each UTXO in " + CURRENCY_UNIT + ""}, {"maximumCount", RPCArg::Type::NUM, RPCArg::DefaultHint{"unlimited"}, "Maximum number of UTXOs"}, {"minimumSumAmount", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"unlimited"}, "Minimum sum value of all UTXOs in " + CURRENCY_UNIT + ""}, {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase UTXOs"} }, RPCArgOptions{.oneline_description="query_options"}}, }, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "txid", "the transaction id"}, {RPCResult::Type::NUM, "vout", "the vout value"}, {RPCResult::Type::STR, "address", /*optional=*/true, "the bitcoin address"}, {RPCResult::Type::STR, "label", /*optional=*/true, "The associated label, or \"\" for the default label"}, {RPCResult::Type::STR, "scriptPubKey", "the script key"}, {RPCResult::Type::STR_AMOUNT, "amount", "the transaction output amount in " + CURRENCY_UNIT}, {RPCResult::Type::NUM, "confirmations", "The number of confirmations"}, {RPCResult::Type::NUM, "ancestorcount", /*optional=*/true, "The number of in-mempool ancestor transactions, including this one (if transaction is in the mempool)"}, {RPCResult::Type::NUM, "ancestorsize", /*optional=*/true, "The virtual transaction size of in-mempool ancestors, including this one (if transaction is in the mempool)"}, {RPCResult::Type::STR_AMOUNT, "ancestorfees", /*optional=*/true, "The total fees of in-mempool ancestors (including this one) with fee deltas used for mining priority in " + CURRENCY_ATOM + " (if transaction is in the mempool)"}, {RPCResult::Type::STR_HEX, "redeemScript", /*optional=*/true, "The redeemScript if scriptPubKey is P2SH"}, {RPCResult::Type::STR, "witnessScript", /*optional=*/true, "witnessScript if the scriptPubKey is P2WSH or P2SH-P2WSH"}, {RPCResult::Type::BOOL, "spendable", "Whether we have the private keys to spend this output"}, {RPCResult::Type::BOOL, "solvable", "Whether we know how to spend this output, ignoring the lack of keys"}, {RPCResult::Type::BOOL, "reused", /*optional=*/true, "(only present if avoid_reuse is set) Whether this output is reused/dirty (sent to an address that was previously spent from)"}, {RPCResult::Type::STR, "desc", /*optional=*/true, "(only when solvable) A descriptor for spending this output"}, {RPCResult::Type::ARR, "parent_descs", /*optional=*/false, "List of parent descriptors for the scriptPubKey of this coin.", { {RPCResult::Type::STR, "desc", "The descriptor string."}, }}, {RPCResult::Type::BOOL, "safe", "Whether this output is considered safe to spend. Unconfirmed transactions\n" "from outside keys and unconfirmed replacement transactions are considered unsafe\n" "and are not eligible for spending by fundrawtransaction and sendtoaddress."}, }}, } }, RPCExamples{ HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") + HelpExampleCli("listunspent", "6 9999999 '[]' true '{ \"minimumAmount\": 0.005 }'") + HelpExampleRpc("listunspent", "6, 9999999, [] , true, { \"minimumAmount\": 0.005 } ") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; int nMinDepth = 1; if (!request.params[0].isNull()) { nMinDepth = request.params[0].getInt<int>(); } int nMaxDepth = 9999999; if (!request.params[1].isNull()) { nMaxDepth = request.params[1].getInt<int>(); } std::set<CTxDestination> destinations; if (!request.params[2].isNull()) { UniValue inputs = request.params[2].get_array(); for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; CTxDestination dest = DecodeDestination(input.get_str()); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + input.get_str()); } if (!destinations.insert(dest).second) { throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str()); } } } bool include_unsafe = true; if (!request.params[3].isNull()) { include_unsafe = request.params[3].get_bool(); } CoinFilterParams filter_coins; filter_coins.min_amount = 0; if (!request.params[4].isNull()) { const UniValue& options = request.params[4].get_obj(); RPCTypeCheckObj(options, { {"minimumAmount", UniValueType()}, {"maximumAmount", UniValueType()}, {"minimumSumAmount", UniValueType()}, {"maximumCount", UniValueType(UniValue::VNUM)}, {"include_immature_coinbase", UniValueType(UniValue::VBOOL)} }, true, true); if (options.exists("minimumAmount")) filter_coins.min_amount = AmountFromValue(options["minimumAmount"]); if (options.exists("maximumAmount")) filter_coins.max_amount = AmountFromValue(options["maximumAmount"]); if (options.exists("minimumSumAmount")) filter_coins.min_sum_amount = AmountFromValue(options["minimumSumAmount"]); if (options.exists("maximumCount")) filter_coins.max_count = options["maximumCount"].getInt<int64_t>(); if (options.exists("include_immature_coinbase")) { filter_coins.include_immature_coinbase = options["include_immature_coinbase"].get_bool(); } } // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); UniValue results(UniValue::VARR); std::vector<COutput> vecOutputs; { CCoinControl cctl; cctl.m_avoid_address_reuse = false; cctl.m_min_depth = nMinDepth; cctl.m_max_depth = nMaxDepth; cctl.m_include_unsafe_inputs = include_unsafe; LOCK(pwallet->cs_wallet); vecOutputs = AvailableCoinsListUnspent(*pwallet, &cctl, filter_coins).All(); } LOCK(pwallet->cs_wallet); const bool avoid_reuse = pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE); for (const COutput& out : vecOutputs) { CTxDestination address; const CScript& scriptPubKey = out.txout.scriptPubKey; bool fValidAddress = ExtractDestination(scriptPubKey, address); bool reused = avoid_reuse && pwallet->IsSpentKey(scriptPubKey); if (destinations.size() && (!fValidAddress || !destinations.count(address))) continue; UniValue entry(UniValue::VOBJ); entry.pushKV("txid", out.outpoint.hash.GetHex()); entry.pushKV("vout", (int)out.outpoint.n); if (fValidAddress) { entry.pushKV("address", EncodeDestination(address)); const auto* address_book_entry = pwallet->FindAddressBookEntry(address); if (address_book_entry) { entry.pushKV("label", address_book_entry->GetLabel()); } std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey); if (provider) { if (scriptPubKey.IsPayToScriptHash()) { const CScriptID hash = ToScriptID(std::get<ScriptHash>(address)); CScript redeemScript; if (provider->GetCScript(hash, redeemScript)) { entry.pushKV("redeemScript", HexStr(redeemScript)); // Now check if the redeemScript is actually a P2WSH script CTxDestination witness_destination; if (redeemScript.IsPayToWitnessScriptHash()) { bool extracted = ExtractDestination(redeemScript, witness_destination); CHECK_NONFATAL(extracted); // Also return the witness script const WitnessV0ScriptHash& whash = std::get<WitnessV0ScriptHash>(witness_destination); CScriptID id{RIPEMD160(whash)}; CScript witnessScript; if (provider->GetCScript(id, witnessScript)) { entry.pushKV("witnessScript", HexStr(witnessScript)); } } } } else if (scriptPubKey.IsPayToWitnessScriptHash()) { const WitnessV0ScriptHash& whash = std::get<WitnessV0ScriptHash>(address); CScriptID id{RIPEMD160(whash)}; CScript witnessScript; if (provider->GetCScript(id, witnessScript)) { entry.pushKV("witnessScript", HexStr(witnessScript)); } } } } entry.pushKV("scriptPubKey", HexStr(scriptPubKey)); entry.pushKV("amount", ValueFromAmount(out.txout.nValue)); entry.pushKV("confirmations", out.depth); if (!out.depth) { size_t ancestor_count, descendant_count, ancestor_size; CAmount ancestor_fees; pwallet->chain().getTransactionAncestry(out.outpoint.hash, ancestor_count, descendant_count, &ancestor_size, &ancestor_fees); if (ancestor_count) { entry.pushKV("ancestorcount", uint64_t(ancestor_count)); entry.pushKV("ancestorsize", uint64_t(ancestor_size)); entry.pushKV("ancestorfees", uint64_t(ancestor_fees)); } } entry.pushKV("spendable", out.spendable); entry.pushKV("solvable", out.solvable); if (out.solvable) { std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey); if (provider) { auto descriptor = InferDescriptor(scriptPubKey, *provider); entry.pushKV("desc", descriptor->ToString()); } } PushParentDescriptors(*pwallet, scriptPubKey, entry); if (avoid_reuse) entry.pushKV("reused", reused); entry.pushKV("safe", out.safe); results.push_back(entry); } return results; }, }; } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/signmessage.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <key_io.h> #include <rpc/util.h> #include <util/message.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> #include <univalue.h> namespace wallet { RPCHelpMan signmessage() { return RPCHelpMan{"signmessage", "\nSign a message with the private key of an address" + HELP_REQUIRING_PASSPHRASE, { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to use for the private key."}, {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."}, }, RPCResult{ RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64" }, RPCExamples{ "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"my message\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); std::string strAddress = request.params[0].get_str(); std::string strMessage = request.params[1].get_str(); CTxDestination dest = DecodeDestination(strAddress); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address"); } const PKHash* pkhash = std::get_if<PKHash>(&dest); if (!pkhash) { throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); } std::string signature; SigningResult err = pwallet->SignMessage(strMessage, *pkhash, signature); if (err == SigningResult::SIGNING_FAILED) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, SigningResultString(err)); } else if (err != SigningResult::OK) { throw JSONRPCError(RPC_WALLET_ERROR, SigningResultString(err)); } return signature; }, }; } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/backup.cpp
// Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <clientversion.h> #include <core_io.h> #include <hash.h> #include <interfaces/chain.h> #include <key_io.h> #include <merkleblock.h> #include <rpc/util.h> #include <script/descriptor.h> #include <script/script.h> #include <script/solver.h> #include <sync.h> #include <uint256.h> #include <util/bip32.h> #include <util/fs.h> #include <util/time.h> #include <util/translation.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> #include <cstdint> #include <fstream> #include <tuple> #include <string> #include <univalue.h> using interfaces::FoundBlock; namespace wallet { std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; for (const unsigned char c : str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr({&c, 1}); } else { ret << c; } } return ret.str(); } static std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } static bool GetWalletAddressesForKey(const LegacyScriptPubKeyMan* spk_man, const CWallet& wallet, const CKeyID& keyid, std::string& strAddr, std::string& strLabel) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { bool fLabelFound = false; CKey key; spk_man->GetKey(keyid, key); for (const auto& dest : GetAllDestinationsForKey(key.GetPubKey())) { const auto* address_book_entry = wallet.FindAddressBookEntry(dest); if (address_book_entry) { if (!strAddr.empty()) { strAddr += ","; } strAddr += EncodeDestination(dest); strLabel = EncodeDumpString(address_book_entry->GetLabel()); fLabelFound = true; } } if (!fLabelFound) { strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), wallet.m_default_address_type)); } return fLabelFound; } static const int64_t TIMESTAMP_MIN = 0; static void RescanWallet(CWallet& wallet, const WalletRescanReserver& reserver, int64_t time_begin = TIMESTAMP_MIN, bool update = true) { int64_t scanned_time = wallet.RescanFromTime(time_begin, reserver, update); if (wallet.IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } else if (scanned_time > time_begin) { throw JSONRPCError(RPC_WALLET_ERROR, "Rescan was unable to fully rescan the blockchain. Some transactions may be missing."); } } static void EnsureBlockDataFromTime(const CWallet& wallet, int64_t timestamp) { auto& chain{wallet.chain()}; if (!chain.havePruned()) { return; } int height{0}; const bool found{chain.findFirstBlockWithTimeAndHeight(timestamp - TIMESTAMP_WINDOW, 0, FoundBlock().height(height))}; uint256 tip_hash{WITH_LOCK(wallet.cs_wallet, return wallet.GetLastBlockHash())}; if (found && !chain.hasBlocks(tip_hash, height)) { throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Pruned blocks from height %d required to import keys. Use RPC call getblockchaininfo to determine your pruned height.", height)); } } RPCHelpMan importprivkey() { return RPCHelpMan{"importprivkey", "\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n" "Hint: use importmulti to import more than one private key.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported key exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "The rescan parameter can be set to false if the key was never used to create transactions. If it is set to false,\n" "but the key was used to create transactions, rescanblockchain needs to be called with the appropriate block range.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n" "Note: This command is only compatible with legacy wallets. Use \"importdescriptors\" with \"combo(X)\" for descriptor wallets.\n", { {"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key (see dumpprivkey)"}, {"label", RPCArg::Type::STR, RPCArg::DefaultHint{"current label if address exists, otherwise \"\""}, "An optional label"}, {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Scan the chain and mempool for wallet transactions."}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nImport using default blank label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); } EnsureLegacyScriptPubKeyMan(*pwallet, true); WalletRescanReserver reserver(*pwallet); bool fRescan = true; { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); std::string strSecret = request.params[0].get_str(); const std::string strLabel{LabelFromValue(request.params[1])}; // Whether to perform rescan after import if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned"); } if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } CKey key = DecodeSecret(strSecret); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CPubKey pubkey = key.GetPubKey(); CHECK_NONFATAL(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwallet->MarkDirty(); // We don't know which corresponding address will be used; // label all new addresses, and label existing addresses if a // label was passed. for (const auto& dest : GetAllDestinationsForKey(pubkey)) { if (!request.params[1].isNull() || !pwallet->FindAddressBookEntry(dest)) { pwallet->SetAddressBook(dest, strLabel, AddressPurpose::RECEIVE); } } // Use timestamp of 1 to scan the whole chain if (!pwallet->ImportPrivKeys({{vchAddress, key}}, 1)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } // Add the wpkh script for this key if possible if (pubkey.IsCompressed()) { pwallet->ImportScripts({GetScriptForDestination(WitnessV0KeyHash(vchAddress))}, /*timestamp=*/0); } } } if (fRescan) { RescanWallet(*pwallet, reserver); } return UniValue::VNULL; }, }; } RPCHelpMan importaddress() { return RPCHelpMan{"importaddress", "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported address exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "The rescan parameter can be set to false if the key was never used to create transactions. If it is set to false,\n" "but the key was used to create transactions, rescanblockchain needs to be called with the appropriate block range.\n" "If you have the full public key, you should call importpubkey instead of this.\n" "Hint: use importmulti to import more than one address.\n" "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n" "as change, and not show up in many RPCs.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n" "Note: This command is only compatible with legacy wallets. Use \"importdescriptors\" for descriptor wallets.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Bitcoin address (or hex-encoded script)"}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "An optional label"}, {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Scan the chain and mempool for wallet transactions."}, {"p2sh", RPCArg::Type::BOOL, RPCArg::Default{false}, "Add the P2SH version of the script as well"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; EnsureLegacyScriptPubKeyMan(*pwallet, true); const std::string strLabel{LabelFromValue(request.params[1])}; // Whether to perform rescan after import bool fRescan = true; if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned"); } WalletRescanReserver reserver(*pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } // Whether to import a p2sh version, too bool fP2SH = false; if (!request.params[3].isNull()) fP2SH = request.params[3].get_bool(); { LOCK(pwallet->cs_wallet); CTxDestination dest = DecodeDestination(request.params[0].get_str()); if (IsValidDestination(dest)) { if (fP2SH) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead"); } if (OutputTypeFromDestination(dest) == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m addresses cannot be imported into legacy wallets"); } pwallet->MarkDirty(); pwallet->ImportScriptPubKeys(strLabel, {GetScriptForDestination(dest)}, /*have_solving_data=*/false, /*apply_label=*/true, /*timestamp=*/1); } else if (IsHex(request.params[0].get_str())) { std::vector<unsigned char> data(ParseHex(request.params[0].get_str())); CScript redeem_script(data.begin(), data.end()); std::set<CScript> scripts = {redeem_script}; pwallet->ImportScripts(scripts, /*timestamp=*/0); if (fP2SH) { scripts.insert(GetScriptForDestination(ScriptHash(redeem_script))); } pwallet->ImportScriptPubKeys(strLabel, scripts, /*have_solving_data=*/false, /*apply_label=*/true, /*timestamp=*/1); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address or script"); } } if (fRescan) { RescanWallet(*pwallet, reserver); pwallet->ResubmitWalletTransactions(/*relay=*/false, /*force=*/true); } return UniValue::VNULL; }, }; } RPCHelpMan importprunedfunds() { return RPCHelpMan{"importprunedfunds", "\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n", { {"rawtransaction", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A raw transaction in hex funding an already-existing address in wallet"}, {"txoutproof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex output from gettxoutproof that contains the transaction"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; CMutableTransaction tx; if (!DecodeHexTx(tx, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input."); } uint256 hashTx = tx.GetHash(); DataStream ssMB{ParseHexV(request.params[1], "proof")}; CMerkleBlock merkleBlock; ssMB >> merkleBlock; //Search partial merkle tree in proof for our transaction and index in valid block std::vector<uint256> vMatch; std::vector<unsigned int> vIndex; if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock"); } LOCK(pwallet->cs_wallet); int height; if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.header.GetHash(), FoundBlock().height(height))) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } std::vector<uint256>::const_iterator it; if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx)) == vMatch.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof"); } unsigned int txnIndex = vIndex[it - vMatch.begin()]; CTransactionRef tx_ref = MakeTransactionRef(tx); if (pwallet->IsMine(*tx_ref)) { pwallet->AddToWallet(std::move(tx_ref), TxStateConfirmed{merkleBlock.header.GetHash(), height, static_cast<int>(txnIndex)}); return UniValue::VNULL; } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction"); }, }; } RPCHelpMan removeprunedfunds() { return RPCHelpMan{"removeprunedfunds", "\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded id of the transaction you are deleting"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); uint256 hash(ParseHashV(request.params[0], "txid")); std::vector<uint256> vHash; vHash.push_back(hash); std::vector<uint256> vHashOut; if (pwallet->ZapSelectTx(vHash, vHashOut) != DBErrors::LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction."); } if(vHashOut.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet."); } return UniValue::VNULL; }, }; } RPCHelpMan importpubkey() { return RPCHelpMan{"importpubkey", "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "Hint: use importmulti to import more than one public key.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported pubkey exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "The rescan parameter can be set to false if the key was never used to create transactions. If it is set to false,\n" "but the key was used to create transactions, rescanblockchain needs to be called with the appropriate block range.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n" "Note: This command is only compatible with legacy wallets. Use \"importdescriptors\" with \"combo(X)\" for descriptor wallets.\n", { {"pubkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The hex-encoded public key"}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "An optional label"}, {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Scan the chain and mempool for wallet transactions."}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nImport a public key with rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; EnsureLegacyScriptPubKeyMan(*pwallet, true); const std::string strLabel{LabelFromValue(request.params[1])}; // Whether to perform rescan after import bool fRescan = true; if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned"); } WalletRescanReserver reserver(*pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } if (!IsHex(request.params[0].get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string"); std::vector<unsigned char> data(ParseHex(request.params[0].get_str())); CPubKey pubKey(data); if (!pubKey.IsFullyValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key"); { LOCK(pwallet->cs_wallet); std::set<CScript> script_pub_keys; for (const auto& dest : GetAllDestinationsForKey(pubKey)) { script_pub_keys.insert(GetScriptForDestination(dest)); } pwallet->MarkDirty(); pwallet->ImportScriptPubKeys(strLabel, script_pub_keys, /*have_solving_data=*/true, /*apply_label=*/true, /*timestamp=*/1); pwallet->ImportPubKeys({pubKey.GetID()}, {{pubKey.GetID(), pubKey}} , /*key_origins=*/{}, /*add_keypool=*/false, /*internal=*/false, /*timestamp=*/1); } if (fRescan) { RescanWallet(*pwallet, reserver); pwallet->ResubmitWalletTransactions(/*relay=*/false, /*force=*/true); } return UniValue::VNULL; }, }; } RPCHelpMan importwallet() { return RPCHelpMan{"importwallet", "\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n" "Note: Blockchain and Mempool will be rescanned after a successful import. Use \"getwalletinfo\" to query the scanning progress.\n" "Note: This command is only compatible with legacy wallets.\n", { {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet file"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; EnsureLegacyScriptPubKeyMan(*pwallet, true); WalletRescanReserver reserver(*pwallet); if (!reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int64_t nTimeBegin = 0; bool fGood = true; { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); std::ifstream file; file.open(fs::u8path(request.params[0].get_str()), std::ios::in | std::ios::ate); if (!file.is_open()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); } CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(nTimeBegin))); int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); // Use uiInterface.ShowProgress instead of pwallet.ShowProgress because pwallet.ShowProgress has a cancel button tied to AbortRescan which // we don't want for this progress bar showing the import progress. uiInterface.ShowProgress does not have a cancel button. pwallet->chain().showProgress(strprintf("%s " + _("Importing…").translated, pwallet->GetDisplayName()), 0, false); // show progress dialog in GUI std::vector<std::tuple<CKey, int64_t, bool, std::string>> keys; std::vector<std::pair<CScript, int64_t>> scripts; while (file.good()) { pwallet->chain().showProgress("", std::max(1, std::min(50, (int)(((double)file.tellg() / (double)nFilesize) * 100))), false); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr = SplitString(line, ' '); if (vstr.size() < 2) continue; CKey key = DecodeSecret(vstr[0]); if (key.IsValid()) { int64_t nTime = ParseISO8601DateTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (vstr[nStr].front() == '#') break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (vstr[nStr].substr(0,6) == "label=") { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } nTimeBegin = std::min(nTimeBegin, nTime); keys.emplace_back(key, nTime, fLabel, strLabel); } else if(IsHex(vstr[0])) { std::vector<unsigned char> vData(ParseHex(vstr[0])); CScript script = CScript(vData.begin(), vData.end()); int64_t birth_time = ParseISO8601DateTime(vstr[1]); if (birth_time > 0) nTimeBegin = std::min(nTimeBegin, birth_time); scripts.emplace_back(script, birth_time); } } file.close(); EnsureBlockDataFromTime(*pwallet, nTimeBegin); // We now know whether we are importing private keys, so we can error if private keys are disabled if (keys.size() > 0 && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled when private keys are disabled"); } double total = (double)(keys.size() + scripts.size()); double progress = 0; for (const auto& key_tuple : keys) { pwallet->chain().showProgress("", std::max(50, std::min(75, (int)((progress / total) * 100) + 50)), false); const CKey& key = std::get<0>(key_tuple); int64_t time = std::get<1>(key_tuple); bool has_label = std::get<2>(key_tuple); std::string label = std::get<3>(key_tuple); CPubKey pubkey = key.GetPubKey(); CHECK_NONFATAL(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); pwallet->WalletLogPrintf("Importing %s...\n", EncodeDestination(PKHash(keyid))); if (!pwallet->ImportPrivKeys({{keyid, key}}, time)) { pwallet->WalletLogPrintf("Error importing key for %s\n", EncodeDestination(PKHash(keyid))); fGood = false; continue; } if (has_label) pwallet->SetAddressBook(PKHash(keyid), label, AddressPurpose::RECEIVE); progress++; } for (const auto& script_pair : scripts) { pwallet->chain().showProgress("", std::max(50, std::min(75, (int)((progress / total) * 100) + 50)), false); const CScript& script = script_pair.first; int64_t time = script_pair.second; if (!pwallet->ImportScripts({script}, time)) { pwallet->WalletLogPrintf("Error importing script %s\n", HexStr(script)); fGood = false; continue; } progress++; } pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI } pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI RescanWallet(*pwallet, reserver, nTimeBegin, /*update=*/false); pwallet->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys/scripts to wallet"); return UniValue::VNULL; }, }; } RPCHelpMan dumpprivkey() { return RPCHelpMan{"dumpprivkey", "\nReveals the private key corresponding to 'address'.\n" "Then the importprivkey can be used with this output\n" "Note: This command is only compatible with legacy wallets.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for the private key"}, }, RPCResult{ RPCResult::Type::STR, "key", "The private key" }, RPCExamples{ HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; const LegacyScriptPubKeyMan& spk_man = EnsureConstLegacyScriptPubKeyMan(*pwallet); LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore); EnsureWalletIsUnlocked(*pwallet); std::string strAddress = request.params[0].get_str(); CTxDestination dest = DecodeDestination(strAddress); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); } auto keyid = GetKeyForDestination(spk_man, dest); if (keyid.IsNull()) { throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); } CKey vchSecret; if (!spk_man.GetKey(keyid, vchSecret)) { throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); } return EncodeSecret(vchSecret); }, }; } RPCHelpMan dumpwallet() { return RPCHelpMan{"dumpwallet", "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n" "Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\n" "Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\n" "only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n" "Note: This command is only compatible with legacy wallets.\n", { {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The filename with path (absolute path recommended)"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "filename", "The filename with full absolute path"}, } }, RPCExamples{ HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; const CWallet& wallet = *pwallet; const LegacyScriptPubKeyMan& spk_man = EnsureConstLegacyScriptPubKeyMan(wallet); // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); LOCK(wallet.cs_wallet); EnsureWalletIsUnlocked(wallet); fs::path filepath = fs::u8path(request.params[0].get_str()); filepath = fs::absolute(filepath); /* Prevent arbitrary files from being overwritten. There have been reports * that users have overwritten wallet files this way: * https://github.com/bitcoin/bitcoin/issues/9934 * It may also avoid other security issues. */ if (fs::exists(filepath)) { throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.utf8string() + " already exists. If you are sure this is what you want, move it out of the way first"); } std::ofstream file; file.open(filepath); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; wallet.GetKeyBirthTimes(mapKeyBirth); int64_t block_time = 0; CHECK_NONFATAL(wallet.chain().findBlock(wallet.GetLastBlockHash(), FoundBlock().time(block_time))); // Note: To avoid a lock order issue, access to cs_main must be locked before cs_KeyStore. // So we do the two things in this function that lock cs_main first: GetKeyBirthTimes, and findBlock. LOCK(spk_man.cs_KeyStore); const std::map<CKeyID, int64_t>& mapKeyPool = spk_man.GetAllReserveKeys(); std::set<CScriptID> scripts = spk_man.GetCScripts(); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; vKeyBirth.reserve(mapKeyBirth.size()); for (const auto& entry : mapKeyBirth) { vKeyBirth.emplace_back(entry.second, entry.first); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by %s %s\n", PACKAGE_NAME, FormatFullVersion()); file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", wallet.GetLastBlockHeight(), wallet.GetLastBlockHash().ToString()); file << strprintf("# mined on %s\n", FormatISO8601DateTime(block_time)); file << "\n"; // add the base58check encoded extended master if the wallet uses HD CKeyID seed_id = spk_man.GetHDChain().seed_id; if (!seed_id.IsNull()) { CKey seed; if (spk_man.GetKey(seed_id, seed)) { CExtKey masterKey; masterKey.SetSeed(seed); file << "# extended private masterkey: " << EncodeExtKey(masterKey) << "\n\n"; } } for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = FormatISO8601DateTime(it->first); std::string strAddr; std::string strLabel; CKey key; if (spk_man.GetKey(keyid, key)) { CKeyMetadata metadata; const auto it{spk_man.mapKeyMetadata.find(keyid)}; if (it != spk_man.mapKeyMetadata.end()) metadata = it->second; file << strprintf("%s %s ", EncodeSecret(key), strTime); if (GetWalletAddressesForKey(&spk_man, wallet, keyid, strAddr, strLabel)) { file << strprintf("label=%s", strLabel); } else if (keyid == seed_id) { file << "hdseed=1"; } else if (mapKeyPool.count(keyid)) { file << "reserve=1"; } else if (metadata.hdKeypath == "s") { file << "inactivehdseed=1"; } else { file << "change=1"; } file << strprintf(" # addr=%s%s\n", strAddr, (metadata.has_key_origin ? " hdkeypath="+WriteHDKeypath(metadata.key_origin.path, /*apostrophe=*/true) : "")); } } file << "\n"; for (const CScriptID &scriptid : scripts) { CScript script; std::string create_time = "0"; std::string address = EncodeDestination(ScriptHash(scriptid)); // get birth times for scripts with metadata auto it = spk_man.m_script_metadata.find(scriptid); if (it != spk_man.m_script_metadata.end()) { create_time = FormatISO8601DateTime(it->second.nCreateTime); } if(spk_man.GetCScript(scriptid, script)) { file << strprintf("%s %s script=1", HexStr(script), create_time); file << strprintf(" # addr=%s\n", address); } } file << "\n"; file << "# End of dump\n"; file.close(); UniValue reply(UniValue::VOBJ); reply.pushKV("filename", filepath.utf8string()); return reply; }, }; } struct ImportData { // Input data std::unique_ptr<CScript> redeemscript; //!< Provided redeemScript; will be moved to `import_scripts` if relevant. std::unique_ptr<CScript> witnessscript; //!< Provided witnessScript; will be moved to `import_scripts` if relevant. // Output data std::set<CScript> import_scripts; std::map<CKeyID, bool> used_keys; //!< Import these private keys if available (the value indicates whether if the key is required for solvability) std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> key_origins; }; enum class ScriptContext { TOP, //!< Top-level scriptPubKey P2SH, //!< P2SH redeemScript WITNESS_V0, //!< P2WSH witnessScript }; // Analyse the provided scriptPubKey, determining which keys and which redeem scripts from the ImportData struct are needed to spend it, and mark them as used. // Returns an error string, or the empty string for success. static std::string RecurseImportData(const CScript& script, ImportData& import_data, const ScriptContext script_ctx) { // Use Solver to obtain script type and parsed pubkeys or hashes: std::vector<std::vector<unsigned char>> solverdata; TxoutType script_type = Solver(script, solverdata); switch (script_type) { case TxoutType::PUBKEY: { CPubKey pubkey(solverdata[0]); import_data.used_keys.emplace(pubkey.GetID(), false); return ""; } case TxoutType::PUBKEYHASH: { CKeyID id = CKeyID(uint160(solverdata[0])); import_data.used_keys[id] = true; return ""; } case TxoutType::SCRIPTHASH: { if (script_ctx == ScriptContext::P2SH) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2SH inside another P2SH"); if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2SH inside a P2WSH"); CHECK_NONFATAL(script_ctx == ScriptContext::TOP); CScriptID id = CScriptID(uint160(solverdata[0])); auto subscript = std::move(import_data.redeemscript); // Remove redeemscript from import_data to check for superfluous script later. if (!subscript) return "missing redeemscript"; if (CScriptID(*subscript) != id) return "redeemScript does not match the scriptPubKey"; import_data.import_scripts.emplace(*subscript); return RecurseImportData(*subscript, import_data, ScriptContext::P2SH); } case TxoutType::MULTISIG: { for (size_t i = 1; i + 1< solverdata.size(); ++i) { CPubKey pubkey(solverdata[i]); import_data.used_keys.emplace(pubkey.GetID(), false); } return ""; } case TxoutType::WITNESS_V0_SCRIPTHASH: { if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2WSH inside another P2WSH"); CScriptID id{RIPEMD160(solverdata[0])}; auto subscript = std::move(import_data.witnessscript); // Remove redeemscript from import_data to check for superfluous script later. if (!subscript) return "missing witnessscript"; if (CScriptID(*subscript) != id) return "witnessScript does not match the scriptPubKey or redeemScript"; if (script_ctx == ScriptContext::TOP) { import_data.import_scripts.emplace(script); // Special rule for IsMine: native P2WSH requires the TOP script imported (see script/ismine.cpp) } import_data.import_scripts.emplace(*subscript); return RecurseImportData(*subscript, import_data, ScriptContext::WITNESS_V0); } case TxoutType::WITNESS_V0_KEYHASH: { if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2WPKH inside P2WSH"); CKeyID id = CKeyID(uint160(solverdata[0])); import_data.used_keys[id] = true; if (script_ctx == ScriptContext::TOP) { import_data.import_scripts.emplace(script); // Special rule for IsMine: native P2WPKH requires the TOP script imported (see script/ismine.cpp) } return ""; } case TxoutType::NULL_DATA: return "unspendable script"; case TxoutType::NONSTANDARD: case TxoutType::WITNESS_UNKNOWN: case TxoutType::WITNESS_V1_TAPROOT: return "unrecognized script"; } // no default case, so the compiler can warn about missing cases NONFATAL_UNREACHABLE(); } static UniValue ProcessImportLegacy(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys) { UniValue warnings(UniValue::VARR); // First ensure scriptPubKey has either a script or JSON with "address" string const UniValue& scriptPubKey = data["scriptPubKey"]; bool isScript = scriptPubKey.getType() == UniValue::VSTR; if (!isScript && !(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address"))) { throw JSONRPCError(RPC_INVALID_PARAMETER, "scriptPubKey must be string with script or JSON with address string"); } const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str(); // Optional fields. const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : ""; const std::string& witness_script_hex = data.exists("witnessscript") ? data["witnessscript"].get_str() : ""; const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue(); const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue(); const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; const bool watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false; if (data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for a non-descriptor import"); } // Generate the script and destination for the scriptPubKey provided CScript script; if (!isScript) { CTxDestination dest = DecodeDestination(output); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address \"" + output + "\""); } if (OutputTypeFromDestination(dest) == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m addresses cannot be imported into legacy wallets"); } script = GetScriptForDestination(dest); } else { if (!IsHex(output)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey \"" + output + "\""); } std::vector<unsigned char> vData(ParseHex(output)); script = CScript(vData.begin(), vData.end()); CTxDestination dest; if (!ExtractDestination(script, dest) && !internal) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set to true for nonstandard scriptPubKey imports."); } } script_pub_keys.emplace(script); // Parse all arguments if (strRedeemScript.size()) { if (!IsHex(strRedeemScript)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script \"" + strRedeemScript + "\": must be hex string"); } auto parsed_redeemscript = ParseHex(strRedeemScript); import_data.redeemscript = std::make_unique<CScript>(parsed_redeemscript.begin(), parsed_redeemscript.end()); } if (witness_script_hex.size()) { if (!IsHex(witness_script_hex)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid witness script \"" + witness_script_hex + "\": must be hex string"); } auto parsed_witnessscript = ParseHex(witness_script_hex); import_data.witnessscript = std::make_unique<CScript>(parsed_witnessscript.begin(), parsed_witnessscript.end()); } for (size_t i = 0; i < pubKeys.size(); ++i) { const auto& str = pubKeys[i].get_str(); if (!IsHex(str)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + str + "\" must be a hex string"); } auto parsed_pubkey = ParseHex(str); CPubKey pubkey(parsed_pubkey); if (!pubkey.IsFullyValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + str + "\" is not a valid public key"); } pubkey_map.emplace(pubkey.GetID(), pubkey); ordered_pubkeys.push_back(pubkey.GetID()); } for (size_t i = 0; i < keys.size(); ++i) { const auto& str = keys[i].get_str(); CKey key = DecodeSecret(str); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); } CPubKey pubkey = key.GetPubKey(); CKeyID id = pubkey.GetID(); if (pubkey_map.count(id)) { pubkey_map.erase(id); } privkey_map.emplace(id, key); } // Verify and process input data have_solving_data = import_data.redeemscript || import_data.witnessscript || pubkey_map.size() || privkey_map.size(); if (have_solving_data) { // Match up data in import_data with the scriptPubKey in script. auto error = RecurseImportData(script, import_data, ScriptContext::TOP); // Verify whether the watchonly option corresponds to the availability of private keys. bool spendable = std::all_of(import_data.used_keys.begin(), import_data.used_keys.end(), [&](const std::pair<CKeyID, bool>& used_key){ return privkey_map.count(used_key.first) > 0; }); if (!watchOnly && !spendable) { warnings.push_back("Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."); } if (watchOnly && spendable) { warnings.push_back("All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."); } // Check that all required keys for solvability are provided. if (error.empty()) { for (const auto& require_key : import_data.used_keys) { if (!require_key.second) continue; // Not a required key if (pubkey_map.count(require_key.first) == 0 && privkey_map.count(require_key.first) == 0) { error = "some required keys are missing"; } } } if (!error.empty()) { warnings.push_back("Importing as non-solvable: " + error + ". If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript."); import_data = ImportData(); pubkey_map.clear(); privkey_map.clear(); have_solving_data = false; } else { // RecurseImportData() removes any relevant redeemscript/witnessscript from import_data, so we can use that to discover if a superfluous one was provided. if (import_data.redeemscript) warnings.push_back("Ignoring redeemscript as this is not a P2SH script."); if (import_data.witnessscript) warnings.push_back("Ignoring witnessscript as this is not a (P2SH-)P2WSH script."); for (auto it = privkey_map.begin(); it != privkey_map.end(); ) { auto oldit = it++; if (import_data.used_keys.count(oldit->first) == 0) { warnings.push_back("Ignoring irrelevant private key."); privkey_map.erase(oldit); } } for (auto it = pubkey_map.begin(); it != pubkey_map.end(); ) { auto oldit = it++; auto key_data_it = import_data.used_keys.find(oldit->first); if (key_data_it == import_data.used_keys.end() || !key_data_it->second) { warnings.push_back("Ignoring public key \"" + HexStr(oldit->first) + "\" as it doesn't appear inside P2PKH or P2WPKH."); pubkey_map.erase(oldit); } } } } return warnings; } static UniValue ProcessImportDescriptor(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys) { UniValue warnings(UniValue::VARR); const std::string& descriptor = data["desc"].get_str(); FlatSigningProvider keys; std::string error; auto parsed_desc = Parse(descriptor, keys, error, /* require_checksum = */ true); if (!parsed_desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } if (parsed_desc->GetOutputType() == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m descriptors cannot be imported into legacy wallets"); } have_solving_data = parsed_desc->IsSolvable(); const bool watch_only = data.exists("watchonly") ? data["watchonly"].get_bool() : false; int64_t range_start = 0, range_end = 0; if (!parsed_desc->IsRange() && data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor"); } else if (parsed_desc->IsRange()) { if (!data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor is ranged, please specify the range"); } std::tie(range_start, range_end) = ParseDescriptorRange(data["range"]); } const UniValue& priv_keys = data.exists("keys") ? data["keys"].get_array() : UniValue(); // Expand all descriptors to get public keys and scripts, and private keys if available. for (int i = range_start; i <= range_end; ++i) { FlatSigningProvider out_keys; std::vector<CScript> scripts_temp; parsed_desc->Expand(i, keys, scripts_temp, out_keys); std::copy(scripts_temp.begin(), scripts_temp.end(), std::inserter(script_pub_keys, script_pub_keys.end())); for (const auto& key_pair : out_keys.pubkeys) { ordered_pubkeys.push_back(key_pair.first); } for (const auto& x : out_keys.scripts) { import_data.import_scripts.emplace(x.second); } parsed_desc->ExpandPrivate(i, keys, out_keys); std::copy(out_keys.pubkeys.begin(), out_keys.pubkeys.end(), std::inserter(pubkey_map, pubkey_map.end())); std::copy(out_keys.keys.begin(), out_keys.keys.end(), std::inserter(privkey_map, privkey_map.end())); import_data.key_origins.insert(out_keys.origins.begin(), out_keys.origins.end()); } for (size_t i = 0; i < priv_keys.size(); ++i) { const auto& str = priv_keys[i].get_str(); CKey key = DecodeSecret(str); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); } CPubKey pubkey = key.GetPubKey(); CKeyID id = pubkey.GetID(); // Check if this private key corresponds to a public key from the descriptor if (!pubkey_map.count(id)) { warnings.push_back("Ignoring irrelevant private key."); } else { privkey_map.emplace(id, key); } } // Check if all the public keys have corresponding private keys in the import for spendability. // This does not take into account threshold multisigs which could be spendable without all keys. // Thus, threshold multisigs without all keys will be considered not spendable here, even if they are, // perhaps triggering a false warning message. This is consistent with the current wallet IsMine check. bool spendable = std::all_of(pubkey_map.begin(), pubkey_map.end(), [&](const std::pair<CKeyID, CPubKey>& used_key) { return privkey_map.count(used_key.first) > 0; }) && std::all_of(import_data.key_origins.begin(), import_data.key_origins.end(), [&](const std::pair<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& entry) { return privkey_map.count(entry.first) > 0; }); if (!watch_only && !spendable) { warnings.push_back("Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."); } if (watch_only && spendable) { warnings.push_back("All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."); } return warnings; } static UniValue ProcessImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { UniValue warnings(UniValue::VARR); UniValue result(UniValue::VOBJ); try { const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; // Internal addresses should not have a label if (internal && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label"); } const std::string label{LabelFromValue(data["label"])}; const bool add_keypool = data.exists("keypool") ? data["keypool"].get_bool() : false; // Add to keypool only works with privkeys disabled if (add_keypool && !wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Keys can only be imported to the keypool when private keys are disabled"); } ImportData import_data; std::map<CKeyID, CPubKey> pubkey_map; std::map<CKeyID, CKey> privkey_map; std::set<CScript> script_pub_keys; std::vector<CKeyID> ordered_pubkeys; bool have_solving_data; if (data.exists("scriptPubKey") && data.exists("desc")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Both a descriptor and a scriptPubKey should not be provided."); } else if (data.exists("scriptPubKey")) { warnings = ProcessImportLegacy(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys); } else if (data.exists("desc")) { warnings = ProcessImportDescriptor(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys); } else { throw JSONRPCError(RPC_INVALID_PARAMETER, "Either a descriptor or scriptPubKey must be provided."); } // If private keys are disabled, abort if private keys are being imported if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !privkey_map.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); } // Check whether we have any work to do for (const CScript& script : script_pub_keys) { if (wallet.IsMine(script) & ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script (\"" + HexStr(script) + "\")"); } } // All good, time to import wallet.MarkDirty(); if (!wallet.ImportScripts(import_data.import_scripts, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding script to wallet"); } if (!wallet.ImportPrivKeys(privkey_map, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } if (!wallet.ImportPubKeys(ordered_pubkeys, pubkey_map, import_data.key_origins, add_keypool, internal, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } if (!wallet.ImportScriptPubKeys(label, script_pub_keys, have_solving_data, !internal, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } result.pushKV("success", UniValue(true)); } catch (const UniValue& e) { result.pushKV("success", UniValue(false)); result.pushKV("error", e); } catch (...) { result.pushKV("success", UniValue(false)); result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields")); } PushWarnings(warnings, result); return result; } static int64_t GetImportTimestamp(const UniValue& data, int64_t now) { if (data.exists("timestamp")) { const UniValue& timestamp = data["timestamp"]; if (timestamp.isNum()) { return timestamp.getInt<int64_t>(); } else if (timestamp.isStr() && timestamp.get_str() == "now") { return now; } throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type()))); } throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key"); } RPCHelpMan importmulti() { return RPCHelpMan{"importmulti", "\nImport addresses/scripts (with private or public keys, redeem script (P2SH)), optionally rescanning the blockchain from the earliest creation time of the imported scripts. Requires a new wallet backup.\n" "If an address/script is imported without all of the private keys required to spend from that address, it will be watchonly. The 'watchonly' option must be set to true in this case or a warning will be returned.\n" "Conversely, if all the private keys are provided and the address/script is spendable, the watchonly option must be set to false, or a warning will be returned.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n" "The rescan parameter can be set to false if the key was never used to create transactions. If it is set to false,\n" "but the key was used to create transactions, rescanblockchain needs to be called with the appropriate block range.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n" "Note: This command is only compatible with legacy wallets. Use \"importdescriptors\" for descriptor wallets.\n", { {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"desc", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Descriptor to import. If using descriptor, do not also provide address/scriptPubKey, scripts, or pubkeys"}, {"scriptPubKey", RPCArg::Type::STR, RPCArg::Optional::NO, "Type of scriptPubKey (string for script, json for address). Should not be provided if using a descriptor", RPCArgOptions{.type_str={"\"<script>\" | { \"address\":\"<address>\" }", "string / json"}} }, {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Creation time of the key expressed in " + UNIX_EPOCH_TIME + ",\n" "or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n" "key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n" "\"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n" "0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n" "creation time of all keys being imported by the importmulti call will be scanned.", RPCArgOptions{.type_str={"timestamp | \"now\"", "integer / string"}} }, {"redeemscript", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Allowed only if the scriptPubKey is a P2SH or P2SH-P2WSH address/scriptPubKey"}, {"witnessscript", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Allowed only if the scriptPubKey is a P2SH-P2WSH or P2WSH address/scriptPubKey"}, {"pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Array of strings giving pubkeys to import. They must occur in P2PKH or P2WPKH scripts. They are not required when the private key is also provided (see the \"keys\" argument).", { {"pubKey", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""}, } }, {"keys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Array of strings giving private keys to import. The corresponding public keys must occur in the output or redeemscript.", { {"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""}, } }, {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"}, {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether matching outputs should be treated as not incoming payments (also known as change)"}, {"watchonly", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether matching outputs should be considered watchonly."}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false"}, {"keypool", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether imported public keys should be added to the keypool for when users request new addresses. Only allowed when wallet private keys are disabled"}, }, }, }, RPCArgOptions{.oneline_description="requests"}}, {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", { {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Scan the chain and mempool for wallet transactions after all imports."}, }, RPCArgOptions{.oneline_description="options"}}, }, RPCResult{ RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "success", ""}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "", { {RPCResult::Type::STR, "", ""}, }}, {RPCResult::Type::OBJ, "error", /*optional=*/true, "", { {RPCResult::Type::ELISION, "", "JSONRPC error"}, }}, }}, } }, RPCExamples{ HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, " "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") + HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") }, [&](const RPCHelpMan& self, const JSONRPCRequest& mainRequest) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(mainRequest); if (!pwallet) return UniValue::VNULL; CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); EnsureLegacyScriptPubKeyMan(*pwallet, true); const UniValue& requests = mainRequest.params[0]; //Default options bool fRescan = true; if (!mainRequest.params[1].isNull()) { const UniValue& options = mainRequest.params[1]; if (options.exists("rescan")) { fRescan = options["rescan"].get_bool(); } } WalletRescanReserver reserver(*pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int64_t now = 0; bool fRunScan = false; int64_t nLowestTimestamp = 0; UniValue response(UniValue::VARR); { LOCK(pwallet->cs_wallet); // Check all requests are watchonly bool is_watchonly{true}; for (size_t i = 0; i < requests.size(); ++i) { const UniValue& request = requests[i]; if (!request.exists("watchonly") || !request["watchonly"].get_bool()) { is_watchonly = false; break; } } // Wallet does not need to be unlocked if all requests are watchonly if (!is_watchonly) EnsureWalletIsUnlocked(wallet); // Verify all timestamps are present before importing any keys. CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(nLowestTimestamp).mtpTime(now))); for (const UniValue& data : requests.getValues()) { GetImportTimestamp(data, now); } const int64_t minimumTimestamp = 1; for (const UniValue& data : requests.getValues()) { const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp); const UniValue result = ProcessImport(*pwallet, data, timestamp); response.push_back(result); if (!fRescan) { continue; } // If at least one request was successful then allow rescan. if (result["success"].get_bool()) { fRunScan = true; } // Get the lowest timestamp. if (timestamp < nLowestTimestamp) { nLowestTimestamp = timestamp; } } } if (fRescan && fRunScan && requests.size()) { int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, reserver, /*update=*/true); pwallet->ResubmitWalletTransactions(/*relay=*/false, /*force=*/true); if (pwallet->IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } if (scannedTime > nLowestTimestamp) { std::vector<UniValue> results = response.getValues(); response.clear(); response.setArray(); size_t i = 0; for (const UniValue& request : requests.getValues()) { // If key creation date is within the successfully scanned // range, or if the import result already has an error set, let // the result stand unmodified. Otherwise replace the result // with an error message. if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) { response.push_back(results.at(i)); } else { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV( "error", JSONRPCError( RPC_MISC_ERROR, strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a " "block from time %d, which is after or within %d seconds of key creation, and " "could contain transactions pertaining to the key. As a result, transactions " "and coins using this key may not appear in the wallet. This error could be " "caused by pruning or data corruption (see bitcoind log for details) and could " "be dealt with by downloading and rescanning the relevant blocks (see -reindex " "option and rescanblockchain RPC).", GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW))); response.push_back(std::move(result)); } ++i; } } } return response; }, }; } static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { UniValue warnings(UniValue::VARR); UniValue result(UniValue::VOBJ); try { if (!data.exists("desc")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor not found."); } const std::string& descriptor = data["desc"].get_str(); const bool active = data.exists("active") ? data["active"].get_bool() : false; const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; const std::string label{LabelFromValue(data["label"])}; // Parse descriptor string FlatSigningProvider keys; std::string error; auto parsed_desc = Parse(descriptor, keys, error, /* require_checksum = */ true); if (!parsed_desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } // Range check int64_t range_start = 0, range_end = 1, next_index = 0; if (!parsed_desc->IsRange() && data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor"); } else if (parsed_desc->IsRange()) { if (data.exists("range")) { auto range = ParseDescriptorRange(data["range"]); range_start = range.first; range_end = range.second + 1; // Specified range end is inclusive, but we need range end as exclusive } else { warnings.push_back("Range not given, using default keypool range"); range_start = 0; range_end = wallet.m_keypool_size; } next_index = range_start; if (data.exists("next_index")) { next_index = data["next_index"].getInt<int64_t>(); // bound checks if (next_index < range_start || next_index >= range_end) { throw JSONRPCError(RPC_INVALID_PARAMETER, "next_index is out of range"); } } } // Active descriptors must be ranged if (active && !parsed_desc->IsRange()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Active descriptors must be ranged"); } // Ranged descriptors should not have a label if (data.exists("range") && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptors should not have a label"); } // Internal addresses should not have a label either if (internal && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label"); } // Combo descriptor check if (active && !parsed_desc->IsSingleType()) { throw JSONRPCError(RPC_WALLET_ERROR, "Combo descriptors cannot be set to active"); } // If the wallet disabled private keys, abort if private keys exist if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !keys.keys.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); } // Need to ExpandPrivate to check if private keys are available for all pubkeys FlatSigningProvider expand_keys; std::vector<CScript> scripts; if (!parsed_desc->Expand(0, keys, scripts, expand_keys)) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot expand descriptor. Probably because of hardened derivations without private keys provided"); } parsed_desc->ExpandPrivate(0, keys, expand_keys); // Check if all private keys are provided bool have_all_privkeys = !expand_keys.keys.empty(); for (const auto& entry : expand_keys.origins) { const CKeyID& key_id = entry.first; CKey key; if (!expand_keys.GetKey(key_id, key)) { have_all_privkeys = false; break; } } // If private keys are enabled, check some things. if (!wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { if (keys.keys.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import descriptor without private keys to a wallet with private keys enabled"); } if (!have_all_privkeys) { warnings.push_back("Not all private keys provided. Some wallet functionality may return unexpected errors"); } } WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index); // Check if the wallet already contains the descriptor auto existing_spk_manager = wallet.GetDescriptorScriptPubKeyMan(w_desc); if (existing_spk_manager) { if (!existing_spk_manager->CanUpdateToWalletDescriptor(w_desc, error)) { throw JSONRPCError(RPC_INVALID_PARAMETER, error); } } // Add descriptor to the wallet auto spk_manager = wallet.AddWalletDescriptor(w_desc, keys, label, internal); if (spk_manager == nullptr) { throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Could not add descriptor '%s'", descriptor)); } // Set descriptor as active if necessary if (active) { if (!w_desc.descriptor->GetOutputType()) { warnings.push_back("Unknown output type, cannot set descriptor to active."); } else { wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), internal); } } else { if (w_desc.descriptor->GetOutputType()) { wallet.DeactivateScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), internal); } } result.pushKV("success", UniValue(true)); } catch (const UniValue& e) { result.pushKV("success", UniValue(false)); result.pushKV("error", e); } PushWarnings(warnings, result); return result; } RPCHelpMan importdescriptors() { return RPCHelpMan{"importdescriptors", "\nImport descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported. Requires a new wallet backup.\n" "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n" "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n" "The rescan is significantly faster if block filters are available (using startup option \"-blockfilterindex=1\").\n", { {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "Descriptor to import."}, {"active", RPCArg::Type::BOOL, RPCArg::Default{false}, "Set this descriptor to be the active descriptor for the corresponding output type/externality"}, {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"}, {"next_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If a ranged descriptor is set to active, this specifies the next index to generate addresses from"}, {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time from which to start rescanning the blockchain for this descriptor, in " + UNIX_EPOCH_TIME + "\n" "Use the string \"now\" to substitute the current synced blockchain time.\n" "\"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n" "0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n" "of all descriptors being imported will be scanned as well as the mempool.", RPCArgOptions{.type_str={"timestamp | \"now\"", "integer / string"}} }, {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether matching outputs should be treated as not incoming payments (e.g. change)"}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false. Disabled for ranged descriptors"}, }, }, }, RPCArgOptions{.oneline_description="requests"}}, }, RPCResult{ RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "success", ""}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "", { {RPCResult::Type::STR, "", ""}, }}, {RPCResult::Type::OBJ, "error", /*optional=*/true, "", { {RPCResult::Type::ELISION, "", "JSONRPC error"}, }}, }}, } }, RPCExamples{ HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, " "{ \"desc\": \"<my descriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") + HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'") }, [&](const RPCHelpMan& self, const JSONRPCRequest& main_request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(main_request); if (!pwallet) return UniValue::VNULL; CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); // Make sure wallet is a descriptor wallet if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) { throw JSONRPCError(RPC_WALLET_ERROR, "importdescriptors is not available for non-descriptor wallets"); } WalletRescanReserver reserver(*pwallet); if (!reserver.reserve(/*with_passphrase=*/true)) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } // Ensure that the wallet is not locked for the remainder of this RPC, as // the passphrase is used to top up the keypool. LOCK(pwallet->m_relock_mutex); const UniValue& requests = main_request.params[0]; const int64_t minimum_timestamp = 1; int64_t now = 0; int64_t lowest_timestamp = 0; bool rescan = false; UniValue response(UniValue::VARR); { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(lowest_timestamp).mtpTime(now))); // Get all timestamps and extract the lowest timestamp for (const UniValue& request : requests.getValues()) { // This throws an error if "timestamp" doesn't exist const int64_t timestamp = std::max(GetImportTimestamp(request, now), minimum_timestamp); const UniValue result = ProcessDescriptorImport(*pwallet, request, timestamp); response.push_back(result); if (lowest_timestamp > timestamp ) { lowest_timestamp = timestamp; } // If we know the chain tip, and at least one request was successful then allow rescan if (!rescan && result["success"].get_bool()) { rescan = true; } } pwallet->ConnectScriptPubKeyManNotifiers(); } // Rescan the blockchain using the lowest timestamp if (rescan) { int64_t scanned_time = pwallet->RescanFromTime(lowest_timestamp, reserver, /*update=*/true); pwallet->ResubmitWalletTransactions(/*relay=*/false, /*force=*/true); if (pwallet->IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } if (scanned_time > lowest_timestamp) { std::vector<UniValue> results = response.getValues(); response.clear(); response.setArray(); // Compose the response for (unsigned int i = 0; i < requests.size(); ++i) { const UniValue& request = requests.getValues().at(i); // If the descriptor timestamp is within the successfully scanned // range, or if the import result already has an error set, let // the result stand unmodified. Otherwise replace the result // with an error message. if (scanned_time <= GetImportTimestamp(request, now) || results.at(i).exists("error")) { response.push_back(results.at(i)); } else { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV( "error", JSONRPCError( RPC_MISC_ERROR, strprintf("Rescan failed for descriptor with timestamp %d. There was an error reading a " "block from time %d, which is after or within %d seconds of key creation, and " "could contain transactions pertaining to the desc. As a result, transactions " "and coins using this desc may not appear in the wallet. This error could be " "caused by pruning or data corruption (see bitcoind log for details) and could " "be dealt with by downloading and rescanning the relevant blocks (see -reindex " "option and rescanblockchain RPC).", GetImportTimestamp(request, now), scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW))); response.push_back(std::move(result)); } } } } return response; }, }; } RPCHelpMan listdescriptors() { return RPCHelpMan{ "listdescriptors", "\nList descriptors imported into a descriptor-enabled wallet.\n", { {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private descriptors."} }, RPCResult{RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"}, {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects (sorted by descriptor string representation)", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "desc", "Descriptor string representation"}, {RPCResult::Type::NUM, "timestamp", "The creation time of the descriptor"}, {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"}, {RPCResult::Type::BOOL, "internal", /*optional=*/true, "True if this descriptor is used to generate change addresses. False if this descriptor is used to generate receiving addresses; defined only for active descriptors"}, {RPCResult::Type::ARR_FIXED, "range", /*optional=*/true, "Defined only for ranged descriptors", { {RPCResult::Type::NUM, "", "Range start inclusive"}, {RPCResult::Type::NUM, "", "Range end inclusive"}, }}, {RPCResult::Type::NUM, "next", /*optional=*/true, "Same as next_index field. Kept for compatibility reason."}, {RPCResult::Type::NUM, "next_index", /*optional=*/true, "The next index to generate addresses from; defined only for ranged descriptors"}, }}, }} }}, RPCExamples{ HelpExampleCli("listdescriptors", "") + HelpExampleRpc("listdescriptors", "") + HelpExampleCli("listdescriptors", "true") + HelpExampleRpc("listdescriptors", "true") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return UniValue::VNULL; if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) { throw JSONRPCError(RPC_WALLET_ERROR, "listdescriptors is not available for non-descriptor wallets"); } const bool priv = !request.params[0].isNull() && request.params[0].get_bool(); if (priv) { EnsureWalletIsUnlocked(*wallet); } LOCK(wallet->cs_wallet); const auto active_spk_mans = wallet->GetActiveScriptPubKeyMans(); struct WalletDescInfo { std::string descriptor; uint64_t creation_time; bool active; std::optional<bool> internal; std::optional<std::pair<int64_t,int64_t>> range; int64_t next_index; }; std::vector<WalletDescInfo> wallet_descriptors; for (const auto& spk_man : wallet->GetAllScriptPubKeyMans()) { const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man); if (!desc_spk_man) { throw JSONRPCError(RPC_WALLET_ERROR, "Unexpected ScriptPubKey manager type."); } LOCK(desc_spk_man->cs_desc_man); const auto& wallet_descriptor = desc_spk_man->GetWalletDescriptor(); std::string descriptor; if (!desc_spk_man->GetDescriptorString(descriptor, priv)) { throw JSONRPCError(RPC_WALLET_ERROR, "Can't get descriptor string."); } const bool is_range = wallet_descriptor.descriptor->IsRange(); wallet_descriptors.push_back({ descriptor, wallet_descriptor.creation_time, active_spk_mans.count(desc_spk_man) != 0, wallet->IsInternalScriptPubKeyMan(desc_spk_man), is_range ? std::optional(std::make_pair(wallet_descriptor.range_start, wallet_descriptor.range_end)) : std::nullopt, wallet_descriptor.next_index }); } std::sort(wallet_descriptors.begin(), wallet_descriptors.end(), [](const auto& a, const auto& b) { return a.descriptor < b.descriptor; }); UniValue descriptors(UniValue::VARR); for (const WalletDescInfo& info : wallet_descriptors) { UniValue spk(UniValue::VOBJ); spk.pushKV("desc", info.descriptor); spk.pushKV("timestamp", info.creation_time); spk.pushKV("active", info.active); if (info.internal.has_value()) { spk.pushKV("internal", info.internal.value()); } if (info.range.has_value()) { UniValue range(UniValue::VARR); range.push_back(info.range->first); range.push_back(info.range->second - 1); spk.pushKV("range", range); spk.pushKV("next", info.next_index); spk.pushKV("next_index", info.next_index); } descriptors.push_back(spk); } UniValue response(UniValue::VOBJ); response.pushKV("wallet_name", wallet->GetName()); response.pushKV("descriptors", descriptors); return response; }, }; } RPCHelpMan backupwallet() { return RPCHelpMan{"backupwallet", "\nSafely copies the current wallet file to the specified destination, which can either be a directory or a path with a filename.\n", { {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); std::string strDest = request.params[0].get_str(); if (!pwallet->BackupWallet(strDest)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); } return UniValue::VNULL; }, }; } RPCHelpMan restorewallet() { return RPCHelpMan{ "restorewallet", "\nRestores and loads a wallet from backup.\n" "\nThe rescan is significantly faster if a descriptor wallet is restored" "\nand block filters are available (using startup option \"-blockfilterindex=1\").\n", { {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name that will be applied to the restored wallet"}, {"backup_file", RPCArg::Type::STR, RPCArg::Optional::NO, "The backup file that will be used to restore the wallet."}, {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "name", "The wallet name if restored successfully."}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to restoring and loading the wallet.", { {RPCResult::Type::STR, "", ""}, }}, } }, RPCExamples{ HelpExampleCli("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"") + HelpExampleRpc("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"") + HelpExampleCliNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}}) + HelpExampleRpcNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}}) }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { WalletContext& context = EnsureWalletContext(request.context); auto backup_file = fs::u8path(request.params[1].get_str()); std::string wallet_name = request.params[0].get_str(); std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool()); DatabaseStatus status; bilingual_str error; std::vector<bilingual_str> warnings; const std::shared_ptr<CWallet> wallet = RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings); HandleWalletError(wallet, status, error); UniValue obj(UniValue::VOBJ); obj.pushKV("name", wallet->GetName()); PushWarnings(warnings, obj); return obj; }, }; } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/wallet.h
// Copyright (c) 2016-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_RPC_WALLET_H #define BITCOIN_WALLET_RPC_WALLET_H #include <span.h> class CRPCCommand; namespace wallet { Span<const CRPCCommand> GetWalletRPCCommands(); } // namespace wallet #endif // BITCOIN_WALLET_RPC_WALLET_H
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/util.h
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_RPC_UTIL_H #define BITCOIN_WALLET_RPC_UTIL_H #include <rpc/util.h> #include <script/script.h> #include <wallet/wallet.h> #include <any> #include <memory> #include <string> #include <vector> class JSONRPCRequest; class UniValue; struct bilingual_str; namespace wallet { class LegacyScriptPubKeyMan; enum class DatabaseStatus; struct WalletContext; extern const std::string HELP_REQUIRING_PASSPHRASE; static const RPCResult RESULT_LAST_PROCESSED_BLOCK { RPCResult::Type::OBJ, "lastprocessedblock", "hash and height of the block this information was generated on",{ {RPCResult::Type::STR_HEX, "hash", "hash of the block this information was generated on"}, {RPCResult::Type::NUM, "height", "height of the block this information was generated on"}} }; /** * Figures out what wallet, if any, to use for a JSONRPCRequest. * * @param[in] request JSONRPCRequest that wishes to access a wallet * @return nullptr if no wallet should be used, or a pointer to the CWallet */ std::shared_ptr<CWallet> GetWalletForJSONRPCRequest(const JSONRPCRequest& request); bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest& request, std::string& wallet_name); void EnsureWalletIsUnlocked(const CWallet&); WalletContext& EnsureWalletContext(const std::any& context); LegacyScriptPubKeyMan& EnsureLegacyScriptPubKeyMan(CWallet& wallet, bool also_create = false); const LegacyScriptPubKeyMan& EnsureConstLegacyScriptPubKeyMan(const CWallet& wallet); bool GetAvoidReuseFlag(const CWallet& wallet, const UniValue& param); bool ParseIncludeWatchonly(const UniValue& include_watchonly, const CWallet& wallet); std::string LabelFromValue(const UniValue& value); //! Fetch parent descriptors of this scriptPubKey. void PushParentDescriptors(const CWallet& wallet, const CScript& script_pubkey, UniValue& entry); void HandleWalletError(const std::shared_ptr<CWallet> wallet, DatabaseStatus& status, bilingual_str& error); int64_t ParseISO8601DateTime(const std::string& str); void AppendLastProcessedBlock(UniValue& entry, const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet); } // namespace wallet #endif // BITCOIN_WALLET_RPC_UTIL_H
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/wallet.cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <key_io.h> #include <rpc/server.h> #include <rpc/util.h> #include <util/translation.h> #include <wallet/context.h> #include <wallet/receive.h> #include <wallet/rpc/wallet.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> #include <wallet/walletutil.h> #include <optional> #include <univalue.h> namespace wallet { static const std::map<uint64_t, std::string> WALLET_FLAG_CAVEATS{ {WALLET_FLAG_AVOID_REUSE, "You need to rescan the blockchain in order to correctly mark used " "destinations in the past. Until this is done, some destinations may " "be considered unused, even if the opposite is the case."}, }; /** Checks if a CKey is in the given CWallet compressed or otherwise*/ bool HaveKey(const SigningProvider& wallet, const CKey& key) { CKey key2; key2.Set(key.begin(), key.end(), !key.IsCompressed()); return wallet.HaveKey(key.GetPubKey().GetID()) || wallet.HaveKey(key2.GetPubKey().GetID()); } static RPCHelpMan getwalletinfo() { return RPCHelpMan{"getwalletinfo", "Returns an object containing various wallet state info.\n", {}, RPCResult{ RPCResult::Type::OBJ, "", "", { { {RPCResult::Type::STR, "walletname", "the wallet name"}, {RPCResult::Type::NUM, "walletversion", "the wallet version"}, {RPCResult::Type::STR, "format", "the database format (bdb or sqlite)"}, {RPCResult::Type::STR_AMOUNT, "balance", "DEPRECATED. Identical to getbalances().mine.trusted"}, {RPCResult::Type::STR_AMOUNT, "unconfirmed_balance", "DEPRECATED. Identical to getbalances().mine.untrusted_pending"}, {RPCResult::Type::STR_AMOUNT, "immature_balance", "DEPRECATED. Identical to getbalances().mine.immature"}, {RPCResult::Type::NUM, "txcount", "the total number of transactions in the wallet"}, {RPCResult::Type::NUM_TIME, "keypoololdest", /*optional=*/true, "the " + UNIX_EPOCH_TIME + " of the oldest pre-generated key in the key pool. Legacy wallets only."}, {RPCResult::Type::NUM, "keypoolsize", "how many new keys are pre-generated (only counts external keys)"}, {RPCResult::Type::NUM, "keypoolsize_hd_internal", /*optional=*/true, "how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)"}, {RPCResult::Type::NUM_TIME, "unlocked_until", /*optional=*/true, "the " + UNIX_EPOCH_TIME + " until which the wallet is unlocked for transfers, or 0 if the wallet is locked (only present for passphrase-encrypted wallets)"}, {RPCResult::Type::STR_AMOUNT, "paytxfee", "the transaction fee configuration, set in " + CURRENCY_UNIT + "/kvB"}, {RPCResult::Type::STR_HEX, "hdseedid", /*optional=*/true, "the Hash160 of the HD seed (only present when HD is enabled)"}, {RPCResult::Type::BOOL, "private_keys_enabled", "false if privatekeys are disabled for this wallet (enforced watch-only wallet)"}, {RPCResult::Type::BOOL, "avoid_reuse", "whether this wallet tracks clean/dirty coins in terms of reuse"}, {RPCResult::Type::OBJ, "scanning", "current scanning details, or false if no scan is in progress", { {RPCResult::Type::NUM, "duration", "elapsed seconds since scan start"}, {RPCResult::Type::NUM, "progress", "scanning progress percentage [0.0, 1.0]"}, }, /*skip_type_check=*/true}, {RPCResult::Type::BOOL, "descriptors", "whether this wallet uses descriptors for scriptPubKey management"}, {RPCResult::Type::BOOL, "external_signer", "whether this wallet is configured to use an external signer such as a hardware wallet"}, {RPCResult::Type::BOOL, "blank", "Whether this wallet intentionally does not contain any keys, scripts, or descriptors"}, {RPCResult::Type::NUM_TIME, "birthtime", /*optional=*/true, "The start time for blocks scanning. It could be modified by (re)importing any descriptor with an earlier timestamp."}, RESULT_LAST_PROCESSED_BLOCK, }}, }, RPCExamples{ HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); UniValue obj(UniValue::VOBJ); size_t kpExternalSize = pwallet->KeypoolCountExternalKeys(); const auto bal = GetBalance(*pwallet); obj.pushKV("walletname", pwallet->GetName()); obj.pushKV("walletversion", pwallet->GetVersion()); obj.pushKV("format", pwallet->GetDatabase().Format()); obj.pushKV("balance", ValueFromAmount(bal.m_mine_trusted)); obj.pushKV("unconfirmed_balance", ValueFromAmount(bal.m_mine_untrusted_pending)); obj.pushKV("immature_balance", ValueFromAmount(bal.m_mine_immature)); obj.pushKV("txcount", (int)pwallet->mapWallet.size()); const auto kp_oldest = pwallet->GetOldestKeyPoolTime(); if (kp_oldest.has_value()) { obj.pushKV("keypoololdest", kp_oldest.value()); } obj.pushKV("keypoolsize", (int64_t)kpExternalSize); LegacyScriptPubKeyMan* spk_man = pwallet->GetLegacyScriptPubKeyMan(); if (spk_man) { CKeyID seed_id = spk_man->GetHDChain().seed_id; if (!seed_id.IsNull()) { obj.pushKV("hdseedid", seed_id.GetHex()); } } if (pwallet->CanSupportFeature(FEATURE_HD_SPLIT)) { obj.pushKV("keypoolsize_hd_internal", (int64_t)(pwallet->GetKeyPoolSize() - kpExternalSize)); } if (pwallet->IsCrypted()) { obj.pushKV("unlocked_until", pwallet->nRelockTime); } obj.pushKV("paytxfee", ValueFromAmount(pwallet->m_pay_tx_fee.GetFeePerK())); obj.pushKV("private_keys_enabled", !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)); obj.pushKV("avoid_reuse", pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)); if (pwallet->IsScanning()) { UniValue scanning(UniValue::VOBJ); scanning.pushKV("duration", Ticks<std::chrono::seconds>(pwallet->ScanningDuration())); scanning.pushKV("progress", pwallet->ScanningProgress()); obj.pushKV("scanning", scanning); } else { obj.pushKV("scanning", false); } obj.pushKV("descriptors", pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)); obj.pushKV("external_signer", pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)); obj.pushKV("blank", pwallet->IsWalletFlagSet(WALLET_FLAG_BLANK_WALLET)); if (int64_t birthtime = pwallet->GetBirthTime(); birthtime != UNKNOWN_TIME) { obj.pushKV("birthtime", birthtime); } AppendLastProcessedBlock(obj, *pwallet); return obj; }, }; } static RPCHelpMan listwalletdir() { return RPCHelpMan{"listwalletdir", "Returns a list of wallets in the wallet directory.\n", {}, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::ARR, "wallets", "", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "name", "The wallet name"}, }}, }}, } }, RPCExamples{ HelpExampleCli("listwalletdir", "") + HelpExampleRpc("listwalletdir", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { UniValue wallets(UniValue::VARR); for (const auto& path : ListDatabases(GetWalletDir())) { UniValue wallet(UniValue::VOBJ); wallet.pushKV("name", path.utf8string()); wallets.push_back(wallet); } UniValue result(UniValue::VOBJ); result.pushKV("wallets", wallets); return result; }, }; } static RPCHelpMan listwallets() { return RPCHelpMan{"listwallets", "Returns a list of currently loaded wallets.\n" "For full information on the wallet, use \"getwalletinfo\"\n", {}, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::STR, "walletname", "the wallet name"}, } }, RPCExamples{ HelpExampleCli("listwallets", "") + HelpExampleRpc("listwallets", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { UniValue obj(UniValue::VARR); WalletContext& context = EnsureWalletContext(request.context); for (const std::shared_ptr<CWallet>& wallet : GetWallets(context)) { LOCK(wallet->cs_wallet); obj.push_back(wallet->GetName()); } return obj; }, }; } static RPCHelpMan loadwallet() { return RPCHelpMan{"loadwallet", "\nLoads a wallet from a wallet file or directory." "\nNote that all wallet command-line options used when starting bitcoind will be" "\napplied to the new wallet.\n", { {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet directory or .dat file."}, {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "name", "The wallet name if loaded successfully."}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to loading the wallet.", { {RPCResult::Type::STR, "", ""}, }}, } }, RPCExamples{ HelpExampleCli("loadwallet", "\"test.dat\"") + HelpExampleRpc("loadwallet", "\"test.dat\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { WalletContext& context = EnsureWalletContext(request.context); const std::string name(request.params[0].get_str()); DatabaseOptions options; DatabaseStatus status; ReadDatabaseArgs(*context.args, options); options.require_existing = true; bilingual_str error; std::vector<bilingual_str> warnings; std::optional<bool> load_on_start = request.params[1].isNull() ? std::nullopt : std::optional<bool>(request.params[1].get_bool()); { LOCK(context.wallets_mutex); if (std::any_of(context.wallets.begin(), context.wallets.end(), [&name](const auto& wallet) { return wallet->GetName() == name; })) { throw JSONRPCError(RPC_WALLET_ALREADY_LOADED, "Wallet \"" + name + "\" is already loaded."); } } std::shared_ptr<CWallet> const wallet = LoadWallet(context, name, load_on_start, options, status, error, warnings); HandleWalletError(wallet, status, error); UniValue obj(UniValue::VOBJ); obj.pushKV("name", wallet->GetName()); PushWarnings(warnings, obj); return obj; }, }; } static RPCHelpMan setwalletflag() { std::string flags; for (auto& it : WALLET_FLAG_MAP) if (it.second & MUTABLE_WALLET_FLAGS) flags += (flags == "" ? "" : ", ") + it.first; return RPCHelpMan{"setwalletflag", "\nChange the state of the given wallet flag for a wallet.\n", { {"flag", RPCArg::Type::STR, RPCArg::Optional::NO, "The name of the flag to change. Current available flags: " + flags}, {"value", RPCArg::Type::BOOL, RPCArg::Default{true}, "The new state."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "flag_name", "The name of the flag that was modified"}, {RPCResult::Type::BOOL, "flag_state", "The new state of the flag"}, {RPCResult::Type::STR, "warnings", /*optional=*/true, "Any warnings associated with the change"}, } }, RPCExamples{ HelpExampleCli("setwalletflag", "avoid_reuse") + HelpExampleRpc("setwalletflag", "\"avoid_reuse\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; std::string flag_str = request.params[0].get_str(); bool value = request.params[1].isNull() || request.params[1].get_bool(); if (!WALLET_FLAG_MAP.count(flag_str)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unknown wallet flag: %s", flag_str)); } auto flag = WALLET_FLAG_MAP.at(flag_str); if (!(flag & MUTABLE_WALLET_FLAGS)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Wallet flag is immutable: %s", flag_str)); } UniValue res(UniValue::VOBJ); if (pwallet->IsWalletFlagSet(flag) == value) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Wallet flag is already set to %s: %s", value ? "true" : "false", flag_str)); } res.pushKV("flag_name", flag_str); res.pushKV("flag_state", value); if (value) { pwallet->SetWalletFlag(flag); } else { pwallet->UnsetWalletFlag(flag); } if (flag && value && WALLET_FLAG_CAVEATS.count(flag)) { res.pushKV("warnings", WALLET_FLAG_CAVEATS.at(flag)); } return res; }, }; } static RPCHelpMan createwallet() { return RPCHelpMan{ "createwallet", "\nCreates and loads a new wallet.\n", { {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name for the new wallet. If this is a path, the wallet will be created at the path location."}, {"disable_private_keys", RPCArg::Type::BOOL, RPCArg::Default{false}, "Disable the possibility of private keys (only watchonlys are possible in this mode)."}, {"blank", RPCArg::Type::BOOL, RPCArg::Default{false}, "Create a blank wallet. A blank wallet has no keys or HD seed. One can be set using sethdseed."}, {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Encrypt the wallet with this passphrase."}, {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{false}, "Keep track of coin reuse, and treat dirty and clean coins differently with privacy considerations in mind."}, {"descriptors", RPCArg::Type::BOOL, RPCArg::Default{true}, "Create a native descriptor wallet. The wallet will use descriptors internally to handle address creation." " Setting to \"false\" will create a legacy wallet; This is only possible with the -deprecatedrpc=create_bdb setting because, the legacy wallet type is being deprecated and" " support for creating and opening legacy wallets will be removed in the future."}, {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."}, {"external_signer", RPCArg::Type::BOOL, RPCArg::Default{false}, "Use an external signer such as a hardware wallet. Requires -signer to be configured. Wallet creation will fail if keys cannot be fetched. Requires disable_private_keys and descriptors set to true."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "name", "The wallet name if created successfully. If the wallet was created using a full path, the wallet_name will be the full path."}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to creating and loading the wallet.", { {RPCResult::Type::STR, "", ""}, }}, } }, RPCExamples{ HelpExampleCli("createwallet", "\"testwallet\"") + HelpExampleRpc("createwallet", "\"testwallet\"") + HelpExampleCliNamed("createwallet", {{"wallet_name", "descriptors"}, {"avoid_reuse", true}, {"descriptors", true}, {"load_on_startup", true}}) + HelpExampleRpcNamed("createwallet", {{"wallet_name", "descriptors"}, {"avoid_reuse", true}, {"descriptors", true}, {"load_on_startup", true}}) }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { WalletContext& context = EnsureWalletContext(request.context); uint64_t flags = 0; if (!request.params[1].isNull() && request.params[1].get_bool()) { flags |= WALLET_FLAG_DISABLE_PRIVATE_KEYS; } if (!request.params[2].isNull() && request.params[2].get_bool()) { flags |= WALLET_FLAG_BLANK_WALLET; } SecureString passphrase; passphrase.reserve(100); std::vector<bilingual_str> warnings; if (!request.params[3].isNull()) { passphrase = std::string_view{request.params[3].get_str()}; if (passphrase.empty()) { // Empty string means unencrypted warnings.emplace_back(Untranslated("Empty string given as passphrase, wallet will not be encrypted.")); } } if (!request.params[4].isNull() && request.params[4].get_bool()) { flags |= WALLET_FLAG_AVOID_REUSE; } if (self.Arg<bool>(5)) { #ifndef USE_SQLITE throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without sqlite support (required for descriptor wallets)"); #endif flags |= WALLET_FLAG_DESCRIPTORS; } else { if (!context.chain->rpcEnableDeprecated("create_bdb")) { throw JSONRPCError(RPC_WALLET_ERROR, "BDB wallet creation is deprecated and will be removed in a future release." " In this release it can be re-enabled temporarily with the -deprecatedrpc=create_bdb setting."); } } if (!request.params[7].isNull() && request.params[7].get_bool()) { #ifdef ENABLE_EXTERNAL_SIGNER flags |= WALLET_FLAG_EXTERNAL_SIGNER; #else throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without external signing support (required for external signing)"); #endif } #ifndef USE_BDB if (!(flags & WALLET_FLAG_DESCRIPTORS)) { throw JSONRPCError(RPC_WALLET_ERROR, "Compiled without bdb support (required for legacy wallets)"); } #endif DatabaseOptions options; DatabaseStatus status; ReadDatabaseArgs(*context.args, options); options.require_create = true; options.create_flags = flags; options.create_passphrase = passphrase; bilingual_str error; std::optional<bool> load_on_start = request.params[6].isNull() ? std::nullopt : std::optional<bool>(request.params[6].get_bool()); const std::shared_ptr<CWallet> wallet = CreateWallet(context, request.params[0].get_str(), load_on_start, options, status, error, warnings); if (!wallet) { RPCErrorCode code = status == DatabaseStatus::FAILED_ENCRYPT ? RPC_WALLET_ENCRYPTION_FAILED : RPC_WALLET_ERROR; throw JSONRPCError(code, error.original); } UniValue obj(UniValue::VOBJ); obj.pushKV("name", wallet->GetName()); PushWarnings(warnings, obj); return obj; }, }; } static RPCHelpMan unloadwallet() { return RPCHelpMan{"unloadwallet", "Unloads the wallet referenced by the request endpoint, otherwise unloads the wallet specified in the argument.\n" "Specifying the wallet name on a wallet endpoint is invalid.", { {"wallet_name", RPCArg::Type::STR, RPCArg::DefaultHint{"the wallet name from the RPC endpoint"}, "The name of the wallet to unload. If provided both here and in the RPC endpoint, the two must be identical."}, {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."}, }, RPCResult{RPCResult::Type::OBJ, "", "", { {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to unloading the wallet.", { {RPCResult::Type::STR, "", ""}, }}, }}, RPCExamples{ HelpExampleCli("unloadwallet", "wallet_name") + HelpExampleRpc("unloadwallet", "wallet_name") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::string wallet_name; if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) { if (!(request.params[0].isNull() || request.params[0].get_str() == wallet_name)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "RPC endpoint wallet and wallet_name parameter specify different wallets"); } } else { wallet_name = request.params[0].get_str(); } WalletContext& context = EnsureWalletContext(request.context); std::shared_ptr<CWallet> wallet = GetWallet(context, wallet_name); if (!wallet) { throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded"); } std::vector<bilingual_str> warnings; { WalletRescanReserver reserver(*wallet); if (!reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } // Release the "main" shared pointer and prevent further notifications. // Note that any attempt to load the same wallet would fail until the wallet // is destroyed (see CheckUniqueFileid). std::optional<bool> load_on_start{self.MaybeArg<bool>(1)}; if (!RemoveWallet(context, wallet, load_on_start, warnings)) { throw JSONRPCError(RPC_MISC_ERROR, "Requested wallet already unloaded"); } } UnloadWallet(std::move(wallet)); UniValue result(UniValue::VOBJ); PushWarnings(warnings, result); return result; }, }; } static RPCHelpMan sethdseed() { return RPCHelpMan{"sethdseed", "\nSet or generate a new HD wallet seed. Non-HD wallets will not be upgraded to being a HD wallet. Wallets that are already\n" "HD will have a new HD seed set so that new keys added to the keypool will be derived from this new seed.\n" "\nNote that you will need to MAKE A NEW BACKUP of your wallet after setting the HD wallet seed." + HELP_REQUIRING_PASSPHRASE + "Note: This command is only compatible with legacy wallets.\n", { {"newkeypool", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether to flush old unused addresses, including change addresses, from the keypool and regenerate it.\n" "If true, the next address from getnewaddress and change address from getrawchangeaddress will be from this new seed.\n" "If false, addresses (including change addresses if the wallet already had HD Chain Split enabled) from the existing\n" "keypool will be used until it has been depleted."}, {"seed", RPCArg::Type::STR, RPCArg::DefaultHint{"random seed"}, "The WIF private key to use as the new HD seed.\n" "The seed value can be retrieved using the dumpwallet command. It is the private key marked hdseed=1"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("sethdseed", "") + HelpExampleCli("sethdseed", "false") + HelpExampleCli("sethdseed", "true \"wifkey\"") + HelpExampleRpc("sethdseed", "true, \"wifkey\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet, true); if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set a HD seed to a wallet with private keys disabled"); } LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore); // Do not do anything to non-HD wallets if (!pwallet->CanSupportFeature(FEATURE_HD)) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set an HD seed on a non-HD wallet. Use the upgradewallet RPC in order to upgrade a non-HD wallet to HD"); } EnsureWalletIsUnlocked(*pwallet); bool flush_key_pool = true; if (!request.params[0].isNull()) { flush_key_pool = request.params[0].get_bool(); } CPubKey master_pub_key; if (request.params[1].isNull()) { master_pub_key = spk_man.GenerateNewSeed(); } else { CKey key = DecodeSecret(request.params[1].get_str()); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); } if (HaveKey(spk_man, key)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)"); } master_pub_key = spk_man.DeriveNewSeed(key); } spk_man.SetHDSeed(master_pub_key); if (flush_key_pool) spk_man.NewKeyPool(); return UniValue::VNULL; }, }; } static RPCHelpMan upgradewallet() { return RPCHelpMan{"upgradewallet", "\nUpgrade the wallet. Upgrades to the latest version if no version number is specified.\n" "New keys may be generated and a new wallet backup will need to be made.", { {"version", RPCArg::Type::NUM, RPCArg::Default{int{FEATURE_LATEST}}, "The version number to upgrade to. Default is the latest wallet version."} }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"}, {RPCResult::Type::NUM, "previous_version", "Version of wallet before this operation"}, {RPCResult::Type::NUM, "current_version", "Version of wallet after this operation"}, {RPCResult::Type::STR, "result", /*optional=*/true, "Description of result, if no error"}, {RPCResult::Type::STR, "error", /*optional=*/true, "Error message (if there is one)"} }, }, RPCExamples{ HelpExampleCli("upgradewallet", "169900") + HelpExampleRpc("upgradewallet", "169900") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; EnsureWalletIsUnlocked(*pwallet); int version = 0; if (!request.params[0].isNull()) { version = request.params[0].getInt<int>(); } bilingual_str error; const int previous_version{pwallet->GetVersion()}; const bool wallet_upgraded{pwallet->UpgradeWallet(version, error)}; const int current_version{pwallet->GetVersion()}; std::string result; if (wallet_upgraded) { if (previous_version == current_version) { result = "Already at latest version. Wallet version unchanged."; } else { result = strprintf("Wallet upgraded successfully from version %i to version %i.", previous_version, current_version); } } UniValue obj(UniValue::VOBJ); obj.pushKV("wallet_name", pwallet->GetName()); obj.pushKV("previous_version", previous_version); obj.pushKV("current_version", current_version); if (!result.empty()) { obj.pushKV("result", result); } else { CHECK_NONFATAL(!error.empty()); obj.pushKV("error", error.original); } return obj; }, }; } RPCHelpMan simulaterawtransaction() { return RPCHelpMan{"simulaterawtransaction", "\nCalculate the balance change resulting in the signing and broadcasting of the given transaction(s).\n", { {"rawtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "An array of hex strings of raw transactions.\n", { {"rawtx", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, ""}, }, }, {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", { {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses (see RPC importaddress)"}, }, }, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_AMOUNT, "balance_change", "The wallet balance change (negative means decrease)."}, } }, RPCExamples{ HelpExampleCli("simulaterawtransaction", "[\"myhex\"]") + HelpExampleRpc("simulaterawtransaction", "[\"myhex\"]") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> rpc_wallet = GetWalletForJSONRPCRequest(request); if (!rpc_wallet) return UniValue::VNULL; const CWallet& wallet = *rpc_wallet; LOCK(wallet.cs_wallet); UniValue include_watchonly(UniValue::VNULL); if (request.params[1].isObject()) { UniValue options = request.params[1]; RPCTypeCheckObj(options, { {"include_watchonly", UniValueType(UniValue::VBOOL)}, }, true, true); include_watchonly = options["include_watchonly"]; } isminefilter filter = ISMINE_SPENDABLE; if (ParseIncludeWatchonly(include_watchonly, wallet)) { filter |= ISMINE_WATCH_ONLY; } const auto& txs = request.params[0].get_array(); CAmount changes{0}; std::map<COutPoint, CAmount> new_utxos; // UTXO:s that were made available in transaction array std::set<COutPoint> spent; for (size_t i = 0; i < txs.size(); ++i) { CMutableTransaction mtx; if (!DecodeHexTx(mtx, txs[i].get_str(), /* try_no_witness */ true, /* try_witness */ true)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Transaction hex string decoding failure."); } // Fetch previous transactions (inputs) std::map<COutPoint, Coin> coins; for (const CTxIn& txin : mtx.vin) { coins[txin.prevout]; // Create empty map entry keyed by prevout. } wallet.chain().findCoins(coins); // Fetch debit; we are *spending* these; if the transaction is signed and // broadcast, we will lose everything in these for (const auto& txin : mtx.vin) { const auto& outpoint = txin.prevout; if (spent.count(outpoint)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction(s) are spending the same output more than once"); } if (new_utxos.count(outpoint)) { changes -= new_utxos.at(outpoint); new_utxos.erase(outpoint); } else { if (coins.at(outpoint).IsSpent()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "One or more transaction inputs are missing or have been spent already"); } changes -= wallet.GetDebit(txin, filter); } spent.insert(outpoint); } // Iterate over outputs; we are *receiving* these, if the wallet considers // them "mine"; if the transaction is signed and broadcast, we will receive // everything in these // Also populate new_utxos in case these are spent in later transactions const auto& hash = mtx.GetHash(); for (size_t i = 0; i < mtx.vout.size(); ++i) { const auto& txout = mtx.vout[i]; bool is_mine = 0 < (wallet.IsMine(txout) & filter); changes += new_utxos[COutPoint(hash, i)] = is_mine ? txout.nValue : 0; } } UniValue result(UniValue::VOBJ); result.pushKV("balance_change", ValueFromAmount(changes)); return result; } }; } static RPCHelpMan migratewallet() { return RPCHelpMan{"migratewallet", "EXPERIMENTAL warning: This call may not work as expected and may be changed in future releases\n" "\nMigrate the wallet to a descriptor wallet.\n" "A new wallet backup will need to be made.\n" "\nThe migration process will create a backup of the wallet before migrating. This backup\n" "file will be named <wallet name>-<timestamp>.legacy.bak and can be found in the directory\n" "for this wallet. In the event of an incorrect migration, the backup can be restored using restorewallet." "\nEncrypted wallets must have the passphrase provided as an argument to this call.", { {"wallet_name", RPCArg::Type::STR, RPCArg::DefaultHint{"the wallet name from the RPC endpoint"}, "The name of the wallet to migrate. If provided both here and in the RPC endpoint, the two must be identical."}, {"passphrase", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "The wallet passphrase"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "wallet_name", "The name of the primary migrated wallet"}, {RPCResult::Type::STR, "watchonly_name", /*optional=*/true, "The name of the migrated wallet containing the watchonly scripts"}, {RPCResult::Type::STR, "solvables_name", /*optional=*/true, "The name of the migrated wallet containing solvable but not watched scripts"}, {RPCResult::Type::STR, "backup_path", "The location of the backup of the original wallet"}, } }, RPCExamples{ HelpExampleCli("migratewallet", "") + HelpExampleRpc("migratewallet", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::string wallet_name; if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) { if (!(request.params[0].isNull() || request.params[0].get_str() == wallet_name)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "RPC endpoint wallet and wallet_name parameter specify different wallets"); } } else { if (request.params[0].isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Either RPC endpoint wallet or wallet_name parameter must be provided"); } wallet_name = request.params[0].get_str(); } SecureString wallet_pass; wallet_pass.reserve(100); if (!request.params[1].isNull()) { wallet_pass = std::string_view{request.params[1].get_str()}; } WalletContext& context = EnsureWalletContext(request.context); util::Result<MigrationResult> res = MigrateLegacyToDescriptor(wallet_name, wallet_pass, context); if (!res) { throw JSONRPCError(RPC_WALLET_ERROR, util::ErrorString(res).original); } UniValue r{UniValue::VOBJ}; r.pushKV("wallet_name", res->wallet_name); if (res->watchonly_wallet) { r.pushKV("watchonly_name", res->watchonly_wallet->GetName()); } if (res->solvables_wallet) { r.pushKV("solvables_name", res->solvables_wallet->GetName()); } r.pushKV("backup_path", res->backup_path.utf8string()); return r; }, }; } // addresses RPCHelpMan getaddressinfo(); RPCHelpMan getnewaddress(); RPCHelpMan getrawchangeaddress(); RPCHelpMan setlabel(); RPCHelpMan listaddressgroupings(); RPCHelpMan addmultisigaddress(); RPCHelpMan keypoolrefill(); RPCHelpMan newkeypool(); RPCHelpMan getaddressesbylabel(); RPCHelpMan listlabels(); #ifdef ENABLE_EXTERNAL_SIGNER RPCHelpMan walletdisplayaddress(); #endif // ENABLE_EXTERNAL_SIGNER // backup RPCHelpMan dumpprivkey(); RPCHelpMan importprivkey(); RPCHelpMan importaddress(); RPCHelpMan importpubkey(); RPCHelpMan dumpwallet(); RPCHelpMan importwallet(); RPCHelpMan importprunedfunds(); RPCHelpMan removeprunedfunds(); RPCHelpMan importmulti(); RPCHelpMan importdescriptors(); RPCHelpMan listdescriptors(); RPCHelpMan backupwallet(); RPCHelpMan restorewallet(); // coins RPCHelpMan getreceivedbyaddress(); RPCHelpMan getreceivedbylabel(); RPCHelpMan getbalance(); RPCHelpMan getunconfirmedbalance(); RPCHelpMan lockunspent(); RPCHelpMan listlockunspent(); RPCHelpMan getbalances(); RPCHelpMan listunspent(); // encryption RPCHelpMan walletpassphrase(); RPCHelpMan walletpassphrasechange(); RPCHelpMan walletlock(); RPCHelpMan encryptwallet(); // spend RPCHelpMan sendtoaddress(); RPCHelpMan sendmany(); RPCHelpMan settxfee(); RPCHelpMan fundrawtransaction(); RPCHelpMan bumpfee(); RPCHelpMan psbtbumpfee(); RPCHelpMan send(); RPCHelpMan sendall(); RPCHelpMan walletprocesspsbt(); RPCHelpMan walletcreatefundedpsbt(); RPCHelpMan signrawtransactionwithwallet(); // signmessage RPCHelpMan signmessage(); // transactions RPCHelpMan listreceivedbyaddress(); RPCHelpMan listreceivedbylabel(); RPCHelpMan listtransactions(); RPCHelpMan listsinceblock(); RPCHelpMan gettransaction(); RPCHelpMan abandontransaction(); RPCHelpMan rescanblockchain(); RPCHelpMan abortrescan(); Span<const CRPCCommand> GetWalletRPCCommands() { static const CRPCCommand commands[]{ {"rawtransactions", &fundrawtransaction}, {"wallet", &abandontransaction}, {"wallet", &abortrescan}, {"wallet", &addmultisigaddress}, {"wallet", &backupwallet}, {"wallet", &bumpfee}, {"wallet", &psbtbumpfee}, {"wallet", &createwallet}, {"wallet", &restorewallet}, {"wallet", &dumpprivkey}, {"wallet", &dumpwallet}, {"wallet", &encryptwallet}, {"wallet", &getaddressesbylabel}, {"wallet", &getaddressinfo}, {"wallet", &getbalance}, {"wallet", &getnewaddress}, {"wallet", &getrawchangeaddress}, {"wallet", &getreceivedbyaddress}, {"wallet", &getreceivedbylabel}, {"wallet", &gettransaction}, {"wallet", &getunconfirmedbalance}, {"wallet", &getbalances}, {"wallet", &getwalletinfo}, {"wallet", &importaddress}, {"wallet", &importdescriptors}, {"wallet", &importmulti}, {"wallet", &importprivkey}, {"wallet", &importprunedfunds}, {"wallet", &importpubkey}, {"wallet", &importwallet}, {"wallet", &keypoolrefill}, {"wallet", &listaddressgroupings}, {"wallet", &listdescriptors}, {"wallet", &listlabels}, {"wallet", &listlockunspent}, {"wallet", &listreceivedbyaddress}, {"wallet", &listreceivedbylabel}, {"wallet", &listsinceblock}, {"wallet", &listtransactions}, {"wallet", &listunspent}, {"wallet", &listwalletdir}, {"wallet", &listwallets}, {"wallet", &loadwallet}, {"wallet", &lockunspent}, {"wallet", &migratewallet}, {"wallet", &newkeypool}, {"wallet", &removeprunedfunds}, {"wallet", &rescanblockchain}, {"wallet", &send}, {"wallet", &sendmany}, {"wallet", &sendtoaddress}, {"wallet", &sethdseed}, {"wallet", &setlabel}, {"wallet", &settxfee}, {"wallet", &setwalletflag}, {"wallet", &signmessage}, {"wallet", &signrawtransactionwithwallet}, {"wallet", &simulaterawtransaction}, {"wallet", &sendall}, {"wallet", &unloadwallet}, {"wallet", &upgradewallet}, {"wallet", &walletcreatefundedpsbt}, #ifdef ENABLE_EXTERNAL_SIGNER {"wallet", &walletdisplayaddress}, #endif // ENABLE_EXTERNAL_SIGNER {"wallet", &walletlock}, {"wallet", &walletpassphrase}, {"wallet", &walletpassphrasechange}, {"wallet", &walletprocesspsbt}, }; return commands; } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/transactions.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <core_io.h> #include <key_io.h> #include <policy/rbf.h> #include <rpc/util.h> #include <util/vector.h> #include <wallet/receive.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> using interfaces::FoundBlock; namespace wallet { static void WalletTxToJSON(const CWallet& wallet, const CWalletTx& wtx, UniValue& entry) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { interfaces::Chain& chain = wallet.chain(); int confirms = wallet.GetTxDepthInMainChain(wtx); entry.pushKV("confirmations", confirms); if (wtx.IsCoinBase()) entry.pushKV("generated", true); if (auto* conf = wtx.state<TxStateConfirmed>()) { entry.pushKV("blockhash", conf->confirmed_block_hash.GetHex()); entry.pushKV("blockheight", conf->confirmed_block_height); entry.pushKV("blockindex", conf->position_in_block); int64_t block_time; CHECK_NONFATAL(chain.findBlock(conf->confirmed_block_hash, FoundBlock().time(block_time))); entry.pushKV("blocktime", block_time); } else { entry.pushKV("trusted", CachedTxIsTrusted(wallet, wtx)); } uint256 hash = wtx.GetHash(); entry.pushKV("txid", hash.GetHex()); entry.pushKV("wtxid", wtx.GetWitnessHash().GetHex()); UniValue conflicts(UniValue::VARR); for (const uint256& conflict : wallet.GetTxConflicts(wtx)) conflicts.push_back(conflict.GetHex()); entry.pushKV("walletconflicts", conflicts); entry.pushKV("time", wtx.GetTxTime()); entry.pushKV("timereceived", int64_t{wtx.nTimeReceived}); // Add opt-in RBF status std::string rbfStatus = "no"; if (confirms <= 0) { RBFTransactionState rbfState = chain.isRBFOptIn(*wtx.tx); if (rbfState == RBFTransactionState::UNKNOWN) rbfStatus = "unknown"; else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125) rbfStatus = "yes"; } entry.pushKV("bip125-replaceable", rbfStatus); for (const std::pair<const std::string, std::string>& item : wtx.mapValue) entry.pushKV(item.first, item.second); } struct tallyitem { CAmount nAmount{0}; int nConf{std::numeric_limits<int>::max()}; std::vector<uint256> txids; bool fIsWatchonly{false}; tallyitem() = default; }; static UniValue ListReceived(const CWallet& wallet, const UniValue& params, const bool by_label, const bool include_immature_coinbase) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { // Minimum confirmations int nMinDepth = 1; if (!params[0].isNull()) nMinDepth = params[0].getInt<int>(); // Whether to include empty labels bool fIncludeEmpty = false; if (!params[1].isNull()) fIncludeEmpty = params[1].get_bool(); isminefilter filter = ISMINE_SPENDABLE; if (ParseIncludeWatchonly(params[2], wallet)) { filter |= ISMINE_WATCH_ONLY; } std::optional<CTxDestination> filtered_address{std::nullopt}; if (!by_label && !params[3].isNull() && !params[3].get_str().empty()) { if (!IsValidDestinationString(params[3].get_str())) { throw JSONRPCError(RPC_WALLET_ERROR, "address_filter parameter was invalid"); } filtered_address = DecodeDestination(params[3].get_str()); } // Tally std::map<CTxDestination, tallyitem> mapTally; for (const std::pair<const uint256, CWalletTx>& pairWtx : wallet.mapWallet) { const CWalletTx& wtx = pairWtx.second; int nDepth = wallet.GetTxDepthInMainChain(wtx); if (nDepth < nMinDepth) continue; // Coinbase with less than 1 confirmation is no longer in the main chain if ((wtx.IsCoinBase() && (nDepth < 1)) || (wallet.IsTxImmatureCoinBase(wtx) && !include_immature_coinbase)) { continue; } for (const CTxOut& txout : wtx.tx->vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) continue; if (filtered_address && !(filtered_address == address)) { continue; } isminefilter mine = wallet.IsMine(address); if (!(mine & filter)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = std::min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); if (mine & ISMINE_WATCH_ONLY) item.fIsWatchonly = true; } } // Reply UniValue ret(UniValue::VARR); std::map<std::string, tallyitem> label_tally; const auto& func = [&](const CTxDestination& address, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) { if (is_change) return; // no change addresses auto it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) return; CAmount nAmount = 0; int nConf = std::numeric_limits<int>::max(); bool fIsWatchonly = false; if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; fIsWatchonly = (*it).second.fIsWatchonly; } if (by_label) { tallyitem& _item = label_tally[label]; _item.nAmount += nAmount; _item.nConf = std::min(_item.nConf, nConf); _item.fIsWatchonly = fIsWatchonly; } else { UniValue obj(UniValue::VOBJ); if (fIsWatchonly) obj.pushKV("involvesWatchonly", true); obj.pushKV("address", EncodeDestination(address)); obj.pushKV("amount", ValueFromAmount(nAmount)); obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)); obj.pushKV("label", label); UniValue transactions(UniValue::VARR); if (it != mapTally.end()) { for (const uint256& _item : (*it).second.txids) { transactions.push_back(_item.GetHex()); } } obj.pushKV("txids", transactions); ret.push_back(obj); } }; if (filtered_address) { const auto& entry = wallet.FindAddressBookEntry(*filtered_address, /*allow_change=*/false); if (entry) func(*filtered_address, entry->GetLabel(), entry->IsChange(), entry->purpose); } else { // No filtered addr, walk-through the addressbook entry wallet.ForEachAddrBookEntry(func); } if (by_label) { for (const auto& entry : label_tally) { CAmount nAmount = entry.second.nAmount; int nConf = entry.second.nConf; UniValue obj(UniValue::VOBJ); if (entry.second.fIsWatchonly) obj.pushKV("involvesWatchonly", true); obj.pushKV("amount", ValueFromAmount(nAmount)); obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)); obj.pushKV("label", entry.first); ret.push_back(obj); } } return ret; } RPCHelpMan listreceivedbyaddress() { return RPCHelpMan{"listreceivedbyaddress", "\nList balances by receiving address.\n", { {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "The minimum number of confirmations before payments are included."}, {"include_empty", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to include addresses that haven't received any payments."}, {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses (see 'importaddress')"}, {"address_filter", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "If present and non-empty, only return information on this address."}, {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."}, }, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction"}, {RPCResult::Type::STR, "address", "The receiving address"}, {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received by the address"}, {RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"}, {RPCResult::Type::STR, "label", "The label of the receiving address. The default label is \"\""}, {RPCResult::Type::ARR, "txids", "", { {RPCResult::Type::STR_HEX, "txid", "The ids of transactions received with the address"}, }}, }}, } }, RPCExamples{ HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 true") + HelpExampleCli("listreceivedbyaddress", "6 true true \"\" true") + HelpExampleRpc("listreceivedbyaddress", "6, true, true") + HelpExampleRpc("listreceivedbyaddress", "6, true, true, \"" + EXAMPLE_ADDRESS[0] + "\", true") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); const bool include_immature_coinbase{request.params[4].isNull() ? false : request.params[4].get_bool()}; LOCK(pwallet->cs_wallet); return ListReceived(*pwallet, request.params, false, include_immature_coinbase); }, }; } RPCHelpMan listreceivedbylabel() { return RPCHelpMan{"listreceivedbylabel", "\nList received transactions by label.\n", { {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "The minimum number of confirmations before payments are included."}, {"include_empty", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to include labels that haven't received any payments."}, {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses (see 'importaddress')"}, {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."}, }, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction"}, {RPCResult::Type::STR_AMOUNT, "amount", "The total amount received by addresses with this label"}, {RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"}, {RPCResult::Type::STR, "label", "The label of the receiving address. The default label is \"\""}, }}, } }, RPCExamples{ HelpExampleCli("listreceivedbylabel", "") + HelpExampleCli("listreceivedbylabel", "6 true") + HelpExampleRpc("listreceivedbylabel", "6, true, true, true") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); const bool include_immature_coinbase{request.params[3].isNull() ? false : request.params[3].get_bool()}; LOCK(pwallet->cs_wallet); return ListReceived(*pwallet, request.params, true, include_immature_coinbase); }, }; } static void MaybePushAddress(UniValue & entry, const CTxDestination &dest) { if (IsValidDestination(dest)) { entry.pushKV("address", EncodeDestination(dest)); } } /** * List transactions based on the given criteria. * * @param wallet The wallet. * @param wtx The wallet transaction. * @param nMinDepth The minimum confirmation depth. * @param fLong Whether to include the JSON version of the transaction. * @param ret The vector into which the result is stored. * @param filter_ismine The "is mine" filter flags. * @param filter_label Optional label string to filter incoming transactions. */ template <class Vec> static void ListTransactions(const CWallet& wallet, const CWalletTx& wtx, int nMinDepth, bool fLong, Vec& ret, const isminefilter& filter_ismine, const std::optional<std::string>& filter_label, bool include_change = false) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { CAmount nFee; std::list<COutputEntry> listReceived; std::list<COutputEntry> listSent; CachedTxGetAmounts(wallet, wtx, listReceived, listSent, nFee, filter_ismine, include_change); bool involvesWatchonly = CachedTxIsFromMe(wallet, wtx, ISMINE_WATCH_ONLY); // Sent if (!filter_label.has_value()) { for (const COutputEntry& s : listSent) { UniValue entry(UniValue::VOBJ); if (involvesWatchonly || (wallet.IsMine(s.destination) & ISMINE_WATCH_ONLY)) { entry.pushKV("involvesWatchonly", true); } MaybePushAddress(entry, s.destination); entry.pushKV("category", "send"); entry.pushKV("amount", ValueFromAmount(-s.amount)); const auto* address_book_entry = wallet.FindAddressBookEntry(s.destination); if (address_book_entry) { entry.pushKV("label", address_book_entry->GetLabel()); } entry.pushKV("vout", s.vout); entry.pushKV("fee", ValueFromAmount(-nFee)); if (fLong) WalletTxToJSON(wallet, wtx, entry); entry.pushKV("abandoned", wtx.isAbandoned()); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wallet.GetTxDepthInMainChain(wtx) >= nMinDepth) { for (const COutputEntry& r : listReceived) { std::string label; const auto* address_book_entry = wallet.FindAddressBookEntry(r.destination); if (address_book_entry) { label = address_book_entry->GetLabel(); } if (filter_label.has_value() && label != filter_label.value()) { continue; } UniValue entry(UniValue::VOBJ); if (involvesWatchonly || (wallet.IsMine(r.destination) & ISMINE_WATCH_ONLY)) { entry.pushKV("involvesWatchonly", true); } MaybePushAddress(entry, r.destination); PushParentDescriptors(wallet, wtx.tx->vout.at(r.vout).scriptPubKey, entry); if (wtx.IsCoinBase()) { if (wallet.GetTxDepthInMainChain(wtx) < 1) entry.pushKV("category", "orphan"); else if (wallet.IsTxImmatureCoinBase(wtx)) entry.pushKV("category", "immature"); else entry.pushKV("category", "generate"); } else { entry.pushKV("category", "receive"); } entry.pushKV("amount", ValueFromAmount(r.amount)); if (address_book_entry) { entry.pushKV("label", label); } entry.pushKV("vout", r.vout); entry.pushKV("abandoned", wtx.isAbandoned()); if (fLong) WalletTxToJSON(wallet, wtx, entry); ret.push_back(entry); } } } static std::vector<RPCResult> TransactionDescriptionString() { return{{RPCResult::Type::NUM, "confirmations", "The number of confirmations for the transaction. Negative confirmations means the\n" "transaction conflicted that many blocks ago."}, {RPCResult::Type::BOOL, "generated", /*optional=*/true, "Only present if the transaction's only input is a coinbase one."}, {RPCResult::Type::BOOL, "trusted", /*optional=*/true, "Whether we consider the transaction to be trusted and safe to spend from.\n" "Only present when the transaction has 0 confirmations (or negative confirmations, if conflicted)."}, {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The block hash containing the transaction."}, {RPCResult::Type::NUM, "blockheight", /*optional=*/true, "The block height containing the transaction."}, {RPCResult::Type::NUM, "blockindex", /*optional=*/true, "The index of the transaction in the block that includes it."}, {RPCResult::Type::NUM_TIME, "blocktime", /*optional=*/true, "The block time expressed in " + UNIX_EPOCH_TIME + "."}, {RPCResult::Type::STR_HEX, "txid", "The transaction id."}, {RPCResult::Type::STR_HEX, "wtxid", "The hash of serialized transaction, including witness data."}, {RPCResult::Type::ARR, "walletconflicts", "Conflicting transaction ids.", { {RPCResult::Type::STR_HEX, "txid", "The transaction id."}, }}, {RPCResult::Type::STR_HEX, "replaced_by_txid", /*optional=*/true, "The txid if this tx was replaced."}, {RPCResult::Type::STR_HEX, "replaces_txid", /*optional=*/true, "The txid if the tx replaces one."}, {RPCResult::Type::STR, "to", /*optional=*/true, "If a comment to is associated with the transaction."}, {RPCResult::Type::NUM_TIME, "time", "The transaction time expressed in " + UNIX_EPOCH_TIME + "."}, {RPCResult::Type::NUM_TIME, "timereceived", "The time received expressed in " + UNIX_EPOCH_TIME + "."}, {RPCResult::Type::STR, "comment", /*optional=*/true, "If a comment is associated with the transaction, only present if not empty."}, {RPCResult::Type::STR, "bip125-replaceable", "(\"yes|no|unknown\") Whether this transaction signals BIP125 replaceability or has an unconfirmed ancestor signaling BIP125 replaceability.\n" "May be unknown for unconfirmed transactions not in the mempool because their unconfirmed ancestors are unknown."}, {RPCResult::Type::ARR, "parent_descs", /*optional=*/true, "Only if 'category' is 'received'. List of parent descriptors for the scriptPubKey of this coin.", { {RPCResult::Type::STR, "desc", "The descriptor string."}, }}, }; } RPCHelpMan listtransactions() { return RPCHelpMan{"listtransactions", "\nIf a label name is provided, this will return only incoming transactions paying to addresses with the specified label.\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions.\n", { {"label|dummy", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "If set, should be a valid label name to return only incoming transactions\n" "with the specified label, or \"*\" to disable filtering and return all transactions."}, {"count", RPCArg::Type::NUM, RPCArg::Default{10}, "The number of transactions to return"}, {"skip", RPCArg::Type::NUM, RPCArg::Default{0}, "The number of transactions to skip"}, {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Include transactions to watch-only addresses (see 'importaddress')"}, }, RPCResult{ RPCResult::Type::ARR, "", "", { {RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>( { {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction."}, {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address of the transaction (not returned if the output does not have an address, e.g. OP_RETURN null data)."}, {RPCResult::Type::STR, "category", "The transaction category.\n" "\"send\" Transactions sent.\n" "\"receive\" Non-coinbase transactions received.\n" "\"generate\" Coinbase transactions received with more than 100 confirmations.\n" "\"immature\" Coinbase transactions received with 100 or fewer confirmations.\n" "\"orphan\" Orphaned coinbase transactions received."}, {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n" "for all other categories"}, {RPCResult::Type::STR, "label", /*optional=*/true, "A comment for the address/transaction, if any"}, {RPCResult::Type::NUM, "vout", "the vout value"}, {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n" "'send' category of transactions."}, }, TransactionDescriptionString()), { {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable)."}, })}, } }, RPCExamples{ "\nList the most recent 10 transactions in the systems\n" + HelpExampleCli("listtransactions", "") + "\nList transactions 100 to 120\n" + HelpExampleCli("listtransactions", "\"*\" 20 100") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("listtransactions", "\"*\", 20, 100") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); std::optional<std::string> filter_label; if (!request.params[0].isNull() && request.params[0].get_str() != "*") { filter_label.emplace(LabelFromValue(request.params[0])); if (filter_label.value().empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Label argument must be a valid label name or \"*\"."); } } int nCount = 10; if (!request.params[1].isNull()) nCount = request.params[1].getInt<int>(); int nFrom = 0; if (!request.params[2].isNull()) nFrom = request.params[2].getInt<int>(); isminefilter filter = ISMINE_SPENDABLE; if (ParseIncludeWatchonly(request.params[3], *pwallet)) { filter |= ISMINE_WATCH_ONLY; } if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); std::vector<UniValue> ret; { LOCK(pwallet->cs_wallet); const CWallet::TxItems & txOrdered = pwallet->wtxOrdered; // iterate backwards until we have nCount items to return: for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second; ListTransactions(*pwallet, *pwtx, 0, true, ret, filter, filter_label); if ((int)ret.size() >= (nCount+nFrom)) break; } } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; auto txs_rev_it{std::make_move_iterator(ret.rend())}; UniValue result{UniValue::VARR}; result.push_backV(txs_rev_it - nFrom - nCount, txs_rev_it - nFrom); // Return oldest to newest return result; }, }; } RPCHelpMan listsinceblock() { return RPCHelpMan{"listsinceblock", "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted.\n" "If \"blockhash\" is no longer a part of the main chain, transactions from the fork point onward are included.\n" "Additionally, if include_removed is set, transactions affecting the wallet which were removed are returned in the \"removed\" array.\n", { {"blockhash", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "If set, the block hash to list transactions since, otherwise list all transactions."}, {"target_confirmations", RPCArg::Type::NUM, RPCArg::Default{1}, "Return the nth block hash from the main chain. e.g. 1 would mean the best block hash. Note: this is not used as a filter, but only affects [lastblock] in the return value"}, {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Include transactions to watch-only addresses (see 'importaddress')"}, {"include_removed", RPCArg::Type::BOOL, RPCArg::Default{true}, "Show transactions that were removed due to a reorg in the \"removed\" array\n" "(not guaranteed to work on pruned nodes)"}, {"include_change", RPCArg::Type::BOOL, RPCArg::Default{false}, "Also add entries for change outputs.\n"}, {"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Return only incoming transactions paying to addresses with the specified label.\n"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::ARR, "transactions", "", { {RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>( { {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction."}, {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address of the transaction (not returned if the output does not have an address, e.g. OP_RETURN null data)."}, {RPCResult::Type::STR, "category", "The transaction category.\n" "\"send\" Transactions sent.\n" "\"receive\" Non-coinbase transactions received.\n" "\"generate\" Coinbase transactions received with more than 100 confirmations.\n" "\"immature\" Coinbase transactions received with 100 or fewer confirmations.\n" "\"orphan\" Orphaned coinbase transactions received."}, {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n" "for all other categories"}, {RPCResult::Type::NUM, "vout", "the vout value"}, {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n" "'send' category of transactions."}, }, TransactionDescriptionString()), { {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable)."}, {RPCResult::Type::STR, "label", /*optional=*/true, "A comment for the address/transaction, if any"}, })}, }}, {RPCResult::Type::ARR, "removed", /*optional=*/true, "<structure is the same as \"transactions\" above, only present if include_removed=true>\n" "Note: transactions that were re-added in the active chain will appear as-is in this array, and may thus have a positive confirmation count." , {{RPCResult::Type::ELISION, "", ""},}}, {RPCResult::Type::STR_HEX, "lastblock", "The hash of the block (target_confirmations-1) from the best block on the main chain, or the genesis hash if the referenced block does not exist yet. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones"}, } }, RPCExamples{ HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6") + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; const CWallet& wallet = *pwallet; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); LOCK(wallet.cs_wallet); std::optional<int> height; // Height of the specified block or the common ancestor, if the block provided was in a deactivated chain. std::optional<int> altheight; // Height of the specified block, even if it's in a deactivated chain. int target_confirms = 1; isminefilter filter = ISMINE_SPENDABLE; uint256 blockId; if (!request.params[0].isNull() && !request.params[0].get_str().empty()) { blockId = ParseHashV(request.params[0], "blockhash"); height = int{}; altheight = int{}; if (!wallet.chain().findCommonAncestor(blockId, wallet.GetLastBlockHash(), /*ancestor_out=*/FoundBlock().height(*height), /*block1_out=*/FoundBlock().height(*altheight))) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } } if (!request.params[1].isNull()) { target_confirms = request.params[1].getInt<int>(); if (target_confirms < 1) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } } if (ParseIncludeWatchonly(request.params[2], wallet)) { filter |= ISMINE_WATCH_ONLY; } bool include_removed = (request.params[3].isNull() || request.params[3].get_bool()); bool include_change = (!request.params[4].isNull() && request.params[4].get_bool()); // Only set it if 'label' was provided. std::optional<std::string> filter_label; if (!request.params[5].isNull()) filter_label.emplace(LabelFromValue(request.params[5])); int depth = height ? wallet.GetLastBlockHeight() + 1 - *height : -1; UniValue transactions(UniValue::VARR); for (const std::pair<const uint256, CWalletTx>& pairWtx : wallet.mapWallet) { const CWalletTx& tx = pairWtx.second; if (depth == -1 || abs(wallet.GetTxDepthInMainChain(tx)) < depth) { ListTransactions(wallet, tx, 0, true, transactions, filter, filter_label, include_change); } } // when a reorg'd block is requested, we also list any relevant transactions // in the blocks of the chain that was detached UniValue removed(UniValue::VARR); while (include_removed && altheight && *altheight > *height) { CBlock block; if (!wallet.chain().findBlock(blockId, FoundBlock().data(block)) || block.IsNull()) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); } for (const CTransactionRef& tx : block.vtx) { auto it = wallet.mapWallet.find(tx->GetHash()); if (it != wallet.mapWallet.end()) { // We want all transactions regardless of confirmation count to appear here, // even negative confirmation ones, hence the big negative. ListTransactions(wallet, it->second, -100000000, true, removed, filter, filter_label, include_change); } } blockId = block.hashPrevBlock; --*altheight; } uint256 lastblock; target_confirms = std::min(target_confirms, wallet.GetLastBlockHeight() + 1); CHECK_NONFATAL(wallet.chain().findAncestorByHeight(wallet.GetLastBlockHash(), wallet.GetLastBlockHeight() + 1 - target_confirms, FoundBlock().hash(lastblock))); UniValue ret(UniValue::VOBJ); ret.pushKV("transactions", transactions); if (include_removed) ret.pushKV("removed", removed); ret.pushKV("lastblock", lastblock.GetHex()); return ret; }, }; } RPCHelpMan gettransaction() { return RPCHelpMan{"gettransaction", "\nGet detailed information about in-wallet transaction <txid>\n", { {"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"}, {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses in balance calculation and details[]"}, {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to include a `decoded` field containing the decoded transaction (equivalent to RPC decoderawtransaction)"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>( { {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT}, {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n" "'send' category of transactions."}, }, TransactionDescriptionString()), { {RPCResult::Type::ARR, "details", "", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction."}, {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address involved in the transaction."}, {RPCResult::Type::STR, "category", "The transaction category.\n" "\"send\" Transactions sent.\n" "\"receive\" Non-coinbase transactions received.\n" "\"generate\" Coinbase transactions received with more than 100 confirmations.\n" "\"immature\" Coinbase transactions received with 100 or fewer confirmations.\n" "\"orphan\" Orphaned coinbase transactions received."}, {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT}, {RPCResult::Type::STR, "label", /*optional=*/true, "A comment for the address/transaction, if any"}, {RPCResult::Type::NUM, "vout", "the vout value"}, {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" "'send' category of transactions."}, {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable)."}, {RPCResult::Type::ARR, "parent_descs", /*optional=*/true, "Only if 'category' is 'received'. List of parent descriptors for the scriptPubKey of this coin.", { {RPCResult::Type::STR, "desc", "The descriptor string."}, }}, }}, }}, {RPCResult::Type::STR_HEX, "hex", "Raw data for transaction"}, {RPCResult::Type::OBJ, "decoded", /*optional=*/true, "The decoded transaction (only present when `verbose` is passed)", { {RPCResult::Type::ELISION, "", "Equivalent to the RPC decoderawtransaction method, or the RPC getrawtransaction method when `verbose` is passed."}, }}, RESULT_LAST_PROCESSED_BLOCK, }) }, RPCExamples{ HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" false true") + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); uint256 hash(ParseHashV(request.params[0], "txid")); isminefilter filter = ISMINE_SPENDABLE; if (ParseIncludeWatchonly(request.params[1], *pwallet)) { filter |= ISMINE_WATCH_ONLY; } bool verbose = request.params[2].isNull() ? false : request.params[2].get_bool(); UniValue entry(UniValue::VOBJ); auto it = pwallet->mapWallet.find(hash); if (it == pwallet->mapWallet.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); } const CWalletTx& wtx = it->second; CAmount nCredit = CachedTxGetCredit(*pwallet, wtx, filter); CAmount nDebit = CachedTxGetDebit(*pwallet, wtx, filter); CAmount nNet = nCredit - nDebit; CAmount nFee = (CachedTxIsFromMe(*pwallet, wtx, filter) ? wtx.tx->GetValueOut() - nDebit : 0); entry.pushKV("amount", ValueFromAmount(nNet - nFee)); if (CachedTxIsFromMe(*pwallet, wtx, filter)) entry.pushKV("fee", ValueFromAmount(nFee)); WalletTxToJSON(*pwallet, wtx, entry); UniValue details(UniValue::VARR); ListTransactions(*pwallet, wtx, 0, false, details, filter, /*filter_label=*/std::nullopt); entry.pushKV("details", details); std::string strHex = EncodeHexTx(*wtx.tx, pwallet->chain().rpcSerializationWithoutWitness()); entry.pushKV("hex", strHex); if (verbose) { UniValue decoded(UniValue::VOBJ); TxToUniv(*wtx.tx, /*block_hash=*/uint256(), /*entry=*/decoded, /*include_hex=*/false); entry.pushKV("decoded", decoded); } AppendLastProcessedBlock(entry, *pwallet); return entry; }, }; } RPCHelpMan abandontransaction() { return RPCHelpMan{"abandontransaction", "\nMark in-wallet transaction <txid> as abandoned\n" "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n" "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n" "It only works on transactions which are not included in a block and are not currently in the mempool.\n" "It has no effect on transactions which are already abandoned.\n", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); uint256 hash(ParseHashV(request.params[0], "txid")); if (!pwallet->mapWallet.count(hash)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); } if (!pwallet->AbandonTransaction(hash)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment"); } return UniValue::VNULL; }, }; } RPCHelpMan rescanblockchain() { return RPCHelpMan{"rescanblockchain", "\nRescan the local blockchain for wallet related transactions.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n" "The rescan is significantly faster when used on a descriptor wallet\n" "and block filters are available (using startup option \"-blockfilterindex=1\").\n", { {"start_height", RPCArg::Type::NUM, RPCArg::Default{0}, "block height where the rescan should start"}, {"stop_height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "the last block height that should be scanned. If none is provided it will rescan up to the tip at return time of this call."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::NUM, "start_height", "The block height where the rescan started (the requested height or 0)"}, {RPCResult::Type::NUM, "stop_height", "The height of the last rescanned block. May be null in rare cases if there was a reorg and the call didn't scan any blocks because they were already scanned in the background."}, } }, RPCExamples{ HelpExampleCli("rescanblockchain", "100000 120000") + HelpExampleRpc("rescanblockchain", "100000, 120000") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); WalletRescanReserver reserver(*pwallet); if (!reserver.reserve(/*with_passphrase=*/true)) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int start_height = 0; std::optional<int> stop_height; uint256 start_block; LOCK(pwallet->m_relock_mutex); { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); int tip_height = pwallet->GetLastBlockHeight(); if (!request.params[0].isNull()) { start_height = request.params[0].getInt<int>(); if (start_height < 0 || start_height > tip_height) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height"); } } if (!request.params[1].isNull()) { stop_height = request.params[1].getInt<int>(); if (*stop_height < 0 || *stop_height > tip_height) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height"); } else if (*stop_height < start_height) { throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater than start_height"); } } // We can't rescan beyond non-pruned blocks, stop and throw an error if (!pwallet->chain().hasBlocks(pwallet->GetLastBlockHash(), start_height, stop_height)) { throw JSONRPCError(RPC_MISC_ERROR, "Can't rescan beyond pruned data. Use RPC call getblockchaininfo to determine your pruned height."); } CHECK_NONFATAL(pwallet->chain().findAncestorByHeight(pwallet->GetLastBlockHash(), start_height, FoundBlock().hash(start_block))); } CWallet::ScanResult result = pwallet->ScanForWalletTransactions(start_block, start_height, stop_height, reserver, /*fUpdate=*/true, /*save_progress=*/false); switch (result.status) { case CWallet::ScanResult::SUCCESS: break; case CWallet::ScanResult::FAILURE: throw JSONRPCError(RPC_MISC_ERROR, "Rescan failed. Potentially corrupted data files."); case CWallet::ScanResult::USER_ABORT: throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted."); // no default case, so the compiler can warn about missing cases } UniValue response(UniValue::VOBJ); response.pushKV("start_height", start_height); response.pushKV("stop_height", result.last_scanned_height ? *result.last_scanned_height : UniValue()); return response; }, }; } RPCHelpMan abortrescan() { return RPCHelpMan{"abortrescan", "\nStops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n", {}, RPCResult{RPCResult::Type::BOOL, "", "Whether the abort was successful"}, RPCExamples{ "\nImport a private key\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nAbort the running wallet rescan\n" + HelpExampleCli("abortrescan", "") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("abortrescan", "") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false; pwallet->AbortRescan(); return true; }, }; } } // namespace wallet
0
bitcoin/src/wallet
bitcoin/src/wallet/rpc/spend.cpp
// Copyright (c) 2011-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/validation.h> #include <core_io.h> #include <key_io.h> #include <policy/policy.h> #include <rpc/rawtransaction_util.h> #include <rpc/util.h> #include <script/script.h> #include <util/fees.h> #include <util/rbf.h> #include <util/translation.h> #include <util/vector.h> #include <wallet/coincontrol.h> #include <wallet/feebumper.h> #include <wallet/fees.h> #include <wallet/rpc/util.h> #include <wallet/spend.h> #include <wallet/wallet.h> #include <univalue.h> namespace wallet { static void ParseRecipients(const UniValue& address_amounts, const UniValue& subtract_fee_outputs, std::vector<CRecipient>& recipients) { std::set<CTxDestination> destinations; int i = 0; for (const std::string& address: address_amounts.getKeys()) { CTxDestination dest = DecodeDestination(address); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + address); } if (destinations.count(dest)) { throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + address); } destinations.insert(dest); CAmount amount = AmountFromValue(address_amounts[i++]); bool subtract_fee = false; for (unsigned int idx = 0; idx < subtract_fee_outputs.size(); idx++) { const UniValue& addr = subtract_fee_outputs[idx]; if (addr.get_str() == address) { subtract_fee = true; } } CRecipient recipient = {dest, amount, subtract_fee}; recipients.push_back(recipient); } } static void InterpretFeeEstimationInstructions(const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, UniValue& options) { if (options.exists("conf_target") || options.exists("estimate_mode")) { if (!conf_target.isNull() || !estimate_mode.isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass conf_target and estimate_mode either as arguments or in the options object, but not both"); } } else { options.pushKV("conf_target", conf_target); options.pushKV("estimate_mode", estimate_mode); } if (options.exists("fee_rate")) { if (!fee_rate.isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass the fee_rate either as an argument, or in the options object, but not both"); } } else { options.pushKV("fee_rate", fee_rate); } if (!options["conf_target"].isNull() && (options["estimate_mode"].isNull() || (options["estimate_mode"].get_str() == "unset"))) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Specify estimate_mode"); } } static UniValue FinishTransaction(const std::shared_ptr<CWallet> pwallet, const UniValue& options, const CMutableTransaction& rawTx) { // Make a blank psbt PartiallySignedTransaction psbtx(rawTx); // First fill transaction with our data without signing, // so external signers are not asked to sign more than once. bool complete; pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, /*sign=*/false, /*bip32derivs=*/true); const TransactionError err{pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, /*sign=*/true, /*bip32derivs=*/false)}; if (err != TransactionError::OK) { throw JSONRPCTransactionError(err); } CMutableTransaction mtx; complete = FinalizeAndExtractPSBT(psbtx, mtx); UniValue result(UniValue::VOBJ); const bool psbt_opt_in{options.exists("psbt") && options["psbt"].get_bool()}; bool add_to_wallet{options.exists("add_to_wallet") ? options["add_to_wallet"].get_bool() : true}; if (psbt_opt_in || !complete || !add_to_wallet) { // Serialize the PSBT DataStream ssTx{}; ssTx << psbtx; result.pushKV("psbt", EncodeBase64(ssTx.str())); } if (complete) { std::string hex{EncodeHexTx(CTransaction(mtx))}; CTransactionRef tx(MakeTransactionRef(std::move(mtx))); result.pushKV("txid", tx->GetHash().GetHex()); if (add_to_wallet && !psbt_opt_in) { pwallet->CommitTransaction(tx, {}, /*orderForm=*/{}); } else { result.pushKV("hex", hex); } } result.pushKV("complete", complete); return result; } static void PreventOutdatedOptions(const UniValue& options) { if (options.exists("feeRate")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Use fee_rate (" + CURRENCY_ATOM + "/vB) instead of feeRate"); } if (options.exists("changeAddress")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_address instead of changeAddress"); } if (options.exists("changePosition")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_position instead of changePosition"); } if (options.exists("includeWatching")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Use include_watching instead of includeWatching"); } if (options.exists("lockUnspents")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Use lock_unspents instead of lockUnspents"); } if (options.exists("subtractFeeFromOutputs")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Use subtract_fee_from_outputs instead of subtractFeeFromOutputs"); } } UniValue SendMoney(CWallet& wallet, const CCoinControl &coin_control, std::vector<CRecipient> &recipients, mapValue_t map_value, bool verbose) { EnsureWalletIsUnlocked(wallet); // This function is only used by sendtoaddress and sendmany. // This should always try to sign, if we don't have private keys, don't try to do anything here. if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet"); } // Shuffle recipient list std::shuffle(recipients.begin(), recipients.end(), FastRandomContext()); // Send auto res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, coin_control, true); if (!res) { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, util::ErrorString(res).original); } const CTransactionRef& tx = res->tx; wallet.CommitTransaction(tx, std::move(map_value), /*orderForm=*/{}); if (verbose) { UniValue entry(UniValue::VOBJ); entry.pushKV("txid", tx->GetHash().GetHex()); entry.pushKV("fee_reason", StringForFeeReason(res->fee_calc.reason)); return entry; } return tx->GetHash().GetHex(); } /** * Update coin control with fee estimation based on the given parameters * * @param[in] wallet Wallet reference * @param[in,out] cc Coin control to be updated * @param[in] conf_target UniValue integer; confirmation target in blocks, values between 1 and 1008 are valid per policy/fees.h; * @param[in] estimate_mode UniValue string; fee estimation mode, valid values are "unset", "economical" or "conservative"; * @param[in] fee_rate UniValue real; fee rate in sat/vB; * if present, both conf_target and estimate_mode must either be null, or "unset" * @param[in] override_min_fee bool; whether to set fOverrideFeeRate to true to disable minimum fee rate checks and instead * verify only that fee_rate is greater than 0 * @throws a JSONRPCError if conf_target, estimate_mode, or fee_rate contain invalid values or are in conflict */ static void SetFeeEstimateMode(const CWallet& wallet, CCoinControl& cc, const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, bool override_min_fee) { if (!fee_rate.isNull()) { if (!conf_target.isNull()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and fee_rate. Please provide either a confirmation target in blocks for automatic fee estimation, or an explicit fee rate."); } if (!estimate_mode.isNull() && estimate_mode.get_str() != "unset") { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and fee_rate"); } // Fee rates in sat/vB cannot represent more than 3 significant digits. cc.m_feerate = CFeeRate{AmountFromValue(fee_rate, /*decimals=*/3)}; if (override_min_fee) cc.fOverrideFeeRate = true; // Default RBF to true for explicit fee_rate, if unset. if (!cc.m_signal_bip125_rbf) cc.m_signal_bip125_rbf = true; return; } if (!estimate_mode.isNull() && !FeeModeFromString(estimate_mode.get_str(), cc.m_fee_mode)) { throw JSONRPCError(RPC_INVALID_PARAMETER, InvalidEstimateModeErrorMessage()); } if (!conf_target.isNull()) { cc.m_confirm_target = ParseConfirmTarget(conf_target, wallet.chain().estimateMaxBlocks()); } } RPCHelpMan sendtoaddress() { return RPCHelpMan{"sendtoaddress", "\nSend an amount to a given address." + HELP_REQUIRING_PASSPHRASE, { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to send to."}, {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"}, {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment used to store what the transaction is for.\n" "This is not part of the transaction, just kept in your wallet."}, {"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment to store the name of the person or organization\n" "to which you're sending the transaction. This is not part of the \n" "transaction, just kept in your wallet."}, {"subtractfeefromamount", RPCArg::Type::BOOL, RPCArg::Default{false}, "The fee will be deducted from the amount being sent.\n" "The recipient will receive less bitcoins than you enter in the amount field."}, {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"}, {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\""}, {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{true}, "(only available if avoid_reuse wallet flag is set) Avoid spending from dirty addresses; addresses are considered\n" "dirty if they have previously been used in a transaction. If true, this also activates avoidpartialspends, grouping outputs by their addresses."}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."}, {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."}, }, { RPCResult{"if verbose is not set or set to false", RPCResult::Type::STR_HEX, "txid", "The transaction id." }, RPCResult{"if verbose is set to true", RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "txid", "The transaction id."}, {RPCResult::Type::STR, "fee_reason", "The transaction fee reason."} }, }, }, RPCExamples{ "\nSend 0.1 BTC\n" + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1") + "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode using positional arguments\n" + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"donation\" \"sean's outpost\" false true 6 economical") + "\nSend 0.1 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB, subtract fee from amount, BIP125-replaceable, using positional arguments\n" + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"drinks\" \"room77\" true true null \"unset\" null 1.1") + "\nSend 0.2 BTC with a confirmation target of 6 blocks in economical fee estimate mode using named arguments\n" + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.2 conf_target=6 estimate_mode=\"economical\"") + "\nSend 0.5 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n" + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.5 fee_rate=25") + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.5 fee_rate=25 subtractfeefromamount=false replaceable=true avoid_reuse=true comment=\"2 pizzas\" comment_to=\"jeremy\" verbose=true") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); // Wallet comments mapValue_t mapValue; if (!request.params[2].isNull() && !request.params[2].get_str().empty()) mapValue["comment"] = request.params[2].get_str(); if (!request.params[3].isNull() && !request.params[3].get_str().empty()) mapValue["to"] = request.params[3].get_str(); bool fSubtractFeeFromAmount = false; if (!request.params[4].isNull()) { fSubtractFeeFromAmount = request.params[4].get_bool(); } CCoinControl coin_control; if (!request.params[5].isNull()) { coin_control.m_signal_bip125_rbf = request.params[5].get_bool(); } coin_control.m_avoid_address_reuse = GetAvoidReuseFlag(*pwallet, request.params[8]); // We also enable partial spend avoidance if reuse avoidance is set. coin_control.m_avoid_partial_spends |= coin_control.m_avoid_address_reuse; SetFeeEstimateMode(*pwallet, coin_control, /*conf_target=*/request.params[6], /*estimate_mode=*/request.params[7], /*fee_rate=*/request.params[9], /*override_min_fee=*/false); EnsureWalletIsUnlocked(*pwallet); UniValue address_amounts(UniValue::VOBJ); const std::string address = request.params[0].get_str(); address_amounts.pushKV(address, request.params[1]); UniValue subtractFeeFromAmount(UniValue::VARR); if (fSubtractFeeFromAmount) { subtractFeeFromAmount.push_back(address); } std::vector<CRecipient> recipients; ParseRecipients(address_amounts, subtractFeeFromAmount, recipients); const bool verbose{request.params[10].isNull() ? false : request.params[10].get_bool()}; return SendMoney(*pwallet, coin_control, recipients, mapValue, verbose); }, }; } RPCHelpMan sendmany() { return RPCHelpMan{"sendmany", "Send multiple times. Amounts are double-precision floating point numbers." + HELP_REQUIRING_PASSPHRASE, { {"dummy", RPCArg::Type::STR, RPCArg::Default{"\"\""}, "Must be set to \"\" for backwards compatibility.", RPCArgOptions{ .oneline_description = "\"\"", }}, {"amounts", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::NO, "The addresses and amounts", { {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The bitcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value"}, }, }, {"minconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Ignored dummy value"}, {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment"}, {"subtractfeefrom", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The addresses.\n" "The fee will be equally deducted from the amount of each selected address.\n" "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" "If no addresses are specified here, the sender pays the fee.", { {"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Subtract fee from this address"}, }, }, {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"}, {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\""}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."}, {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."}, }, { RPCResult{"if verbose is not set or set to false", RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n" "the number of addresses." }, RPCResult{"if verbose is set to true", RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n" "the number of addresses."}, {RPCResult::Type::STR, "fee_reason", "The transaction fee reason."} }, }, }, RPCExamples{ "\nSend two amounts to two different addresses:\n" + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\"") + "\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 6 \"testing\"") + "\nSend two amounts to two different addresses, subtract fee from amount:\n" + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 1 \"\" \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("sendmany", "\"\", {\"" + EXAMPLE_ADDRESS[0] + "\":0.01,\"" + EXAMPLE_ADDRESS[1] + "\":0.02}, 6, \"testing\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); if (!request.params[0].isNull() && !request.params[0].get_str().empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Dummy value must be set to \"\""); } UniValue sendTo = request.params[1].get_obj(); mapValue_t mapValue; if (!request.params[3].isNull() && !request.params[3].get_str().empty()) mapValue["comment"] = request.params[3].get_str(); UniValue subtractFeeFromAmount(UniValue::VARR); if (!request.params[4].isNull()) subtractFeeFromAmount = request.params[4].get_array(); CCoinControl coin_control; if (!request.params[5].isNull()) { coin_control.m_signal_bip125_rbf = request.params[5].get_bool(); } SetFeeEstimateMode(*pwallet, coin_control, /*conf_target=*/request.params[6], /*estimate_mode=*/request.params[7], /*fee_rate=*/request.params[8], /*override_min_fee=*/false); std::vector<CRecipient> recipients; ParseRecipients(sendTo, subtractFeeFromAmount, recipients); const bool verbose{request.params[9].isNull() ? false : request.params[9].get_bool()}; return SendMoney(*pwallet, coin_control, recipients, std::move(mapValue), verbose); }, }; } RPCHelpMan settxfee() { return RPCHelpMan{"settxfee", "\nSet the transaction fee rate in " + CURRENCY_UNIT + "/kvB for this wallet. Overrides the global -paytxfee command line parameter.\n" "Can be deactivated by passing 0 as the fee. In that case automatic fee selection will be used by default.\n", { {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The transaction fee rate in " + CURRENCY_UNIT + "/kvB"}, }, RPCResult{ RPCResult::Type::BOOL, "", "Returns true if successful" }, RPCExamples{ HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; LOCK(pwallet->cs_wallet); CAmount nAmount = AmountFromValue(request.params[0]); CFeeRate tx_fee_rate(nAmount, 1000); CFeeRate max_tx_fee_rate(pwallet->m_default_max_tx_fee, 1000); if (tx_fee_rate == CFeeRate(0)) { // automatic selection } else if (tx_fee_rate < pwallet->chain().relayMinFee()) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than min relay tx fee (%s)", pwallet->chain().relayMinFee().ToString())); } else if (tx_fee_rate < pwallet->m_min_fee) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than wallet min fee (%s)", pwallet->m_min_fee.ToString())); } else if (tx_fee_rate > max_tx_fee_rate) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be more than wallet max tx fee (%s)", max_tx_fee_rate.ToString())); } pwallet->m_pay_tx_fee = tx_fee_rate; return true; }, }; } // Only includes key documentation where the key is snake_case in all RPC methods. MixedCase keys can be added later. static std::vector<RPCArg> FundTxDoc(bool solving_data = true) { std::vector<RPCArg> args = { {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks", RPCArgOptions{.also_positional = true}}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\"", RPCArgOptions{.also_positional = true}}, { "replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125-replaceable.\n" "Allows this transaction to be replaced by a transaction with higher fees" }, }; if (solving_data) { args.push_back({"solving_data", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "Keys and scripts needed for producing a final transaction with a dummy signature.\n" "Used for fee estimation during coin selection.", { { "pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Public keys involved in this transaction.", { {"pubkey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A public key"}, } }, { "scripts", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Scripts involved in this transaction.", { {"script", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A script"}, } }, { "descriptors", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Descriptors that provide solving data for this transaction.", { {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A descriptor"}, } }, } }); } return args; } CreatedTransactionResult FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const UniValue& options, CCoinControl& coinControl, bool override_min_fee) { // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); std::optional<unsigned int> change_position; bool lockUnspents = false; UniValue subtractFeeFromOutputs; std::set<int> setSubtractFeeFromOutputs; if (!options.isNull()) { if (options.type() == UniValue::VBOOL) { // backward compatibility bool only fallback coinControl.fAllowWatchOnly = options.get_bool(); } else { RPCTypeCheckObj(options, { {"add_inputs", UniValueType(UniValue::VBOOL)}, {"include_unsafe", UniValueType(UniValue::VBOOL)}, {"add_to_wallet", UniValueType(UniValue::VBOOL)}, {"changeAddress", UniValueType(UniValue::VSTR)}, {"change_address", UniValueType(UniValue::VSTR)}, {"changePosition", UniValueType(UniValue::VNUM)}, {"change_position", UniValueType(UniValue::VNUM)}, {"change_type", UniValueType(UniValue::VSTR)}, {"includeWatching", UniValueType(UniValue::VBOOL)}, {"include_watching", UniValueType(UniValue::VBOOL)}, {"inputs", UniValueType(UniValue::VARR)}, {"lockUnspents", UniValueType(UniValue::VBOOL)}, {"lock_unspents", UniValueType(UniValue::VBOOL)}, {"locktime", UniValueType(UniValue::VNUM)}, {"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode() {"feeRate", UniValueType()}, // will be checked by AmountFromValue() below {"psbt", UniValueType(UniValue::VBOOL)}, {"solving_data", UniValueType(UniValue::VOBJ)}, {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)}, {"subtract_fee_from_outputs", UniValueType(UniValue::VARR)}, {"replaceable", UniValueType(UniValue::VBOOL)}, {"conf_target", UniValueType(UniValue::VNUM)}, {"estimate_mode", UniValueType(UniValue::VSTR)}, {"minconf", UniValueType(UniValue::VNUM)}, {"maxconf", UniValueType(UniValue::VNUM)}, {"input_weights", UniValueType(UniValue::VARR)}, }, true, true); if (options.exists("add_inputs")) { coinControl.m_allow_other_inputs = options["add_inputs"].get_bool(); } if (options.exists("changeAddress") || options.exists("change_address")) { const std::string change_address_str = (options.exists("change_address") ? options["change_address"] : options["changeAddress"]).get_str(); CTxDestination dest = DecodeDestination(change_address_str); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Change address must be a valid bitcoin address"); } coinControl.destChange = dest; } if (options.exists("changePosition") || options.exists("change_position")) { int pos = (options.exists("change_position") ? options["change_position"] : options["changePosition"]).getInt<int>(); if (pos < 0 || (unsigned int)pos > tx.vout.size()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds"); } change_position = (unsigned int)pos; } if (options.exists("change_type")) { if (options.exists("changeAddress") || options.exists("change_address")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both change address and address type options"); } if (std::optional<OutputType> parsed = ParseOutputType(options["change_type"].get_str())) { coinControl.m_change_type.emplace(parsed.value()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str())); } } const UniValue include_watching_option = options.exists("include_watching") ? options["include_watching"] : options["includeWatching"]; coinControl.fAllowWatchOnly = ParseIncludeWatchonly(include_watching_option, wallet); if (options.exists("lockUnspents") || options.exists("lock_unspents")) { lockUnspents = (options.exists("lock_unspents") ? options["lock_unspents"] : options["lockUnspents"]).get_bool(); } if (options.exists("include_unsafe")) { coinControl.m_include_unsafe_inputs = options["include_unsafe"].get_bool(); } if (options.exists("feeRate")) { if (options.exists("fee_rate")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both fee_rate (" + CURRENCY_ATOM + "/vB) and feeRate (" + CURRENCY_UNIT + "/kvB)"); } if (options.exists("conf_target")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and feeRate. Please provide either a confirmation target in blocks for automatic fee estimation, or an explicit fee rate."); } if (options.exists("estimate_mode")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate"); } coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"])); coinControl.fOverrideFeeRate = true; } if (options.exists("subtractFeeFromOutputs") || options.exists("subtract_fee_from_outputs") ) subtractFeeFromOutputs = (options.exists("subtract_fee_from_outputs") ? options["subtract_fee_from_outputs"] : options["subtractFeeFromOutputs"]).get_array(); if (options.exists("replaceable")) { coinControl.m_signal_bip125_rbf = options["replaceable"].get_bool(); } if (options.exists("minconf")) { coinControl.m_min_depth = options["minconf"].getInt<int>(); if (coinControl.m_min_depth < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative minconf"); } } if (options.exists("maxconf")) { coinControl.m_max_depth = options["maxconf"].getInt<int>(); if (coinControl.m_max_depth < coinControl.m_min_depth) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("maxconf can't be lower than minconf: %d < %d", coinControl.m_max_depth, coinControl.m_min_depth)); } } SetFeeEstimateMode(wallet, coinControl, options["conf_target"], options["estimate_mode"], options["fee_rate"], override_min_fee); } } else { // if options is null and not a bool coinControl.fAllowWatchOnly = ParseIncludeWatchonly(NullUniValue, wallet); } if (options.exists("solving_data")) { const UniValue solving_data = options["solving_data"].get_obj(); if (solving_data.exists("pubkeys")) { for (const UniValue& pk_univ : solving_data["pubkeys"].get_array().getValues()) { const std::string& pk_str = pk_univ.get_str(); if (!IsHex(pk_str)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", pk_str)); } const std::vector<unsigned char> data(ParseHex(pk_str)); const CPubKey pubkey(data.begin(), data.end()); if (!pubkey.IsFullyValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not a valid public key", pk_str)); } coinControl.m_external_provider.pubkeys.emplace(pubkey.GetID(), pubkey); // Add witness script for pubkeys const CScript wit_script = GetScriptForDestination(WitnessV0KeyHash(pubkey)); coinControl.m_external_provider.scripts.emplace(CScriptID(wit_script), wit_script); } } if (solving_data.exists("scripts")) { for (const UniValue& script_univ : solving_data["scripts"].get_array().getValues()) { const std::string& script_str = script_univ.get_str(); if (!IsHex(script_str)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", script_str)); } std::vector<unsigned char> script_data(ParseHex(script_str)); const CScript script(script_data.begin(), script_data.end()); coinControl.m_external_provider.scripts.emplace(CScriptID(script), script); } } if (solving_data.exists("descriptors")) { for (const UniValue& desc_univ : solving_data["descriptors"].get_array().getValues()) { const std::string& desc_str = desc_univ.get_str(); FlatSigningProvider desc_out; std::string error; std::vector<CScript> scripts_temp; std::unique_ptr<Descriptor> desc = Parse(desc_str, desc_out, error, true); if (!desc) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor '%s': %s", desc_str, error)); } desc->Expand(0, desc_out, scripts_temp, desc_out); coinControl.m_external_provider.Merge(std::move(desc_out)); } } } if (options.exists("input_weights")) { for (const UniValue& input : options["input_weights"].get_array().getValues()) { Txid txid = Txid::FromUint256(ParseHashO(input, "txid")); const UniValue& vout_v = input.find_value("vout"); if (!vout_v.isNum()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); } int vout = vout_v.getInt<int>(); if (vout < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative"); } const UniValue& weight_v = input.find_value("weight"); if (!weight_v.isNum()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing weight key"); } int64_t weight = weight_v.getInt<int64_t>(); const int64_t min_input_weight = GetTransactionInputWeight(CTxIn()); CHECK_NONFATAL(min_input_weight == 165); if (weight < min_input_weight) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, weight cannot be less than 165 (41 bytes (size of outpoint + sequence + empty scriptSig) * 4 (witness scaling factor)) + 1 (empty witness)"); } if (weight > MAX_STANDARD_TX_WEIGHT) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, weight cannot be greater than the maximum standard tx weight of %d", MAX_STANDARD_TX_WEIGHT)); } coinControl.SetInputWeight(COutPoint(txid, vout), weight); } } if (tx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) { int pos = subtractFeeFromOutputs[idx].getInt<int>(); if (setSubtractFeeFromOutputs.count(pos)) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos)); if (pos < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, negative position: %d", pos)); if (pos >= int(tx.vout.size())) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, position too large: %d", pos)); setSubtractFeeFromOutputs.insert(pos); } auto txr = FundTransaction(wallet, tx, change_position, lockUnspents, setSubtractFeeFromOutputs, coinControl); if (!txr) { throw JSONRPCError(RPC_WALLET_ERROR, ErrorString(txr).original); } return *txr; } static void SetOptionsInputWeights(const UniValue& inputs, UniValue& options) { if (options.exists("input_weights")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Input weights should be specified in inputs rather than in options."); } if (inputs.size() == 0) { return; } UniValue weights(UniValue::VARR); for (const UniValue& input : inputs.getValues()) { if (input.exists("weight")) { weights.push_back(input); } } options.pushKV("input_weights", weights); } RPCHelpMan fundrawtransaction() { return RPCHelpMan{"fundrawtransaction", "\nIf the transaction has no inputs, they will be automatically selected to meet its out value.\n" "It will add at most one change output to the outputs.\n" "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n" "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" "The inputs added will not be signed, use signrawtransactionwithkey\n" "or signrawtransactionwithwallet for that.\n" "All existing inputs must either have their previous output transaction be in the wallet\n" "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n" "Note that all inputs selected must be of standard form and P2SH scripts must be\n" "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n", { {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"}, {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "For backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}", Cat<std::vector<RPCArg>>( { {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{true}, "For a transaction with existing inputs, automatically include more if they are not enough."}, {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n" "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n" "If that happens, you will need to fund the transaction with different inputs and republish it."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."}, {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."}, {"changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"}, {"changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"}, {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."}, {"includeWatching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only.\n" "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n" "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."}, {"lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."}, {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."}, {"subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The integers.\n" "The fee will be equally deducted from the amount of each specified output.\n" "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" "If no outputs are specified here, the sender pays the fee.", { {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."}, }, }, {"input_weights", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Inputs and their corresponding weights", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output index"}, {"weight", RPCArg::Type::NUM, RPCArg::Optional::NO, "The maximum weight for this input, " "including the weight of the outpoint and sequence number. " "Note that serialized signature sizes are not guaranteed to be consistent, " "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures." "Remember to convert serialized sizes to weight units when necessary."}, }, }, }, }, }, FundTxDoc()), RPCArgOptions{ .skip_type_check = true, .oneline_description = "options", }}, {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n" "If iswitness is not present, heuristic tests will be used in decoding.\n" "If true, only witness deserialization will be tried.\n" "If false, only non-witness deserialization will be tried.\n" "This boolean should reflect whether the transaction has inputs\n" "(e.g. fully valid, or on-chain transactions), if known by the caller." }, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "hex", "The resulting raw transaction (hex-encoded string)"}, {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"}, {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"}, } }, RPCExamples{ "\nCreate a transaction with no inputs\n" + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + "\nAdd sufficient unsigned inputs to meet the output value\n" + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + "\nSign the transaction\n" + HelpExampleCli("signrawtransactionwithwallet", "\"fundedtransactionhex\"") + "\nSend the transaction\n" + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; // parse hex string from parameter CMutableTransaction tx; bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool(); bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool(); if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } CCoinControl coin_control; // Automatically select (additional) coins. Can be overridden by options.add_inputs. coin_control.m_allow_other_inputs = true; auto txr = FundTransaction(*pwallet, tx, request.params[1], coin_control, /*override_min_fee=*/true); UniValue result(UniValue::VOBJ); result.pushKV("hex", EncodeHexTx(*txr.tx)); result.pushKV("fee", ValueFromAmount(txr.fee)); result.pushKV("changepos", txr.change_pos ? (int)*txr.change_pos : -1); return result; }, }; } RPCHelpMan signrawtransactionwithwallet() { return RPCHelpMan{"signrawtransactionwithwallet", "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain." + HELP_REQUIRING_PASSPHRASE, { {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"}, {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The previous dependent transaction outputs", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "script key"}, {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"}, {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"}, {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"}, }, }, }, }, {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type. Must be one of\n" " \"DEFAULT\"\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\""}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"}, {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"}, {RPCResult::Type::ARR, "errors", /*optional=*/true, "Script verification errors (if there are any)", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"}, {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"}, {RPCResult::Type::ARR, "witness", "", { {RPCResult::Type::STR_HEX, "witness", ""}, }}, {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"}, {RPCResult::Type::NUM, "sequence", "Script sequence number"}, {RPCResult::Type::STR, "error", "Verification or signing error related to the input"}, }}, }}, } }, RPCExamples{ HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") + HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; CMutableTransaction mtx; if (!DecodeHexTx(mtx, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input."); } // Sign the transaction LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); // Fetch previous transactions (inputs): std::map<COutPoint, Coin> coins; for (const CTxIn& txin : mtx.vin) { coins[txin.prevout]; // Create empty map entry keyed by prevout. } pwallet->chain().findCoins(coins); // Parse the prevtxs array ParsePrevouts(request.params[1], nullptr, coins); int nHashType = ParseSighashString(request.params[2]); // Script verification errors std::map<int, bilingual_str> input_errors; bool complete = pwallet->SignTransaction(mtx, coins, nHashType, input_errors); UniValue result(UniValue::VOBJ); SignTransactionResultToJSON(mtx, complete, coins, input_errors, result); return result; }, }; } // Definition of allowed formats of specifying transaction outputs in // `bumpfee`, `psbtbumpfee`, `send` and `walletcreatefundedpsbt` RPCs. static std::vector<RPCArg> OutputsDoc() { return { {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "", { {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address,\n" "the value (float or string) is the amount in " + CURRENCY_UNIT + ""}, }, }, {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"}, }, }, }; } static RPCHelpMan bumpfee_helper(std::string method_name) { const bool want_psbt = method_name == "psbtbumpfee"; const std::string incremental_fee{CFeeRate(DEFAULT_INCREMENTAL_RELAY_FEE).ToString(FeeEstimateMode::SAT_VB)}; return RPCHelpMan{method_name, "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n" + std::string(want_psbt ? "Returns a PSBT instead of creating and signing a new transaction.\n" : "") + "An opt-in RBF transaction with the given txid must be in the wallet.\n" "The command will pay the additional fee by reducing change outputs or adding inputs when necessary.\n" "It may add a new change output if one does not already exist.\n" "All inputs in the original transaction will be included in the replacement transaction.\n" "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n" "By default, the new fee will be calculated automatically using the estimatesmartfee RPC.\n" "The user can specify a confirmation target for estimatesmartfee.\n" "Alternatively, the user can specify a fee rate in " + CURRENCY_ATOM + "/vB for the new transaction.\n" "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n" "returned by getnetworkinfo) to enter the node's mempool.\n" "* WARNING: before version 0.21, fee_rate was in " + CURRENCY_UNIT + "/kvB. As of 0.21, fee_rate is in " + CURRENCY_ATOM + "/vB. *\n", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The txid to be bumped"}, {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", { {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks\n"}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "\nSpecify a fee rate in " + CURRENCY_ATOM + "/vB instead of relying on the built-in fee estimator.\n" "Must be at least " + incremental_fee + " higher than the current transaction fee rate.\n" "WARNING: before version 0.21, fee_rate was in " + CURRENCY_UNIT + "/kvB. As of 0.21, fee_rate is in " + CURRENCY_ATOM + "/vB.\n"}, {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether the new transaction should still be\n" "marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n" "be left unchanged from the original. If false, any input sequence numbers in the\n" "original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n" "so the new transaction will not be explicitly bip-125 replaceable (though it may\n" "still be replaceable in practice, for example if it has unconfirmed ancestors which\n" "are replaceable).\n"}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\""}, {"outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs specified as key-value pairs.\n" "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n" "At least one output of either type must be specified.\n" "Cannot be provided if 'original_change_index' is specified.", OutputsDoc(), RPCArgOptions{.skip_type_check = true}}, {"original_change_index", RPCArg::Type::NUM, RPCArg::DefaultHint{"not set, detect change automatically"}, "The 0-based index of the change output on the original transaction. " "The indicated output will be recycled into the new change output on the bumped transaction. " "The remainder after paying the recipients and fees will be sent to the output script of the " "original change output. The change output’s amount can increase if bumping the transaction " "adds new inputs, otherwise it will decrease. Cannot be used in combination with the 'outputs' option."}, }, RPCArgOptions{.oneline_description="options"}}, }, RPCResult{ RPCResult::Type::OBJ, "", "", Cat( want_psbt ? std::vector<RPCResult>{{RPCResult::Type::STR, "psbt", "The base64-encoded unsigned PSBT of the new transaction."}} : std::vector<RPCResult>{{RPCResult::Type::STR_HEX, "txid", "The id of the new transaction."}}, { {RPCResult::Type::STR_AMOUNT, "origfee", "The fee of the replaced transaction."}, {RPCResult::Type::STR_AMOUNT, "fee", "The fee of the new transaction."}, {RPCResult::Type::ARR, "errors", "Errors encountered during processing (may be empty).", { {RPCResult::Type::STR, "", ""}, }}, }) }, RPCExamples{ "\nBump the fee, get the new transaction\'s " + std::string(want_psbt ? "psbt" : "txid") + "\n" + HelpExampleCli(method_name, "<txid>") }, [want_psbt](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER) && !want_psbt) { throw JSONRPCError(RPC_WALLET_ERROR, "bumpfee is not available with wallets that have private keys disabled. Use psbtbumpfee instead."); } uint256 hash(ParseHashV(request.params[0], "txid")); CCoinControl coin_control; coin_control.fAllowWatchOnly = pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS); // optional parameters coin_control.m_signal_bip125_rbf = true; std::vector<CTxOut> outputs; std::optional<uint32_t> original_change_index; if (!request.params[1].isNull()) { UniValue options = request.params[1]; RPCTypeCheckObj(options, { {"confTarget", UniValueType(UniValue::VNUM)}, {"conf_target", UniValueType(UniValue::VNUM)}, {"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode() {"replaceable", UniValueType(UniValue::VBOOL)}, {"estimate_mode", UniValueType(UniValue::VSTR)}, {"outputs", UniValueType()}, // will be checked by AddOutputs() {"original_change_index", UniValueType(UniValue::VNUM)}, }, true, true); if (options.exists("confTarget") && options.exists("conf_target")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and conf_target options should not both be set. Use conf_target (confTarget is deprecated)."); } auto conf_target = options.exists("confTarget") ? options["confTarget"] : options["conf_target"]; if (options.exists("replaceable")) { coin_control.m_signal_bip125_rbf = options["replaceable"].get_bool(); } SetFeeEstimateMode(*pwallet, coin_control, conf_target, options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false); // Prepare new outputs by creating a temporary tx and calling AddOutputs(). if (!options["outputs"].isNull()) { if (options["outputs"].isArray() && options["outputs"].empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument cannot be an empty array"); } CMutableTransaction tempTx; AddOutputs(tempTx, options["outputs"]); outputs = tempTx.vout; } if (options.exists("original_change_index")) { original_change_index = options["original_change_index"].getInt<uint32_t>(); } } // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); std::vector<bilingual_str> errors; CAmount old_fee; CAmount new_fee; CMutableTransaction mtx; feebumper::Result res; // Targeting feerate bump. res = feebumper::CreateRateBumpTransaction(*pwallet, hash, coin_control, errors, old_fee, new_fee, mtx, /*require_mine=*/ !want_psbt, outputs, original_change_index); if (res != feebumper::Result::OK) { switch(res) { case feebumper::Result::INVALID_ADDRESS_OR_KEY: throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errors[0].original); break; case feebumper::Result::INVALID_REQUEST: throw JSONRPCError(RPC_INVALID_REQUEST, errors[0].original); break; case feebumper::Result::INVALID_PARAMETER: throw JSONRPCError(RPC_INVALID_PARAMETER, errors[0].original); break; case feebumper::Result::WALLET_ERROR: throw JSONRPCError(RPC_WALLET_ERROR, errors[0].original); break; default: throw JSONRPCError(RPC_MISC_ERROR, errors[0].original); break; } } UniValue result(UniValue::VOBJ); // For bumpfee, return the new transaction id. // For psbtbumpfee, return the base64-encoded unsigned PSBT of the new transaction. if (!want_psbt) { if (!feebumper::SignTransaction(*pwallet, mtx)) { if (pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) { throw JSONRPCError(RPC_WALLET_ERROR, "Transaction incomplete. Try psbtbumpfee instead."); } throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction."); } uint256 txid; if (feebumper::CommitTransaction(*pwallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) { throw JSONRPCError(RPC_WALLET_ERROR, errors[0].original); } result.pushKV("txid", txid.GetHex()); } else { PartiallySignedTransaction psbtx(mtx); bool complete = false; const TransactionError err = pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, /*sign=*/false, /*bip32derivs=*/true); CHECK_NONFATAL(err == TransactionError::OK); CHECK_NONFATAL(!complete); DataStream ssTx{}; ssTx << psbtx; result.pushKV("psbt", EncodeBase64(ssTx.str())); } result.pushKV("origfee", ValueFromAmount(old_fee)); result.pushKV("fee", ValueFromAmount(new_fee)); UniValue result_errors(UniValue::VARR); for (const bilingual_str& error : errors) { result_errors.push_back(error.original); } result.pushKV("errors", result_errors); return result; }, }; } RPCHelpMan bumpfee() { return bumpfee_helper("bumpfee"); } RPCHelpMan psbtbumpfee() { return bumpfee_helper("psbtbumpfee"); } RPCHelpMan send() { return RPCHelpMan{"send", "\nEXPERIMENTAL warning: this call may be changed in future releases.\n" "\nSend a transaction.\n", { {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n" "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n" "At least one output of either type must be specified.\n" "For convenience, a dictionary, which holds the key-value pairs directly, is also accepted.", OutputsDoc(), RPCArgOptions{.skip_type_check = true}}, {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\""}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."}, {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", Cat<std::vector<RPCArg>>( { {"add_inputs", RPCArg::Type::BOOL, RPCArg::DefaultHint{"false when \"inputs\" are specified, true otherwise"},"Automatically include coins from the wallet to cover the target amount.\n"}, {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n" "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n" "If that happens, you will need to fund the transaction with different inputs and republish it."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."}, {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."}, {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns a serialized transaction which will not be added to the wallet or broadcast"}, {"change_address", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"}, {"change_position", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"}, {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if change_address is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\" and \"bech32m\"."}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB.", RPCArgOptions{.also_positional = true}}, {"include_watching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only.\n" "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n" "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."}, {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Specify inputs instead of adding them automatically. A JSON array of JSON objects", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"sequence", RPCArg::Type::NUM, RPCArg::Optional::NO, "The sequence number"}, {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, " "including the weight of the outpoint and sequence number. " "Note that signature sizes are not guaranteed to be consistent, " "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures." "Remember to convert serialized sizes to weight units when necessary."}, }, }, {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"}, {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"}, {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."}, {"subtract_fee_from_outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Outputs to subtract the fee from, specified as integer indices.\n" "The fee will be equally deducted from the amount of each specified output.\n" "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" "If no outputs are specified here, the sender pays the fee.", { {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."}, }, }, }, FundTxDoc()), RPCArgOptions{.oneline_description="options"}}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"}, {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."}, {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"}, {RPCResult::Type::STR, "psbt", /*optional=*/true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"} } }, RPCExamples{"" "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode\n" + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 6 economical\n") + "Send 0.2 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n" + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" 1.1\n") + "Send 0.2 BTC with a fee rate of 1 " + CURRENCY_ATOM + "/vB using the options argument\n" + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" null '{\"fee_rate\": 1}'\n") + "Send 0.3 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n" + HelpExampleCli("-named send", "outputs='{\"" + EXAMPLE_ADDRESS[0] + "\": 0.3}' fee_rate=25\n") + "Create a transaction that should confirm the next block, with a specific input, and return result without adding to wallet or broadcasting to the network\n" + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 1 economical '{\"add_to_wallet\": false, \"inputs\": [{\"txid\":\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\", \"vout\":1}]}'") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; UniValue options{request.params[4].isNull() ? UniValue::VOBJ : request.params[4]}; InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options); PreventOutdatedOptions(options); bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf}; CMutableTransaction rawTx = ConstructTransaction(options["inputs"], request.params[0], options["locktime"], rbf); CCoinControl coin_control; // Automatically select coins, unless at least one is manually selected. Can // be overridden by options.add_inputs. coin_control.m_allow_other_inputs = rawTx.vin.size() == 0; SetOptionsInputWeights(options["inputs"], options); auto txr = FundTransaction(*pwallet, rawTx, options, coin_control, /*override_min_fee=*/false); return FinishTransaction(pwallet, options, CMutableTransaction(*txr.tx)); } }; } RPCHelpMan sendall() { return RPCHelpMan{"sendall", "EXPERIMENTAL warning: this call may be changed in future releases.\n" "\nSpend the value of all (or specific) confirmed UTXOs in the wallet to one or more recipients.\n" "Unconfirmed inbound UTXOs and locked UTXOs will not be spent. Sendall will respect the avoid_reuse wallet flag.\n" "If your wallet contains many small inputs, either because it received tiny payments or as a result of accumulating change, consider using `send_max` to exclude inputs that are worth less than the fees needed to spend them.\n", { {"recipients", RPCArg::Type::ARR, RPCArg::Optional::NO, "The sendall destinations. Each address may only appear once.\n" "Optionally some recipients can be specified with an amount to perform payments, but at least one address must appear without a specified amount.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "A bitcoin address which receives an equal share of the unspecified amount."}, {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "", { {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + ""}, }, }, }, }, {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"}, {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n" "\"" + FeeModes("\"\n\"") + "\""}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."}, { "options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", Cat<std::vector<RPCArg>>( { {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns the serialized transaction without broadcasting or adding it to the wallet"}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB.", RPCArgOptions{.also_positional = true}}, {"include_watching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch-only.\n" "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n" "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."}, {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Use exactly the specified inputs to build the transaction. Specifying inputs is incompatible with the send_max, minconf, and maxconf options.", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"}, }, }, }, }, {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"}, {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"}, {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."}, {"send_max", RPCArg::Type::BOOL, RPCArg::Default{false}, "When true, only use UTXOs that can pay for their own fees to maximize the output amount. When 'false' (default), no UTXO is left behind. send_max is incompatible with providing specific inputs."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "Require inputs with at least this many confirmations."}, {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Require inputs with at most this many confirmations."}, }, FundTxDoc() ), RPCArgOptions{.oneline_description="options"} }, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"}, {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."}, {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"}, {RPCResult::Type::STR, "psbt", /*optional=*/true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"} } }, RPCExamples{"" "\nSpend all UTXOs from the wallet with a fee rate of 1 " + CURRENCY_ATOM + "/vB using named arguments\n" + HelpExampleCli("-named sendall", "recipients='[\"" + EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1\n") + "Spend all UTXOs with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n" + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" 1.1\n") + "Spend all UTXOs split into equal amounts to two addresses with a fee rate of 1.5 " + CURRENCY_ATOM + "/vB using the options argument\n" + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\", \"" + EXAMPLE_ADDRESS[1] + "\"]' null \"unset\" null '{\"fee_rate\": 1.5}'\n") + "Leave dust UTXOs in wallet, spend only UTXOs with positive effective value with a fee rate of 10 " + CURRENCY_ATOM + "/vB using the options argument\n" + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" null '{\"fee_rate\": 10, \"send_max\": true}'\n") + "Spend all UTXOs with a fee rate of 1.3 " + CURRENCY_ATOM + "/vB using named arguments and sending a 0.25 " + CURRENCY_UNIT + " to another recipient\n" + HelpExampleCli("-named sendall", "recipients='[{\"" + EXAMPLE_ADDRESS[1] + "\": 0.25}, \""+ EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1.3\n") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet{GetWalletForJSONRPCRequest(request)}; if (!pwallet) return UniValue::VNULL; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); UniValue options{request.params[4].isNull() ? UniValue::VOBJ : request.params[4]}; InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options); PreventOutdatedOptions(options); std::set<std::string> addresses_without_amount; UniValue recipient_key_value_pairs(UniValue::VARR); const UniValue& recipients{request.params[0]}; for (unsigned int i = 0; i < recipients.size(); ++i) { const UniValue& recipient{recipients[i]}; if (recipient.isStr()) { UniValue rkvp(UniValue::VOBJ); rkvp.pushKV(recipient.get_str(), 0); recipient_key_value_pairs.push_back(rkvp); addresses_without_amount.insert(recipient.get_str()); } else { recipient_key_value_pairs.push_back(recipient); } } if (addresses_without_amount.size() == 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Must provide at least one address without a specified amount"); } CCoinControl coin_control; SetFeeEstimateMode(*pwallet, coin_control, options["conf_target"], options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false); coin_control.fAllowWatchOnly = ParseIncludeWatchonly(options["include_watching"], *pwallet); if (options.exists("minconf")) { if (options["minconf"].getInt<int>() < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid minconf (minconf cannot be negative): %s", options["minconf"].getInt<int>())); } coin_control.m_min_depth = options["minconf"].getInt<int>(); } if (options.exists("maxconf")) { coin_control.m_max_depth = options["maxconf"].getInt<int>(); if (coin_control.m_max_depth < coin_control.m_min_depth) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("maxconf can't be lower than minconf: %d < %d", coin_control.m_max_depth, coin_control.m_min_depth)); } } const bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf}; FeeCalculation fee_calc_out; CFeeRate fee_rate{GetMinimumFeeRate(*pwallet, coin_control, &fee_calc_out)}; // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly // provided one if (coin_control.m_feerate && fee_rate > *coin_control.m_feerate) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Fee rate (%s) is lower than the minimum fee rate setting (%s)", coin_control.m_feerate->ToString(FeeEstimateMode::SAT_VB), fee_rate.ToString(FeeEstimateMode::SAT_VB))); } if (fee_calc_out.reason == FeeReason::FALLBACK && !pwallet->m_allow_fallback_fee) { // eventually allow a fallback fee throw JSONRPCError(RPC_WALLET_ERROR, "Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee."); } CMutableTransaction rawTx{ConstructTransaction(options["inputs"], recipient_key_value_pairs, options["locktime"], rbf)}; LOCK(pwallet->cs_wallet); CAmount total_input_value(0); bool send_max{options.exists("send_max") ? options["send_max"].get_bool() : false}; if (options.exists("inputs") && options.exists("send_max")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine send_max with specific inputs."); } else if (options.exists("inputs") && (options.exists("minconf") || options.exists("maxconf"))) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine minconf or maxconf with specific inputs."); } else if (options.exists("inputs")) { for (const CTxIn& input : rawTx.vin) { if (pwallet->IsSpent(input.prevout)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not available. UTXO (%s:%d) was already spent.", input.prevout.hash.ToString(), input.prevout.n)); } const CWalletTx* tx{pwallet->GetWalletTx(input.prevout.hash)}; if (!tx || input.prevout.n >= tx->tx->vout.size() || !(pwallet->IsMine(tx->tx->vout[input.prevout.n]) & (coin_control.fAllowWatchOnly ? ISMINE_ALL : ISMINE_SPENDABLE))) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not found. UTXO (%s:%d) is not part of wallet.", input.prevout.hash.ToString(), input.prevout.n)); } total_input_value += tx->tx->vout[input.prevout.n].nValue; } } else { CoinFilterParams coins_params; coins_params.min_amount = 0; for (const COutput& output : AvailableCoins(*pwallet, &coin_control, fee_rate, coins_params).All()) { CHECK_NONFATAL(output.input_bytes > 0); if (send_max && fee_rate.GetFee(output.input_bytes) > output.txout.nValue) { continue; } CTxIn input(output.outpoint.hash, output.outpoint.n, CScript(), rbf ? MAX_BIP125_RBF_SEQUENCE : CTxIn::SEQUENCE_FINAL); rawTx.vin.push_back(input); total_input_value += output.txout.nValue; } } // estimate final size of tx const TxSize tx_size{CalculateMaximumSignedTxSize(CTransaction(rawTx), pwallet.get())}; const CAmount fee_from_size{fee_rate.GetFee(tx_size.vsize)}; const CAmount effective_value{total_input_value - fee_from_size}; if (fee_from_size > pwallet->m_default_max_tx_fee) { throw JSONRPCError(RPC_WALLET_ERROR, TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED).original); } if (effective_value <= 0) { if (send_max) { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Total value of UTXO pool too low to pay for transaction, try using lower feerate."); } else { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Total value of UTXO pool too low to pay for transaction. Try using lower feerate or excluding uneconomic UTXOs with 'send_max' option."); } } // If this transaction is too large, e.g. because the wallet has many UTXOs, it will be rejected by the node's mempool. if (tx_size.weight > MAX_STANDARD_TX_WEIGHT) { throw JSONRPCError(RPC_WALLET_ERROR, "Transaction too large."); } CAmount output_amounts_claimed{0}; for (const CTxOut& out : rawTx.vout) { output_amounts_claimed += out.nValue; } if (output_amounts_claimed > total_input_value) { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Assigned more value to outputs than available funds."); } const CAmount remainder{effective_value - output_amounts_claimed}; if (remainder < 0) { throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds for fees after creating specified outputs."); } const CAmount per_output_without_amount{remainder / (long)addresses_without_amount.size()}; bool gave_remaining_to_first{false}; for (CTxOut& out : rawTx.vout) { CTxDestination dest; ExtractDestination(out.scriptPubKey, dest); std::string addr{EncodeDestination(dest)}; if (addresses_without_amount.count(addr) > 0) { out.nValue = per_output_without_amount; if (!gave_remaining_to_first) { out.nValue += remainder % addresses_without_amount.size(); gave_remaining_to_first = true; } if (IsDust(out, pwallet->chain().relayDustFee())) { // Dynamically generated output amount is dust throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Dynamically assigned remainder results in dust output."); } } else { if (IsDust(out, pwallet->chain().relayDustFee())) { // Specified output amount is dust throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Specified output amount to %s is below dust threshold.", addr)); } } } const bool lock_unspents{options.exists("lock_unspents") ? options["lock_unspents"].get_bool() : false}; if (lock_unspents) { for (const CTxIn& txin : rawTx.vin) { pwallet->LockCoin(txin.prevout); } } return FinishTransaction(pwallet, options, rawTx); } }; } RPCHelpMan walletprocesspsbt() { return RPCHelpMan{"walletprocesspsbt", "\nUpdate a PSBT with input information from our wallet and then sign inputs\n" "that we can sign for." + HELP_REQUIRING_PASSPHRASE, { {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"}, {"sign", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also sign the transaction when updating (requires wallet to be unlocked)"}, {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type to sign with if not specified by the PSBT. Must be one of\n" " \"DEFAULT\"\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\""}, {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"}, {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also finalize inputs if possible"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction"}, {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"}, {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if complete"}, } }, RPCExamples{ HelpExampleCli("walletprocesspsbt", "\"psbt\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; const CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); // Unserialize the transaction PartiallySignedTransaction psbtx; std::string error; if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error)); } // Get the sighash type int nHashType = ParseSighashString(request.params[2]); // Fill transaction with our data and also sign bool sign = request.params[1].isNull() ? true : request.params[1].get_bool(); bool bip32derivs = request.params[3].isNull() ? true : request.params[3].get_bool(); bool finalize = request.params[4].isNull() ? true : request.params[4].get_bool(); bool complete = true; if (sign) EnsureWalletIsUnlocked(*pwallet); const TransactionError err{wallet.FillPSBT(psbtx, complete, nHashType, sign, bip32derivs, nullptr, finalize)}; if (err != TransactionError::OK) { throw JSONRPCTransactionError(err); } UniValue result(UniValue::VOBJ); DataStream ssTx{}; ssTx << psbtx; result.pushKV("psbt", EncodeBase64(ssTx.str())); result.pushKV("complete", complete); if (complete) { CMutableTransaction mtx; // Returns true if complete, which we already think it is. CHECK_NONFATAL(FinalizeAndExtractPSBT(psbtx, mtx)); DataStream ssTx_final; ssTx_final << TX_WITH_WITNESS(mtx); result.pushKV("hex", HexStr(ssTx_final)); } return result; }, }; } RPCHelpMan walletcreatefundedpsbt() { return RPCHelpMan{"walletcreatefundedpsbt", "\nCreates and funds a transaction in the Partially Signed Transaction format.\n" "Implements the Creator and Updater roles.\n" "All existing inputs must either have their previous output transaction be in the wallet\n" "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n", { {"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Leave empty to add inputs automatically. See add_inputs option.", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"}, {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"}, {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'locktime' and 'options.replaceable' arguments"}, "The sequence number"}, {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, " "including the weight of the outpoint and sequence number. " "Note that signature sizes are not guaranteed to be consistent, " "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures." "Remember to convert serialized sizes to weight units when necessary."}, }, }, }, }, {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n" "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n" "At least one output of either type must be specified.\n" "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" "accepted as second parameter.", OutputsDoc(), RPCArgOptions{.skip_type_check = true}}, {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"}, {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "", Cat<std::vector<RPCArg>>( { {"add_inputs", RPCArg::Type::BOOL, RPCArg::DefaultHint{"false when \"inputs\" are specified, true otherwise"}, "Automatically include coins from the wallet to cover the target amount.\n"}, {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n" "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n" "If that happens, you will need to fund the transaction with different inputs and republish it."}, {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."}, {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."}, {"changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"}, {"changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"}, {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."}, {"includeWatching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only"}, {"lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"}, {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."}, {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."}, {"subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs to subtract the fee from.\n" "The fee will be equally deducted from the amount of each specified output.\n" "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" "If no outputs are specified here, the sender pays the fee.", { {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."}, }, }, }, FundTxDoc()), RPCArgOptions{.oneline_description="options"}}, {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "psbt", "The resulting raw transaction (base64-encoded string)"}, {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"}, {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"}, } }, RPCExamples{ "\nCreate a transaction with no inputs\n" + HelpExampleCli("walletcreatefundedpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return UniValue::VNULL; CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); UniValue options{request.params[3].isNull() ? UniValue::VOBJ : request.params[3]}; const UniValue &replaceable_arg = options["replaceable"]; const bool rbf{replaceable_arg.isNull() ? wallet.m_signal_rbf : replaceable_arg.get_bool()}; CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf); CCoinControl coin_control; // Automatically select coins, unless at least one is manually selected. Can // be overridden by options.add_inputs. coin_control.m_allow_other_inputs = rawTx.vin.size() == 0; SetOptionsInputWeights(request.params[0], options); auto txr = FundTransaction(wallet, rawTx, options, coin_control, /*override_min_fee=*/true); // Make a blank psbt PartiallySignedTransaction psbtx(CMutableTransaction(*txr.tx)); // Fill transaction with out data but don't sign bool bip32derivs = request.params[4].isNull() ? true : request.params[4].get_bool(); bool complete = true; const TransactionError err{wallet.FillPSBT(psbtx, complete, 1, /*sign=*/false, /*bip32derivs=*/bip32derivs)}; if (err != TransactionError::OK) { throw JSONRPCTransactionError(err); } // Serialize the PSBT DataStream ssTx{}; ssTx << psbtx; UniValue result(UniValue::VOBJ); result.pushKV("psbt", EncodeBase64(ssTx.str())); result.pushKV("fee", ValueFromAmount(txr.fee)); result.pushKV("changepos", txr.change_pos ? (int)*txr.change_pos : -1); return result; }, }; } } // namespace wallet
0
bitcoin/src
bitcoin/src/index/blockfilterindex.cpp
// Copyright (c) 2018-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <map> #include <clientversion.h> #include <common/args.h> #include <dbwrapper.h> #include <hash.h> #include <index/blockfilterindex.h> #include <logging.h> #include <node/blockstorage.h> #include <undo.h> #include <util/fs_helpers.h> #include <validation.h> /* The index database stores three items for each block: the disk location of the encoded filter, * its dSHA256 hash, and the header. Those belonging to blocks on the active chain are indexed by * height, and those belonging to blocks that have been reorganized out of the active chain are * indexed by block hash. This ensures that filter data for any block that becomes part of the * active chain can always be retrieved, alleviating timing concerns. * * The filters themselves are stored in flat files and referenced by the LevelDB entries. This * minimizes the amount of data written to LevelDB and keeps the database values constant size. The * disk location of the next block filter to be written (represented as a FlatFilePos) is stored * under the DB_FILTER_POS key. * * Keys for the height index have the type [DB_BLOCK_HEIGHT, uint32 (BE)]. The height is represented * as big-endian so that sequential reads of filters by height are fast. * Keys for the hash index have the type [DB_BLOCK_HASH, uint256]. */ constexpr uint8_t DB_BLOCK_HASH{'s'}; constexpr uint8_t DB_BLOCK_HEIGHT{'t'}; constexpr uint8_t DB_FILTER_POS{'P'}; constexpr unsigned int MAX_FLTR_FILE_SIZE = 0x1000000; // 16 MiB /** The pre-allocation chunk size for fltr?????.dat files */ constexpr unsigned int FLTR_FILE_CHUNK_SIZE = 0x100000; // 1 MiB /** Maximum size of the cfheaders cache * We have a limit to prevent a bug in filling this cache * potentially turning into an OOM. At 2000 entries, this cache * is big enough for a 2,000,000 length block chain, which * we should be enough until ~2047. */ constexpr size_t CF_HEADERS_CACHE_MAX_SZ{2000}; namespace { struct DBVal { uint256 hash; uint256 header; FlatFilePos pos; SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); } }; struct DBHeightKey { int height; explicit DBHeightKey(int height_in) : height(height_in) {} template<typename Stream> void Serialize(Stream& s) const { ser_writedata8(s, DB_BLOCK_HEIGHT); ser_writedata32be(s, height); } template<typename Stream> void Unserialize(Stream& s) { const uint8_t prefix{ser_readdata8(s)}; if (prefix != DB_BLOCK_HEIGHT) { throw std::ios_base::failure("Invalid format for block filter index DB height key"); } height = ser_readdata32be(s); } }; struct DBHashKey { uint256 hash; explicit DBHashKey(const uint256& hash_in) : hash(hash_in) {} SERIALIZE_METHODS(DBHashKey, obj) { uint8_t prefix{DB_BLOCK_HASH}; READWRITE(prefix); if (prefix != DB_BLOCK_HASH) { throw std::ios_base::failure("Invalid format for block filter index DB hash key"); } READWRITE(obj.hash); } }; }; // namespace static std::map<BlockFilterType, BlockFilterIndex> g_filter_indexes; BlockFilterIndex::BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe) : BaseIndex(std::move(chain), BlockFilterTypeName(filter_type) + " block filter index") , m_filter_type(filter_type) { const std::string& filter_name = BlockFilterTypeName(filter_type); if (filter_name.empty()) throw std::invalid_argument("unknown filter_type"); fs::path path = gArgs.GetDataDirNet() / "indexes" / "blockfilter" / fs::u8path(filter_name); fs::create_directories(path); m_db = std::make_unique<BaseIndex::DB>(path / "db", n_cache_size, f_memory, f_wipe); m_filter_fileseq = std::make_unique<FlatFileSeq>(std::move(path), "fltr", FLTR_FILE_CHUNK_SIZE); } bool BlockFilterIndex::CustomInit(const std::optional<interfaces::BlockKey>& block) { if (!m_db->Read(DB_FILTER_POS, m_next_filter_pos)) { // Check that the cause of the read failure is that the key does not exist. Any other errors // indicate database corruption or a disk failure, and starting the index would cause // further corruption. if (m_db->Exists(DB_FILTER_POS)) { return error("%s: Cannot read current %s state; index may be corrupted", __func__, GetName()); } // If the DB_FILTER_POS is not set, then initialize to the first location. m_next_filter_pos.nFile = 0; m_next_filter_pos.nPos = 0; } return true; } bool BlockFilterIndex::CustomCommit(CDBBatch& batch) { const FlatFilePos& pos = m_next_filter_pos; // Flush current filter file to disk. AutoFile file{m_filter_fileseq->Open(pos)}; if (file.IsNull()) { return error("%s: Failed to open filter file %d", __func__, pos.nFile); } if (!FileCommit(file.Get())) { return error("%s: Failed to commit filter file %d", __func__, pos.nFile); } batch.Write(DB_FILTER_POS, pos); return true; } bool BlockFilterIndex::ReadFilterFromDisk(const FlatFilePos& pos, const uint256& hash, BlockFilter& filter) const { AutoFile filein{m_filter_fileseq->Open(pos, true)}; if (filein.IsNull()) { return false; } // Check that the hash of the encoded_filter matches the one stored in the db. uint256 block_hash; std::vector<uint8_t> encoded_filter; try { filein >> block_hash >> encoded_filter; if (Hash(encoded_filter) != hash) return error("Checksum mismatch in filter decode."); filter = BlockFilter(GetFilterType(), block_hash, std::move(encoded_filter), /*skip_decode_check=*/true); } catch (const std::exception& e) { return error("%s: Failed to deserialize block filter from disk: %s", __func__, e.what()); } return true; } size_t BlockFilterIndex::WriteFilterToDisk(FlatFilePos& pos, const BlockFilter& filter) { assert(filter.GetFilterType() == GetFilterType()); size_t data_size = GetSerializeSize(filter.GetBlockHash()) + GetSerializeSize(filter.GetEncodedFilter()); // If writing the filter would overflow the file, flush and move to the next one. if (pos.nPos + data_size > MAX_FLTR_FILE_SIZE) { AutoFile last_file{m_filter_fileseq->Open(pos)}; if (last_file.IsNull()) { LogPrintf("%s: Failed to open filter file %d\n", __func__, pos.nFile); return 0; } if (!TruncateFile(last_file.Get(), pos.nPos)) { LogPrintf("%s: Failed to truncate filter file %d\n", __func__, pos.nFile); return 0; } if (!FileCommit(last_file.Get())) { LogPrintf("%s: Failed to commit filter file %d\n", __func__, pos.nFile); return 0; } pos.nFile++; pos.nPos = 0; } // Pre-allocate sufficient space for filter data. bool out_of_space; m_filter_fileseq->Allocate(pos, data_size, out_of_space); if (out_of_space) { LogPrintf("%s: out of disk space\n", __func__); return 0; } AutoFile fileout{m_filter_fileseq->Open(pos)}; if (fileout.IsNull()) { LogPrintf("%s: Failed to open filter file %d\n", __func__, pos.nFile); return 0; } fileout << filter.GetBlockHash() << filter.GetEncodedFilter(); return data_size; } bool BlockFilterIndex::CustomAppend(const interfaces::BlockInfo& block) { CBlockUndo block_undo; uint256 prev_header; if (block.height > 0) { // pindex variable gives indexing code access to node internals. It // will be removed in upcoming commit const CBlockIndex* pindex = WITH_LOCK(cs_main, return m_chainstate->m_blockman.LookupBlockIndex(block.hash)); if (!m_chainstate->m_blockman.UndoReadFromDisk(block_undo, *pindex)) { return false; } std::pair<uint256, DBVal> read_out; if (!m_db->Read(DBHeightKey(block.height - 1), read_out)) { return false; } uint256 expected_block_hash = *Assert(block.prev_hash); if (read_out.first != expected_block_hash) { return error("%s: previous block header belongs to unexpected block %s; expected %s", __func__, read_out.first.ToString(), expected_block_hash.ToString()); } prev_header = read_out.second.header; } BlockFilter filter(m_filter_type, *Assert(block.data), block_undo); size_t bytes_written = WriteFilterToDisk(m_next_filter_pos, filter); if (bytes_written == 0) return false; std::pair<uint256, DBVal> value; value.first = block.hash; value.second.hash = filter.GetHash(); value.second.header = filter.ComputeHeader(prev_header); value.second.pos = m_next_filter_pos; if (!m_db->Write(DBHeightKey(block.height), value)) { return false; } m_next_filter_pos.nPos += bytes_written; return true; } [[nodiscard]] static bool CopyHeightIndexToHashIndex(CDBIterator& db_it, CDBBatch& batch, const std::string& index_name, int start_height, int stop_height) { DBHeightKey key(start_height); db_it.Seek(key); for (int height = start_height; height <= stop_height; ++height) { if (!db_it.GetKey(key) || key.height != height) { return error("%s: unexpected key in %s: expected (%c, %d)", __func__, index_name, DB_BLOCK_HEIGHT, height); } std::pair<uint256, DBVal> value; if (!db_it.GetValue(value)) { return error("%s: unable to read value in %s at key (%c, %d)", __func__, index_name, DB_BLOCK_HEIGHT, height); } batch.Write(DBHashKey(value.first), std::move(value.second)); db_it.Next(); } return true; } bool BlockFilterIndex::CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) { CDBBatch batch(*m_db); std::unique_ptr<CDBIterator> db_it(m_db->NewIterator()); // During a reorg, we need to copy all filters for blocks that are getting disconnected from the // height index to the hash index so we can still find them when the height index entries are // overwritten. if (!CopyHeightIndexToHashIndex(*db_it, batch, m_name, new_tip.height, current_tip.height)) { return false; } // The latest filter position gets written in Commit by the call to the BaseIndex::Rewind. // But since this creates new references to the filter, the position should get updated here // atomically as well in case Commit fails. batch.Write(DB_FILTER_POS, m_next_filter_pos); if (!m_db->WriteBatch(batch)) return false; return true; } static bool LookupOne(const CDBWrapper& db, const CBlockIndex* block_index, DBVal& result) { // First check if the result is stored under the height index and the value there matches the // block hash. This should be the case if the block is on the active chain. std::pair<uint256, DBVal> read_out; if (!db.Read(DBHeightKey(block_index->nHeight), read_out)) { return false; } if (read_out.first == block_index->GetBlockHash()) { result = std::move(read_out.second); return true; } // If value at the height index corresponds to an different block, the result will be stored in // the hash index. return db.Read(DBHashKey(block_index->GetBlockHash()), result); } static bool LookupRange(CDBWrapper& db, const std::string& index_name, int start_height, const CBlockIndex* stop_index, std::vector<DBVal>& results) { if (start_height < 0) { return error("%s: start height (%d) is negative", __func__, start_height); } if (start_height > stop_index->nHeight) { return error("%s: start height (%d) is greater than stop height (%d)", __func__, start_height, stop_index->nHeight); } size_t results_size = static_cast<size_t>(stop_index->nHeight - start_height + 1); std::vector<std::pair<uint256, DBVal>> values(results_size); DBHeightKey key(start_height); std::unique_ptr<CDBIterator> db_it(db.NewIterator()); db_it->Seek(DBHeightKey(start_height)); for (int height = start_height; height <= stop_index->nHeight; ++height) { if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) { return false; } size_t i = static_cast<size_t>(height - start_height); if (!db_it->GetValue(values[i])) { return error("%s: unable to read value in %s at key (%c, %d)", __func__, index_name, DB_BLOCK_HEIGHT, height); } db_it->Next(); } results.resize(results_size); // Iterate backwards through block indexes collecting results in order to access the block hash // of each entry in case we need to look it up in the hash index. for (const CBlockIndex* block_index = stop_index; block_index && block_index->nHeight >= start_height; block_index = block_index->pprev) { uint256 block_hash = block_index->GetBlockHash(); size_t i = static_cast<size_t>(block_index->nHeight - start_height); if (block_hash == values[i].first) { results[i] = std::move(values[i].second); continue; } if (!db.Read(DBHashKey(block_hash), results[i])) { return error("%s: unable to read value in %s at key (%c, %s)", __func__, index_name, DB_BLOCK_HASH, block_hash.ToString()); } } return true; } bool BlockFilterIndex::LookupFilter(const CBlockIndex* block_index, BlockFilter& filter_out) const { DBVal entry; if (!LookupOne(*m_db, block_index, entry)) { return false; } return ReadFilterFromDisk(entry.pos, entry.hash, filter_out); } bool BlockFilterIndex::LookupFilterHeader(const CBlockIndex* block_index, uint256& header_out) { LOCK(m_cs_headers_cache); bool is_checkpoint{block_index->nHeight % CFCHECKPT_INTERVAL == 0}; if (is_checkpoint) { // Try to find the block in the headers cache if this is a checkpoint height. auto header = m_headers_cache.find(block_index->GetBlockHash()); if (header != m_headers_cache.end()) { header_out = header->second; return true; } } DBVal entry; if (!LookupOne(*m_db, block_index, entry)) { return false; } if (is_checkpoint && m_headers_cache.size() < CF_HEADERS_CACHE_MAX_SZ) { // Add to the headers cache if this is a checkpoint height. m_headers_cache.emplace(block_index->GetBlockHash(), entry.header); } header_out = entry.header; return true; } bool BlockFilterIndex::LookupFilterRange(int start_height, const CBlockIndex* stop_index, std::vector<BlockFilter>& filters_out) const { std::vector<DBVal> entries; if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) { return false; } filters_out.resize(entries.size()); auto filter_pos_it = filters_out.begin(); for (const auto& entry : entries) { if (!ReadFilterFromDisk(entry.pos, entry.hash, *filter_pos_it)) { return false; } ++filter_pos_it; } return true; } bool BlockFilterIndex::LookupFilterHashRange(int start_height, const CBlockIndex* stop_index, std::vector<uint256>& hashes_out) const { std::vector<DBVal> entries; if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) { return false; } hashes_out.clear(); hashes_out.reserve(entries.size()); for (const auto& entry : entries) { hashes_out.push_back(entry.hash); } return true; } BlockFilterIndex* GetBlockFilterIndex(BlockFilterType filter_type) { auto it = g_filter_indexes.find(filter_type); return it != g_filter_indexes.end() ? &it->second : nullptr; } void ForEachBlockFilterIndex(std::function<void (BlockFilterIndex&)> fn) { for (auto& entry : g_filter_indexes) fn(entry.second); } bool InitBlockFilterIndex(std::function<std::unique_ptr<interfaces::Chain>()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe) { auto result = g_filter_indexes.emplace(std::piecewise_construct, std::forward_as_tuple(filter_type), std::forward_as_tuple(make_chain(), filter_type, n_cache_size, f_memory, f_wipe)); return result.second; } bool DestroyBlockFilterIndex(BlockFilterType filter_type) { return g_filter_indexes.erase(filter_type); } void DestroyAllBlockFilterIndexes() { g_filter_indexes.clear(); }
0
bitcoin/src
bitcoin/src/index/blockfilterindex.h
// Copyright (c) 2018-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INDEX_BLOCKFILTERINDEX_H #define BITCOIN_INDEX_BLOCKFILTERINDEX_H #include <attributes.h> #include <blockfilter.h> #include <chain.h> #include <flatfile.h> #include <index/base.h> #include <util/hasher.h> #include <unordered_map> static const char* const DEFAULT_BLOCKFILTERINDEX = "0"; /** Interval between compact filter checkpoints. See BIP 157. */ static constexpr int CFCHECKPT_INTERVAL = 1000; /** * BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of * blocks by height. An index is constructed for each supported filter type with its own database * (ie. filter data for different types are stored in separate databases). * * This index is used to serve BIP 157 net requests. */ class BlockFilterIndex final : public BaseIndex { private: BlockFilterType m_filter_type; std::unique_ptr<BaseIndex::DB> m_db; FlatFilePos m_next_filter_pos; std::unique_ptr<FlatFileSeq> m_filter_fileseq; bool ReadFilterFromDisk(const FlatFilePos& pos, const uint256& hash, BlockFilter& filter) const; size_t WriteFilterToDisk(FlatFilePos& pos, const BlockFilter& filter); Mutex m_cs_headers_cache; /** cache of block hash to filter header, to avoid disk access when responding to getcfcheckpt. */ std::unordered_map<uint256, uint256, FilterHeaderHasher> m_headers_cache GUARDED_BY(m_cs_headers_cache); bool AllowPrune() const override { return true; } protected: bool CustomInit(const std::optional<interfaces::BlockKey>& block) override; bool CustomCommit(CDBBatch& batch) override; bool CustomAppend(const interfaces::BlockInfo& block) override; bool CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) override; BaseIndex::DB& GetDB() const LIFETIMEBOUND override { return *m_db; } public: /** Constructs the index, which becomes available to be queried. */ explicit BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory = false, bool f_wipe = false); BlockFilterType GetFilterType() const { return m_filter_type; } /** Get a single filter by block. */ bool LookupFilter(const CBlockIndex* block_index, BlockFilter& filter_out) const; /** Get a single filter header by block. */ bool LookupFilterHeader(const CBlockIndex* block_index, uint256& header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache); /** Get a range of filters between two heights on a chain. */ bool LookupFilterRange(int start_height, const CBlockIndex* stop_index, std::vector<BlockFilter>& filters_out) const; /** Get a range of filter hashes between two heights on a chain. */ bool LookupFilterHashRange(int start_height, const CBlockIndex* stop_index, std::vector<uint256>& hashes_out) const; }; /** * Get a block filter index by type. Returns nullptr if index has not been initialized or was * already destroyed. */ BlockFilterIndex* GetBlockFilterIndex(BlockFilterType filter_type); /** Iterate over all running block filter indexes, invoking fn on each. */ void ForEachBlockFilterIndex(std::function<void (BlockFilterIndex&)> fn); /** * Initialize a block filter index for the given type if one does not already exist. Returns true if * a new index is created and false if one has already been initialized. */ bool InitBlockFilterIndex(std::function<std::unique_ptr<interfaces::Chain>()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory = false, bool f_wipe = false); /** * Destroy the block filter index with the given type. Returns false if no such index exists. This * just releases the allocated memory and closes the database connection, it does not delete the * index data. */ bool DestroyBlockFilterIndex(BlockFilterType filter_type); /** Destroy all open block filter indexes. */ void DestroyAllBlockFilterIndexes(); #endif // BITCOIN_INDEX_BLOCKFILTERINDEX_H
0
bitcoin/src
bitcoin/src/index/base.cpp
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <common/args.h> #include <index/base.h> #include <interfaces/chain.h> #include <kernel/chain.h> #include <logging.h> #include <node/abort.h> #include <node/blockstorage.h> #include <node/context.h> #include <node/database_args.h> #include <node/interface_ui.h> #include <tinyformat.h> #include <util/thread.h> #include <util/translation.h> #include <validation.h> // For g_chainman #include <warnings.h> #include <string> #include <utility> constexpr uint8_t DB_BEST_BLOCK{'B'}; constexpr auto SYNC_LOG_INTERVAL{30s}; constexpr auto SYNC_LOCATOR_WRITE_INTERVAL{30s}; template <typename... Args> void BaseIndex::FatalErrorf(const char* fmt, const Args&... args) { auto message = tfm::format(fmt, args...); node::AbortNode(m_chain->context()->shutdown, m_chain->context()->exit_status, message); } CBlockLocator GetLocator(interfaces::Chain& chain, const uint256& block_hash) { CBlockLocator locator; bool found = chain.findBlock(block_hash, interfaces::FoundBlock().locator(locator)); assert(found); assert(!locator.IsNull()); return locator; } BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) : CDBWrapper{DBParams{ .path = path, .cache_bytes = n_cache_size, .memory_only = f_memory, .wipe_data = f_wipe, .obfuscate = f_obfuscate, .options = [] { DBOptions options; node::ReadDatabaseArgs(gArgs, options); return options; }()}} {} bool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const { bool success = Read(DB_BEST_BLOCK, locator); if (!success) { locator.SetNull(); } return success; } void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) { batch.Write(DB_BEST_BLOCK, locator); } BaseIndex::BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name) : m_chain{std::move(chain)}, m_name{std::move(name)} {} BaseIndex::~BaseIndex() { Interrupt(); Stop(); } bool BaseIndex::Init() { AssertLockNotHeld(cs_main); // May need reset if index is being restarted. m_interrupt.reset(); // m_chainstate member gives indexing code access to node internals. It is // removed in followup https://github.com/bitcoin/bitcoin/pull/24230 m_chainstate = WITH_LOCK(::cs_main, return &m_chain->context()->chainman->GetChainstateForIndexing()); // Register to validation interface before setting the 'm_synced' flag, so that // callbacks are not missed once m_synced is true. RegisterValidationInterface(this); CBlockLocator locator; if (!GetDB().ReadBestBlock(locator)) { locator.SetNull(); } LOCK(cs_main); CChain& index_chain = m_chainstate->m_chain; if (locator.IsNull()) { SetBestBlockIndex(nullptr); } else { // Setting the best block to the locator's top block. If it is not part of the // best chain, we will rewind to the fork point during index sync const CBlockIndex* locator_index{m_chainstate->m_blockman.LookupBlockIndex(locator.vHave.at(0))}; if (!locator_index) { return InitError(strprintf(Untranslated("%s: best block of the index not found. Please rebuild the index."), GetName())); } SetBestBlockIndex(locator_index); } // Child init const CBlockIndex* start_block = m_best_block_index.load(); if (!CustomInit(start_block ? std::make_optional(interfaces::BlockKey{start_block->GetBlockHash(), start_block->nHeight}) : std::nullopt)) { return false; } // Note: this will latch to true immediately if the user starts up with an empty // datadir and an index enabled. If this is the case, indexation will happen solely // via `BlockConnected` signals until, possibly, the next restart. m_synced = start_block == index_chain.Tip(); m_init = true; return true; } static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev, CChain& chain) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); if (!pindex_prev) { return chain.Genesis(); } const CBlockIndex* pindex = chain.Next(pindex_prev); if (pindex) { return pindex; } return chain.Next(chain.FindFork(pindex_prev)); } void BaseIndex::ThreadSync() { const CBlockIndex* pindex = m_best_block_index.load(); if (!m_synced) { std::chrono::steady_clock::time_point last_log_time{0s}; std::chrono::steady_clock::time_point last_locator_write_time{0s}; while (true) { if (m_interrupt) { LogPrintf("%s: m_interrupt set; exiting ThreadSync\n", GetName()); SetBestBlockIndex(pindex); // No need to handle errors in Commit. If it fails, the error will be already be // logged. The best way to recover is to continue, as index cannot be corrupted by // a missed commit to disk for an advanced index state. Commit(); return; } { LOCK(cs_main); const CBlockIndex* pindex_next = NextSyncBlock(pindex, m_chainstate->m_chain); if (!pindex_next) { SetBestBlockIndex(pindex); m_synced = true; // No need to handle errors in Commit. See rationale above. Commit(); break; } if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) { FatalErrorf("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName()); return; } pindex = pindex_next; } auto current_time{std::chrono::steady_clock::now()}; if (last_log_time + SYNC_LOG_INTERVAL < current_time) { LogPrintf("Syncing %s with block chain from height %d\n", GetName(), pindex->nHeight); last_log_time = current_time; } if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) { SetBestBlockIndex(pindex->pprev); last_locator_write_time = current_time; // No need to handle errors in Commit. See rationale above. Commit(); } CBlock block; interfaces::BlockInfo block_info = kernel::MakeBlockInfo(pindex); if (!m_chainstate->m_blockman.ReadBlockFromDisk(block, *pindex)) { FatalErrorf("%s: Failed to read block %s from disk", __func__, pindex->GetBlockHash().ToString()); return; } else { block_info.data = &block; } if (!CustomAppend(block_info)) { FatalErrorf("%s: Failed to write block %s to index database", __func__, pindex->GetBlockHash().ToString()); return; } } } if (pindex) { LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight); } else { LogPrintf("%s is enabled\n", GetName()); } } bool BaseIndex::Commit() { // Don't commit anything if we haven't indexed any block yet // (this could happen if init is interrupted). bool ok = m_best_block_index != nullptr; if (ok) { CDBBatch batch(GetDB()); ok = CustomCommit(batch); if (ok) { GetDB().WriteBestBlock(batch, GetLocator(*m_chain, m_best_block_index.load()->GetBlockHash())); ok = GetDB().WriteBatch(batch); } } if (!ok) { return error("%s: Failed to commit latest %s state", __func__, GetName()); } return true; } bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip) { assert(current_tip == m_best_block_index); assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip); if (!CustomRewind({current_tip->GetBlockHash(), current_tip->nHeight}, {new_tip->GetBlockHash(), new_tip->nHeight})) { return false; } // In the case of a reorg, ensure persisted block locator is not stale. // Pruning has a minimum of 288 blocks-to-keep and getting the index // out of sync may be possible but a users fault. // In case we reorg beyond the pruned depth, ReadBlockFromDisk would // throw and lead to a graceful shutdown SetBestBlockIndex(new_tip); if (!Commit()) { // If commit fails, revert the best block index to avoid corruption. SetBestBlockIndex(current_tip); return false; } return true; } void BaseIndex::BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) { // Ignore events from the assumed-valid chain; we will process its blocks // (sequentially) after it is fully verified by the background chainstate. This // is to avoid any out-of-order indexing. // // TODO at some point we could parameterize whether a particular index can be // built out of order, but for now just do the conservative simple thing. if (role == ChainstateRole::ASSUMEDVALID) { return; } // Ignore BlockConnected signals until we have fully indexed the chain. if (!m_synced) { return; } const CBlockIndex* best_block_index = m_best_block_index.load(); if (!best_block_index) { if (pindex->nHeight != 0) { FatalErrorf("%s: First block connected is not the genesis block (height=%d)", __func__, pindex->nHeight); return; } } else { // Ensure block connects to an ancestor of the current best block. This should be the case // most of the time, but may not be immediately after the sync thread catches up and sets // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are // in the ValidationInterface queue backlog even after the sync thread has caught up to the // new chain tip. In this unlikely event, log a warning and let the queue clear. if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) { LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " "known best chain (tip=%s); not updating index\n", __func__, pindex->GetBlockHash().ToString(), best_block_index->GetBlockHash().ToString()); return; } if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) { FatalErrorf("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName()); return; } } interfaces::BlockInfo block_info = kernel::MakeBlockInfo(pindex, block.get()); if (CustomAppend(block_info)) { // Setting the best block index is intentionally the last step of this // function, so BlockUntilSyncedToCurrentChain callers waiting for the // best block index to be updated can rely on the block being fully // processed, and the index object being safe to delete. SetBestBlockIndex(pindex); } else { FatalErrorf("%s: Failed to write block %s to index", __func__, pindex->GetBlockHash().ToString()); return; } } void BaseIndex::ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) { // Ignore events from the assumed-valid chain; we will process its blocks // (sequentially) after it is fully verified by the background chainstate. if (role == ChainstateRole::ASSUMEDVALID) { return; } if (!m_synced) { return; } const uint256& locator_tip_hash = locator.vHave.front(); const CBlockIndex* locator_tip_index; { LOCK(cs_main); locator_tip_index = m_chainstate->m_blockman.LookupBlockIndex(locator_tip_hash); } if (!locator_tip_index) { FatalErrorf("%s: First block (hash=%s) in locator was not found", __func__, locator_tip_hash.ToString()); return; } // This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail // immediately after the sync thread catches up and sets m_synced. Consider the case where // there is a reorg and the blocks on the stale branch are in the ValidationInterface queue // backlog even after the sync thread has caught up to the new chain tip. In this unlikely // event, log a warning and let the queue clear. const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) { LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known best " "chain (tip=%s); not writing index locator\n", __func__, locator_tip_hash.ToString(), best_block_index->GetBlockHash().ToString()); return; } // No need to handle errors in Commit. If it fails, the error will be already be logged. The // best way to recover is to continue, as index cannot be corrupted by a missed commit to disk // for an advanced index state. Commit(); } bool BaseIndex::BlockUntilSyncedToCurrentChain() const { AssertLockNotHeld(cs_main); if (!m_synced) { return false; } { // Skip the queue-draining stuff if we know we're caught up with // m_chain.Tip(). LOCK(cs_main); const CBlockIndex* chain_tip = m_chainstate->m_chain.Tip(); const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) { return true; } } LogPrintf("%s: %s is catching up on block notifications\n", __func__, GetName()); SyncWithValidationInterfaceQueue(); return true; } void BaseIndex::Interrupt() { m_interrupt(); } bool BaseIndex::StartBackgroundSync() { if (!m_init) throw std::logic_error("Error: Cannot start a non-initialized index"); m_thread_sync = std::thread(&util::TraceThread, GetName(), [this] { ThreadSync(); }); return true; } void BaseIndex::Stop() { UnregisterValidationInterface(this); if (m_thread_sync.joinable()) { m_thread_sync.join(); } } IndexSummary BaseIndex::GetSummary() const { IndexSummary summary{}; summary.name = GetName(); summary.synced = m_synced; if (const auto& pindex = m_best_block_index.load()) { summary.best_block_height = pindex->nHeight; summary.best_block_hash = pindex->GetBlockHash(); } else { summary.best_block_height = 0; summary.best_block_hash = m_chain->getBlockHash(0); } return summary; } void BaseIndex::SetBestBlockIndex(const CBlockIndex* block) { assert(!m_chainstate->m_blockman.IsPruneMode() || AllowPrune()); if (AllowPrune() && block) { node::PruneLockInfo prune_lock; prune_lock.height_first = block->nHeight; WITH_LOCK(::cs_main, m_chainstate->m_blockman.UpdatePruneLock(GetName(), prune_lock)); } // Intentionally set m_best_block_index as the last step in this function, // after updating prune locks above, and after making any other references // to *this, so the BlockUntilSyncedToCurrentChain function (which checks // m_best_block_index as an optimization) can be used to wait for the last // BlockConnected notification and safely assume that prune locks are // updated and that the index object is safe to delete. m_best_block_index = block; }
0
bitcoin/src
bitcoin/src/index/disktxpos.h
// Copyright (c) 2019-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INDEX_DISKTXPOS_H #define BITCOIN_INDEX_DISKTXPOS_H #include <flatfile.h> #include <serialize.h> struct CDiskTxPos : public FlatFilePos { unsigned int nTxOffset{0}; // after header SERIALIZE_METHODS(CDiskTxPos, obj) { READWRITE(AsBase<FlatFilePos>(obj), VARINT(obj.nTxOffset)); } CDiskTxPos(const FlatFilePos &blockIn, unsigned int nTxOffsetIn) : FlatFilePos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { } CDiskTxPos() {} }; #endif // BITCOIN_INDEX_DISKTXPOS_H
0
bitcoin/src
bitcoin/src/index/coinstatsindex.h
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INDEX_COINSTATSINDEX_H #define BITCOIN_INDEX_COINSTATSINDEX_H #include <crypto/muhash.h> #include <index/base.h> class CBlockIndex; class CDBBatch; namespace kernel { struct CCoinsStats; } static constexpr bool DEFAULT_COINSTATSINDEX{false}; /** * CoinStatsIndex maintains statistics on the UTXO set. */ class CoinStatsIndex final : public BaseIndex { private: std::unique_ptr<BaseIndex::DB> m_db; MuHash3072 m_muhash; uint64_t m_transaction_output_count{0}; uint64_t m_bogo_size{0}; CAmount m_total_amount{0}; CAmount m_total_subsidy{0}; CAmount m_total_unspendable_amount{0}; CAmount m_total_prevout_spent_amount{0}; CAmount m_total_new_outputs_ex_coinbase_amount{0}; CAmount m_total_coinbase_amount{0}; CAmount m_total_unspendables_genesis_block{0}; CAmount m_total_unspendables_bip30{0}; CAmount m_total_unspendables_scripts{0}; CAmount m_total_unspendables_unclaimed_rewards{0}; [[nodiscard]] bool ReverseBlock(const CBlock& block, const CBlockIndex* pindex); bool AllowPrune() const override { return true; } protected: bool CustomInit(const std::optional<interfaces::BlockKey>& block) override; bool CustomCommit(CDBBatch& batch) override; bool CustomAppend(const interfaces::BlockInfo& block) override; bool CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) override; BaseIndex::DB& GetDB() const override { return *m_db; } public: // Constructs the index, which becomes available to be queried. explicit CoinStatsIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory = false, bool f_wipe = false); // Look up stats for a specific block using CBlockIndex std::optional<kernel::CCoinsStats> LookUpStats(const CBlockIndex& block_index) const; }; /// The global UTXO set hash object. extern std::unique_ptr<CoinStatsIndex> g_coin_stats_index; #endif // BITCOIN_INDEX_COINSTATSINDEX_H
0
bitcoin/src
bitcoin/src/index/txindex.h
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INDEX_TXINDEX_H #define BITCOIN_INDEX_TXINDEX_H #include <index/base.h> static constexpr bool DEFAULT_TXINDEX{false}; /** * TxIndex is used to look up transactions included in the blockchain by hash. * The index is written to a LevelDB database and records the filesystem * location of each transaction by transaction hash. */ class TxIndex final : public BaseIndex { protected: class DB; private: const std::unique_ptr<DB> m_db; bool AllowPrune() const override { return false; } protected: bool CustomAppend(const interfaces::BlockInfo& block) override; BaseIndex::DB& GetDB() const override; public: /// Constructs the index, which becomes available to be queried. explicit TxIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory = false, bool f_wipe = false); // Destructor is declared because this class contains a unique_ptr to an incomplete type. virtual ~TxIndex() override; /// Look up a transaction by hash. /// /// @param[in] tx_hash The hash of the transaction to be returned. /// @param[out] block_hash The hash of the block the transaction is found in. /// @param[out] tx The transaction itself. /// @return true if transaction is found, false otherwise bool FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const; }; /// The global transaction index, used in GetTransaction. May be null. extern std::unique_ptr<TxIndex> g_txindex; #endif // BITCOIN_INDEX_TXINDEX_H
0
bitcoin/src
bitcoin/src/index/coinstatsindex.cpp
// Copyright (c) 2020-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <coins.h> #include <common/args.h> #include <crypto/muhash.h> #include <index/coinstatsindex.h> #include <kernel/coinstats.h> #include <logging.h> #include <node/blockstorage.h> #include <serialize.h> #include <txdb.h> #include <undo.h> #include <validation.h> using kernel::ApplyCoinHash; using kernel::CCoinsStats; using kernel::GetBogoSize; using kernel::RemoveCoinHash; static constexpr uint8_t DB_BLOCK_HASH{'s'}; static constexpr uint8_t DB_BLOCK_HEIGHT{'t'}; static constexpr uint8_t DB_MUHASH{'M'}; namespace { struct DBVal { uint256 muhash; uint64_t transaction_output_count; uint64_t bogo_size; CAmount total_amount; CAmount total_subsidy; CAmount total_unspendable_amount; CAmount total_prevout_spent_amount; CAmount total_new_outputs_ex_coinbase_amount; CAmount total_coinbase_amount; CAmount total_unspendables_genesis_block; CAmount total_unspendables_bip30; CAmount total_unspendables_scripts; CAmount total_unspendables_unclaimed_rewards; SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.muhash); READWRITE(obj.transaction_output_count); READWRITE(obj.bogo_size); READWRITE(obj.total_amount); READWRITE(obj.total_subsidy); READWRITE(obj.total_unspendable_amount); READWRITE(obj.total_prevout_spent_amount); READWRITE(obj.total_new_outputs_ex_coinbase_amount); READWRITE(obj.total_coinbase_amount); READWRITE(obj.total_unspendables_genesis_block); READWRITE(obj.total_unspendables_bip30); READWRITE(obj.total_unspendables_scripts); READWRITE(obj.total_unspendables_unclaimed_rewards); } }; struct DBHeightKey { int height; explicit DBHeightKey(int height_in) : height(height_in) {} template <typename Stream> void Serialize(Stream& s) const { ser_writedata8(s, DB_BLOCK_HEIGHT); ser_writedata32be(s, height); } template <typename Stream> void Unserialize(Stream& s) { const uint8_t prefix{ser_readdata8(s)}; if (prefix != DB_BLOCK_HEIGHT) { throw std::ios_base::failure("Invalid format for coinstatsindex DB height key"); } height = ser_readdata32be(s); } }; struct DBHashKey { uint256 block_hash; explicit DBHashKey(const uint256& hash_in) : block_hash(hash_in) {} SERIALIZE_METHODS(DBHashKey, obj) { uint8_t prefix{DB_BLOCK_HASH}; READWRITE(prefix); if (prefix != DB_BLOCK_HASH) { throw std::ios_base::failure("Invalid format for coinstatsindex DB hash key"); } READWRITE(obj.block_hash); } }; }; // namespace std::unique_ptr<CoinStatsIndex> g_coin_stats_index; CoinStatsIndex::CoinStatsIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory, bool f_wipe) : BaseIndex(std::move(chain), "coinstatsindex") { fs::path path{gArgs.GetDataDirNet() / "indexes" / "coinstats"}; fs::create_directories(path); m_db = std::make_unique<CoinStatsIndex::DB>(path / "db", n_cache_size, f_memory, f_wipe); } bool CoinStatsIndex::CustomAppend(const interfaces::BlockInfo& block) { CBlockUndo block_undo; const CAmount block_subsidy{GetBlockSubsidy(block.height, Params().GetConsensus())}; m_total_subsidy += block_subsidy; // Ignore genesis block if (block.height > 0) { // pindex variable gives indexing code access to node internals. It // will be removed in upcoming commit const CBlockIndex* pindex = WITH_LOCK(cs_main, return m_chainstate->m_blockman.LookupBlockIndex(block.hash)); if (!m_chainstate->m_blockman.UndoReadFromDisk(block_undo, *pindex)) { return false; } std::pair<uint256, DBVal> read_out; if (!m_db->Read(DBHeightKey(block.height - 1), read_out)) { return false; } uint256 expected_block_hash{*Assert(block.prev_hash)}; if (read_out.first != expected_block_hash) { LogPrintf("WARNING: previous block header belongs to unexpected block %s; expected %s\n", read_out.first.ToString(), expected_block_hash.ToString()); if (!m_db->Read(DBHashKey(expected_block_hash), read_out)) { return error("%s: previous block header not found; expected %s", __func__, expected_block_hash.ToString()); } } // Add the new utxos created from the block assert(block.data); for (size_t i = 0; i < block.data->vtx.size(); ++i) { const auto& tx{block.data->vtx.at(i)}; // Skip duplicate txid coinbase transactions (BIP30). if (IsBIP30Unspendable(*pindex) && tx->IsCoinBase()) { m_total_unspendable_amount += block_subsidy; m_total_unspendables_bip30 += block_subsidy; continue; } for (uint32_t j = 0; j < tx->vout.size(); ++j) { const CTxOut& out{tx->vout[j]}; Coin coin{out, block.height, tx->IsCoinBase()}; COutPoint outpoint{tx->GetHash(), j}; // Skip unspendable coins if (coin.out.scriptPubKey.IsUnspendable()) { m_total_unspendable_amount += coin.out.nValue; m_total_unspendables_scripts += coin.out.nValue; continue; } ApplyCoinHash(m_muhash, outpoint, coin); if (tx->IsCoinBase()) { m_total_coinbase_amount += coin.out.nValue; } else { m_total_new_outputs_ex_coinbase_amount += coin.out.nValue; } ++m_transaction_output_count; m_total_amount += coin.out.nValue; m_bogo_size += GetBogoSize(coin.out.scriptPubKey); } // The coinbase tx has no undo data since no former output is spent if (!tx->IsCoinBase()) { const auto& tx_undo{block_undo.vtxundo.at(i - 1)}; for (size_t j = 0; j < tx_undo.vprevout.size(); ++j) { Coin coin{tx_undo.vprevout[j]}; COutPoint outpoint{tx->vin[j].prevout.hash, tx->vin[j].prevout.n}; RemoveCoinHash(m_muhash, outpoint, coin); m_total_prevout_spent_amount += coin.out.nValue; --m_transaction_output_count; m_total_amount -= coin.out.nValue; m_bogo_size -= GetBogoSize(coin.out.scriptPubKey); } } } } else { // genesis block m_total_unspendable_amount += block_subsidy; m_total_unspendables_genesis_block += block_subsidy; } // If spent prevouts + block subsidy are still a higher amount than // new outputs + coinbase + current unspendable amount this means // the miner did not claim the full block reward. Unclaimed block // rewards are also unspendable. const CAmount unclaimed_rewards{(m_total_prevout_spent_amount + m_total_subsidy) - (m_total_new_outputs_ex_coinbase_amount + m_total_coinbase_amount + m_total_unspendable_amount)}; m_total_unspendable_amount += unclaimed_rewards; m_total_unspendables_unclaimed_rewards += unclaimed_rewards; std::pair<uint256, DBVal> value; value.first = block.hash; value.second.transaction_output_count = m_transaction_output_count; value.second.bogo_size = m_bogo_size; value.second.total_amount = m_total_amount; value.second.total_subsidy = m_total_subsidy; value.second.total_unspendable_amount = m_total_unspendable_amount; value.second.total_prevout_spent_amount = m_total_prevout_spent_amount; value.second.total_new_outputs_ex_coinbase_amount = m_total_new_outputs_ex_coinbase_amount; value.second.total_coinbase_amount = m_total_coinbase_amount; value.second.total_unspendables_genesis_block = m_total_unspendables_genesis_block; value.second.total_unspendables_bip30 = m_total_unspendables_bip30; value.second.total_unspendables_scripts = m_total_unspendables_scripts; value.second.total_unspendables_unclaimed_rewards = m_total_unspendables_unclaimed_rewards; uint256 out; m_muhash.Finalize(out); value.second.muhash = out; // Intentionally do not update DB_MUHASH here so it stays in sync with // DB_BEST_BLOCK, and the index is not corrupted if there is an unclean shutdown. return m_db->Write(DBHeightKey(block.height), value); } [[nodiscard]] static bool CopyHeightIndexToHashIndex(CDBIterator& db_it, CDBBatch& batch, const std::string& index_name, int start_height, int stop_height) { DBHeightKey key{start_height}; db_it.Seek(key); for (int height = start_height; height <= stop_height; ++height) { if (!db_it.GetKey(key) || key.height != height) { return error("%s: unexpected key in %s: expected (%c, %d)", __func__, index_name, DB_BLOCK_HEIGHT, height); } std::pair<uint256, DBVal> value; if (!db_it.GetValue(value)) { return error("%s: unable to read value in %s at key (%c, %d)", __func__, index_name, DB_BLOCK_HEIGHT, height); } batch.Write(DBHashKey(value.first), std::move(value.second)); db_it.Next(); } return true; } bool CoinStatsIndex::CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) { CDBBatch batch(*m_db); std::unique_ptr<CDBIterator> db_it(m_db->NewIterator()); // During a reorg, we need to copy all hash digests for blocks that are // getting disconnected from the height index to the hash index so we can // still find them when the height index entries are overwritten. if (!CopyHeightIndexToHashIndex(*db_it, batch, m_name, new_tip.height, current_tip.height)) { return false; } if (!m_db->WriteBatch(batch)) return false; { LOCK(cs_main); const CBlockIndex* iter_tip{m_chainstate->m_blockman.LookupBlockIndex(current_tip.hash)}; const CBlockIndex* new_tip_index{m_chainstate->m_blockman.LookupBlockIndex(new_tip.hash)}; do { CBlock block; if (!m_chainstate->m_blockman.ReadBlockFromDisk(block, *iter_tip)) { return error("%s: Failed to read block %s from disk", __func__, iter_tip->GetBlockHash().ToString()); } if (!ReverseBlock(block, iter_tip)) { return false; // failure cause logged internally } iter_tip = iter_tip->GetAncestor(iter_tip->nHeight - 1); } while (new_tip_index != iter_tip); } return true; } static bool LookUpOne(const CDBWrapper& db, const interfaces::BlockKey& block, DBVal& result) { // First check if the result is stored under the height index and the value // there matches the block hash. This should be the case if the block is on // the active chain. std::pair<uint256, DBVal> read_out; if (!db.Read(DBHeightKey(block.height), read_out)) { return false; } if (read_out.first == block.hash) { result = std::move(read_out.second); return true; } // If value at the height index corresponds to an different block, the // result will be stored in the hash index. return db.Read(DBHashKey(block.hash), result); } std::optional<CCoinsStats> CoinStatsIndex::LookUpStats(const CBlockIndex& block_index) const { CCoinsStats stats{block_index.nHeight, block_index.GetBlockHash()}; stats.index_used = true; DBVal entry; if (!LookUpOne(*m_db, {block_index.GetBlockHash(), block_index.nHeight}, entry)) { return std::nullopt; } stats.hashSerialized = entry.muhash; stats.nTransactionOutputs = entry.transaction_output_count; stats.nBogoSize = entry.bogo_size; stats.total_amount = entry.total_amount; stats.total_subsidy = entry.total_subsidy; stats.total_unspendable_amount = entry.total_unspendable_amount; stats.total_prevout_spent_amount = entry.total_prevout_spent_amount; stats.total_new_outputs_ex_coinbase_amount = entry.total_new_outputs_ex_coinbase_amount; stats.total_coinbase_amount = entry.total_coinbase_amount; stats.total_unspendables_genesis_block = entry.total_unspendables_genesis_block; stats.total_unspendables_bip30 = entry.total_unspendables_bip30; stats.total_unspendables_scripts = entry.total_unspendables_scripts; stats.total_unspendables_unclaimed_rewards = entry.total_unspendables_unclaimed_rewards; return stats; } bool CoinStatsIndex::CustomInit(const std::optional<interfaces::BlockKey>& block) { if (!m_db->Read(DB_MUHASH, m_muhash)) { // Check that the cause of the read failure is that the key does not // exist. Any other errors indicate database corruption or a disk // failure, and starting the index would cause further corruption. if (m_db->Exists(DB_MUHASH)) { return error("%s: Cannot read current %s state; index may be corrupted", __func__, GetName()); } } if (block) { DBVal entry; if (!LookUpOne(*m_db, *block, entry)) { return error("%s: Cannot read current %s state; index may be corrupted", __func__, GetName()); } uint256 out; m_muhash.Finalize(out); if (entry.muhash != out) { return error("%s: Cannot read current %s state; index may be corrupted", __func__, GetName()); } m_transaction_output_count = entry.transaction_output_count; m_bogo_size = entry.bogo_size; m_total_amount = entry.total_amount; m_total_subsidy = entry.total_subsidy; m_total_unspendable_amount = entry.total_unspendable_amount; m_total_prevout_spent_amount = entry.total_prevout_spent_amount; m_total_new_outputs_ex_coinbase_amount = entry.total_new_outputs_ex_coinbase_amount; m_total_coinbase_amount = entry.total_coinbase_amount; m_total_unspendables_genesis_block = entry.total_unspendables_genesis_block; m_total_unspendables_bip30 = entry.total_unspendables_bip30; m_total_unspendables_scripts = entry.total_unspendables_scripts; m_total_unspendables_unclaimed_rewards = entry.total_unspendables_unclaimed_rewards; } return true; } bool CoinStatsIndex::CustomCommit(CDBBatch& batch) { // DB_MUHASH should always be committed in a batch together with DB_BEST_BLOCK // to prevent an inconsistent state of the DB. batch.Write(DB_MUHASH, m_muhash); return true; } // Reverse a single block as part of a reorg bool CoinStatsIndex::ReverseBlock(const CBlock& block, const CBlockIndex* pindex) { CBlockUndo block_undo; std::pair<uint256, DBVal> read_out; const CAmount block_subsidy{GetBlockSubsidy(pindex->nHeight, Params().GetConsensus())}; m_total_subsidy -= block_subsidy; // Ignore genesis block if (pindex->nHeight > 0) { if (!m_chainstate->m_blockman.UndoReadFromDisk(block_undo, *pindex)) { return false; } if (!m_db->Read(DBHeightKey(pindex->nHeight - 1), read_out)) { return false; } uint256 expected_block_hash{pindex->pprev->GetBlockHash()}; if (read_out.first != expected_block_hash) { LogPrintf("WARNING: previous block header belongs to unexpected block %s; expected %s\n", read_out.first.ToString(), expected_block_hash.ToString()); if (!m_db->Read(DBHashKey(expected_block_hash), read_out)) { return error("%s: previous block header not found; expected %s", __func__, expected_block_hash.ToString()); } } } // Remove the new UTXOs that were created from the block for (size_t i = 0; i < block.vtx.size(); ++i) { const auto& tx{block.vtx.at(i)}; for (uint32_t j = 0; j < tx->vout.size(); ++j) { const CTxOut& out{tx->vout[j]}; COutPoint outpoint{tx->GetHash(), j}; Coin coin{out, pindex->nHeight, tx->IsCoinBase()}; // Skip unspendable coins if (coin.out.scriptPubKey.IsUnspendable()) { m_total_unspendable_amount -= coin.out.nValue; m_total_unspendables_scripts -= coin.out.nValue; continue; } RemoveCoinHash(m_muhash, outpoint, coin); if (tx->IsCoinBase()) { m_total_coinbase_amount -= coin.out.nValue; } else { m_total_new_outputs_ex_coinbase_amount -= coin.out.nValue; } --m_transaction_output_count; m_total_amount -= coin.out.nValue; m_bogo_size -= GetBogoSize(coin.out.scriptPubKey); } // The coinbase tx has no undo data since no former output is spent if (!tx->IsCoinBase()) { const auto& tx_undo{block_undo.vtxundo.at(i - 1)}; for (size_t j = 0; j < tx_undo.vprevout.size(); ++j) { Coin coin{tx_undo.vprevout[j]}; COutPoint outpoint{tx->vin[j].prevout.hash, tx->vin[j].prevout.n}; ApplyCoinHash(m_muhash, outpoint, coin); m_total_prevout_spent_amount -= coin.out.nValue; m_transaction_output_count++; m_total_amount += coin.out.nValue; m_bogo_size += GetBogoSize(coin.out.scriptPubKey); } } } const CAmount unclaimed_rewards{(m_total_new_outputs_ex_coinbase_amount + m_total_coinbase_amount + m_total_unspendable_amount) - (m_total_prevout_spent_amount + m_total_subsidy)}; m_total_unspendable_amount -= unclaimed_rewards; m_total_unspendables_unclaimed_rewards -= unclaimed_rewards; // Check that the rolled back internal values are consistent with the DB read out uint256 out; m_muhash.Finalize(out); Assert(read_out.second.muhash == out); Assert(m_transaction_output_count == read_out.second.transaction_output_count); Assert(m_total_amount == read_out.second.total_amount); Assert(m_bogo_size == read_out.second.bogo_size); Assert(m_total_subsidy == read_out.second.total_subsidy); Assert(m_total_unspendable_amount == read_out.second.total_unspendable_amount); Assert(m_total_prevout_spent_amount == read_out.second.total_prevout_spent_amount); Assert(m_total_new_outputs_ex_coinbase_amount == read_out.second.total_new_outputs_ex_coinbase_amount); Assert(m_total_coinbase_amount == read_out.second.total_coinbase_amount); Assert(m_total_unspendables_genesis_block == read_out.second.total_unspendables_genesis_block); Assert(m_total_unspendables_bip30 == read_out.second.total_unspendables_bip30); Assert(m_total_unspendables_scripts == read_out.second.total_unspendables_scripts); Assert(m_total_unspendables_unclaimed_rewards == read_out.second.total_unspendables_unclaimed_rewards); return true; }
0
bitcoin/src
bitcoin/src/index/txindex.cpp
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <index/txindex.h> #include <clientversion.h> #include <common/args.h> #include <index/disktxpos.h> #include <logging.h> #include <node/blockstorage.h> #include <validation.h> constexpr uint8_t DB_TXINDEX{'t'}; std::unique_ptr<TxIndex> g_txindex; /** Access to the txindex database (indexes/txindex/) */ class TxIndex::DB : public BaseIndex::DB { public: explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false); /// Read the disk location of the transaction data with the given hash. Returns false if the /// transaction hash is not indexed. bool ReadTxPos(const uint256& txid, CDiskTxPos& pos) const; /// Write a batch of transaction positions to the DB. [[nodiscard]] bool WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos); }; TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) : BaseIndex::DB(gArgs.GetDataDirNet() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe) {} bool TxIndex::DB::ReadTxPos(const uint256 &txid, CDiskTxPos& pos) const { return Read(std::make_pair(DB_TXINDEX, txid), pos); } bool TxIndex::DB::WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos) { CDBBatch batch(*this); for (const auto& tuple : v_pos) { batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second); } return WriteBatch(batch); } TxIndex::TxIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory, bool f_wipe) : BaseIndex(std::move(chain), "txindex"), m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe)) {} TxIndex::~TxIndex() = default; bool TxIndex::CustomAppend(const interfaces::BlockInfo& block) { // Exclude genesis block transaction because outputs are not spendable. if (block.height == 0) return true; assert(block.data); CDiskTxPos pos({block.file_number, block.data_pos}, GetSizeOfCompactSize(block.data->vtx.size())); std::vector<std::pair<uint256, CDiskTxPos>> vPos; vPos.reserve(block.data->vtx.size()); for (const auto& tx : block.data->vtx) { vPos.emplace_back(tx->GetHash(), pos); pos.nTxOffset += ::GetSerializeSize(TX_WITH_WITNESS(*tx)); } return m_db->WriteTxs(vPos); } BaseIndex::DB& TxIndex::GetDB() const { return *m_db; } bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const { CDiskTxPos postx; if (!m_db->ReadTxPos(tx_hash, postx)) { return false; } AutoFile file{m_chainstate->m_blockman.OpenBlockFile(postx, true)}; if (file.IsNull()) { return error("%s: OpenBlockFile failed", __func__); } CBlockHeader header; try { file >> header; if (fseek(file.Get(), postx.nTxOffset, SEEK_CUR)) { return error("%s: fseek(...) failed", __func__); } file >> TX_WITH_WITNESS(tx); } catch (const std::exception& e) { return error("%s: Deserialize or I/O error - %s", __func__, e.what()); } if (tx->GetHash() != tx_hash) { return error("%s: txid mismatch", __func__); } block_hash = header.GetHash(); return true; }
0
bitcoin/src
bitcoin/src/index/base.h
// Copyright (c) 2017-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_INDEX_BASE_H #define BITCOIN_INDEX_BASE_H #include <dbwrapper.h> #include <interfaces/chain.h> #include <util/threadinterrupt.h> #include <validationinterface.h> #include <string> class CBlock; class CBlockIndex; class Chainstate; class ChainstateManager; namespace interfaces { class Chain; } // namespace interfaces struct IndexSummary { std::string name; bool synced{false}; int best_block_height{0}; uint256 best_block_hash; }; /** * Base class for indices of blockchain data. This implements * CValidationInterface and ensures blocks are indexed sequentially according * to their position in the active chain. * * In the presence of multiple chainstates (i.e. if a UTXO snapshot is loaded), * only the background "IBD" chainstate will be indexed to avoid building the * index out of order. When the background chainstate completes validation, the * index will be reinitialized and indexing will continue. */ class BaseIndex : public CValidationInterface { protected: /** * The database stores a block locator of the chain the database is synced to * so that the index can efficiently determine the point it last stopped at. * A locator is used instead of a simple hash of the chain tip because blocks * and block index entries may not be flushed to disk until after this database * is updated. */ class DB : public CDBWrapper { public: DB(const fs::path& path, size_t n_cache_size, bool f_memory = false, bool f_wipe = false, bool f_obfuscate = false); /// Read block locator of the chain that the index is in sync with. bool ReadBestBlock(CBlockLocator& locator) const; /// Write block locator of the chain that the index is in sync with. void WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator); }; private: /// Whether the index has been initialized or not. std::atomic<bool> m_init{false}; /// Whether the index is in sync with the main chain. The flag is flipped /// from false to true once, after which point this starts processing /// ValidationInterface notifications to stay in sync. /// /// Note that this will latch to true *immediately* upon startup if /// `m_chainstate->m_chain` is empty, which will be the case upon startup /// with an empty datadir if, e.g., `-txindex=1` is specified. std::atomic<bool> m_synced{false}; /// The last block in the chain that the index is in sync with. std::atomic<const CBlockIndex*> m_best_block_index{nullptr}; std::thread m_thread_sync; CThreadInterrupt m_interrupt; /// Sync the index with the block index starting from the current best block. /// Intended to be run in its own thread, m_thread_sync, and can be /// interrupted with m_interrupt. Once the index gets in sync, the m_synced /// flag is set and the BlockConnected ValidationInterface callback takes /// over and the sync thread exits. void ThreadSync(); /// Write the current index state (eg. chain block locator and subclass-specific items) to disk. /// /// Recommendations for error handling: /// If called on a successor of the previous committed best block in the index, the index can /// continue processing without risk of corruption, though the index state will need to catch up /// from further behind on reboot. If the new state is not a successor of the previous state (due /// to a chain reorganization), the index must halt until Commit succeeds or else it could end up /// getting corrupted. bool Commit(); /// Loop over disconnected blocks and call CustomRewind. bool Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip); virtual bool AllowPrune() const = 0; template <typename... Args> void FatalErrorf(const char* fmt, const Args&... args); protected: std::unique_ptr<interfaces::Chain> m_chain; Chainstate* m_chainstate{nullptr}; const std::string m_name; void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override; void ChainStateFlushed(ChainstateRole role, const CBlockLocator& locator) override; /// Initialize internal state from the database and block index. [[nodiscard]] virtual bool CustomInit(const std::optional<interfaces::BlockKey>& block) { return true; } /// Write update index entries for a newly connected block. [[nodiscard]] virtual bool CustomAppend(const interfaces::BlockInfo& block) { return true; } /// Virtual method called internally by Commit that can be overridden to atomically /// commit more index state. virtual bool CustomCommit(CDBBatch& batch) { return true; } /// Rewind index to an earlier chain tip during a chain reorg. The tip must /// be an ancestor of the current best block. [[nodiscard]] virtual bool CustomRewind(const interfaces::BlockKey& current_tip, const interfaces::BlockKey& new_tip) { return true; } virtual DB& GetDB() const = 0; /// Update the internal best block index as well as the prune lock. void SetBestBlockIndex(const CBlockIndex* block); public: BaseIndex(std::unique_ptr<interfaces::Chain> chain, std::string name); /// Destructor interrupts sync thread if running and blocks until it exits. virtual ~BaseIndex(); /// Get the name of the index for display in logs. const std::string& GetName() const LIFETIMEBOUND { return m_name; } /// Blocks the current thread until the index is caught up to the current /// state of the block chain. This only blocks if the index has gotten in /// sync once and only needs to process blocks in the ValidationInterface /// queue. If the index is catching up from far behind, this method does /// not block and immediately returns false. bool BlockUntilSyncedToCurrentChain() const LOCKS_EXCLUDED(::cs_main); void Interrupt(); /// Initializes the sync state and registers the instance to the /// validation interface so that it stays in sync with blockchain updates. [[nodiscard]] bool Init(); /// Starts the initial sync process. [[nodiscard]] bool StartBackgroundSync(); /// Stops the instance from staying in sync with blockchain updates. void Stop(); /// Get a summary of the index and its state. IndexSummary GetSummary() const; }; #endif // BITCOIN_INDEX_BASE_H
0
bitcoin/src
bitcoin/src/ipc/interfaces.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <common/system.h> #include <interfaces/init.h> #include <interfaces/ipc.h> #include <ipc/capnp/protocol.h> #include <ipc/process.h> #include <ipc/protocol.h> #include <logging.h> #include <tinyformat.h> #include <util/fs.h> #include <cstdio> #include <cstdlib> #include <functional> #include <memory> #include <stdexcept> #include <string.h> #include <string> #include <unistd.h> #include <utility> #include <vector> namespace ipc { namespace { class IpcImpl : public interfaces::Ipc { public: IpcImpl(const char* exe_name, const char* process_argv0, interfaces::Init& init) : m_exe_name(exe_name), m_process_argv0(process_argv0), m_init(init), m_protocol(ipc::capnp::MakeCapnpProtocol()), m_process(ipc::MakeProcess()) { } std::unique_ptr<interfaces::Init> spawnProcess(const char* new_exe_name) override { int pid; int fd = m_process->spawn(new_exe_name, m_process_argv0, pid); LogPrint(::BCLog::IPC, "Process %s pid %i launched\n", new_exe_name, pid); auto init = m_protocol->connect(fd, m_exe_name); Ipc::addCleanup(*init, [this, new_exe_name, pid] { int status = m_process->waitSpawned(pid); LogPrint(::BCLog::IPC, "Process %s pid %i exited with status %i\n", new_exe_name, pid, status); }); return init; } bool startSpawnedProcess(int argc, char* argv[], int& exit_status) override { exit_status = EXIT_FAILURE; int32_t fd = -1; if (!m_process->checkSpawned(argc, argv, fd)) { return false; } m_protocol->serve(fd, m_exe_name, m_init); exit_status = EXIT_SUCCESS; return true; } void addCleanup(std::type_index type, void* iface, std::function<void()> cleanup) override { m_protocol->addCleanup(type, iface, std::move(cleanup)); } Context& context() override { return m_protocol->context(); } const char* m_exe_name; const char* m_process_argv0; interfaces::Init& m_init; std::unique_ptr<Protocol> m_protocol; std::unique_ptr<Process> m_process; }; } // namespace } // namespace ipc namespace interfaces { std::unique_ptr<Ipc> MakeIpc(const char* exe_name, const char* process_argv0, Init& init) { return std::make_unique<ipc::IpcImpl>(exe_name, process_argv0, init); } } // namespace interfaces
0
bitcoin/src
bitcoin/src/ipc/protocol.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_PROTOCOL_H #define BITCOIN_IPC_PROTOCOL_H #include <interfaces/init.h> #include <functional> #include <memory> #include <typeindex> namespace ipc { struct Context; //! IPC protocol interface for calling IPC methods over sockets. //! //! There may be different implementations of this interface for different IPC //! protocols (e.g. Cap'n Proto, gRPC, JSON-RPC, or custom protocols). class Protocol { public: virtual ~Protocol() = default; //! Return Init interface that forwards requests over given socket descriptor. //! Socket communication is handled on a background thread. virtual std::unique_ptr<interfaces::Init> connect(int fd, const char* exe_name) = 0; //! Handle requests on provided socket descriptor, forwarding them to the //! provided Init interface. Socket communication is handled on the //! current thread, and this call blocks until the socket is closed. virtual void serve(int fd, const char* exe_name, interfaces::Init& init) = 0; //! Add cleanup callback to interface that will run when the interface is //! deleted. virtual void addCleanup(std::type_index type, void* iface, std::function<void()> cleanup) = 0; //! Context accessor. virtual Context& context() = 0; }; } // namespace ipc #endif // BITCOIN_IPC_PROTOCOL_H
0
bitcoin/src
bitcoin/src/ipc/process.cpp
// Copyright (c) 2021-2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <ipc/process.h> #include <ipc/protocol.h> #include <mp/util.h> #include <tinyformat.h> #include <util/fs.h> #include <util/strencodings.h> #include <cstdint> #include <cstdlib> #include <exception> #include <iostream> #include <stdexcept> #include <string.h> #include <system_error> #include <unistd.h> #include <utility> #include <vector> namespace ipc { namespace { class ProcessImpl : public Process { public: int spawn(const std::string& new_exe_name, const fs::path& argv0_path, int& pid) override { return mp::SpawnProcess(pid, [&](int fd) { fs::path path = argv0_path; path.remove_filename(); path /= fs::PathFromString(new_exe_name); return std::vector<std::string>{fs::PathToString(path), "-ipcfd", strprintf("%i", fd)}; }); } int waitSpawned(int pid) override { return mp::WaitProcess(pid); } bool checkSpawned(int argc, char* argv[], int& fd) override { // If this process was not started with a single -ipcfd argument, it is // not a process spawned by the spawn() call above, so return false and // do not try to serve requests. if (argc != 3 || strcmp(argv[1], "-ipcfd") != 0) { return false; } // If a single -ipcfd argument was provided, return true and get the // file descriptor so Protocol::serve() can be called to handle // requests from the parent process. The -ipcfd argument is not valid // in combination with other arguments because the parent process // should be able to control the child process through the IPC protocol // without passing information out of band. if (!ParseInt32(argv[2], &fd)) { throw std::runtime_error(strprintf("Invalid -ipcfd number '%s'", argv[2])); } return true; } }; } // namespace std::unique_ptr<Process> MakeProcess() { return std::make_unique<ProcessImpl>(); } } // namespace ipc
0
bitcoin/src
bitcoin/src/ipc/context.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_CONTEXT_H #define BITCOIN_IPC_CONTEXT_H namespace ipc { //! Context struct used to give IPC protocol implementations or implementation //! hooks access to application state, in case they need to run extra code that //! isn't needed within a single process, like code copying global state from an //! existing process to a new process when it's initialized, or code dealing //! with shared objects that are created or destroyed remotely. struct Context { }; } // namespace ipc #endif // BITCOIN_IPC_CONTEXT_H
0
bitcoin/src
bitcoin/src/ipc/process.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_PROCESS_H #define BITCOIN_IPC_PROCESS_H #include <util/fs.h> #include <memory> #include <string> namespace ipc { class Protocol; //! IPC process interface for spawning bitcoin processes and serving requests //! in processes that have been spawned. //! //! There will be different implementations of this interface depending on the //! platform (e.g. unix, windows). class Process { public: virtual ~Process() = default; //! Spawn process and return socket file descriptor for communicating with //! it. virtual int spawn(const std::string& new_exe_name, const fs::path& argv0_path, int& pid) = 0; //! Wait for spawned process to exit and return its exit code. virtual int waitSpawned(int pid) = 0; //! Parse command line and determine if current process is a spawned child //! process. If so, return true and a file descriptor for communicating //! with the parent process. virtual bool checkSpawned(int argc, char* argv[], int& fd) = 0; }; //! Constructor for Process interface. Implementation will vary depending on //! the platform (unix or windows). std::unique_ptr<Process> MakeProcess(); } // namespace ipc #endif // BITCOIN_IPC_PROCESS_H
0
bitcoin/src
bitcoin/src/ipc/exception.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_EXCEPTION_H #define BITCOIN_IPC_EXCEPTION_H #include <stdexcept> namespace ipc { //! Exception class thrown when a call to remote method fails due to an IPC //! error, like a socket getting disconnected. class Exception : public std::runtime_error { public: using std::runtime_error::runtime_error; }; } // namespace ipc #endif // BITCOIN_IPC_EXCEPTION_H
0
bitcoin/src/ipc
bitcoin/src/ipc/capnp/protocol.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_CAPNP_PROTOCOL_H #define BITCOIN_IPC_CAPNP_PROTOCOL_H #include <memory> namespace ipc { class Protocol; namespace capnp { std::unique_ptr<Protocol> MakeCapnpProtocol(); } // namespace capnp } // namespace ipc #endif // BITCOIN_IPC_CAPNP_PROTOCOL_H
0
bitcoin/src/ipc
bitcoin/src/ipc/capnp/init.capnp
# Copyright (c) 2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @0xf2c5cfa319406aa6; using Cxx = import "/capnp/c++.capnp"; $Cxx.namespace("ipc::capnp::messages"); using Proxy = import "/mp/proxy.capnp"; $Proxy.include("interfaces/echo.h"); $Proxy.include("interfaces/init.h"); $Proxy.includeTypes("ipc/capnp/init-types.h"); using Echo = import "echo.capnp"; interface Init $Proxy.wrap("interfaces::Init") { construct @0 (threadMap: Proxy.ThreadMap) -> (threadMap :Proxy.ThreadMap); makeEcho @1 (context :Proxy.Context) -> (result :Echo.Echo); }
0
bitcoin/src/ipc
bitcoin/src/ipc/capnp/echo.capnp
# Copyright (c) 2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @0x888b4f7f51e691f7; using Cxx = import "/capnp/c++.capnp"; $Cxx.namespace("ipc::capnp::messages"); using Proxy = import "/mp/proxy.capnp"; $Proxy.include("interfaces/echo.h"); $Proxy.include("ipc/capnp/echo.capnp.h"); interface Echo $Proxy.wrap("interfaces::Echo") { destroy @0 (context :Proxy.Context) -> (); echo @1 (context :Proxy.Context, echo: Text) -> (result :Text); }
0
bitcoin/src/ipc
bitcoin/src/ipc/capnp/context.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_CAPNP_CONTEXT_H #define BITCOIN_IPC_CAPNP_CONTEXT_H #include <ipc/context.h> namespace ipc { namespace capnp { //! Cap'n Proto context struct. Generally the parent ipc::Context struct should //! be used instead of this struct to give all IPC protocols access to //! application state, so there aren't unnecessary differences between IPC //! protocols. But this specialized struct can be used to pass capnp-specific //! function and object types to capnp hooks. struct Context : ipc::Context { }; } // namespace capnp } // namespace ipc #endif // BITCOIN_IPC_CAPNP_CONTEXT_H
0
bitcoin/src/ipc
bitcoin/src/ipc/capnp/init-types.h
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_IPC_CAPNP_INIT_TYPES_H #define BITCOIN_IPC_CAPNP_INIT_TYPES_H #include <ipc/capnp/echo.capnp.proxy-types.h> #endif // BITCOIN_IPC_CAPNP_INIT_TYPES_H
0
bitcoin/src/ipc
bitcoin/src/ipc/capnp/protocol.cpp
// Copyright (c) 2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <interfaces/init.h> #include <ipc/capnp/context.h> #include <ipc/capnp/init.capnp.h> #include <ipc/capnp/init.capnp.proxy.h> #include <ipc/capnp/protocol.h> #include <ipc/exception.h> #include <ipc/protocol.h> #include <kj/async.h> #include <logging.h> #include <mp/proxy-io.h> #include <mp/proxy-types.h> #include <mp/util.h> #include <util/threadnames.h> #include <assert.h> #include <errno.h> #include <future> #include <memory> #include <mutex> #include <optional> #include <string> #include <thread> namespace ipc { namespace capnp { namespace { void IpcLogFn(bool raise, std::string message) { LogPrint(BCLog::IPC, "%s\n", message); if (raise) throw Exception(message); } class CapnpProtocol : public Protocol { public: ~CapnpProtocol() noexcept(true) { if (m_loop) { std::unique_lock<std::mutex> lock(m_loop->m_mutex); m_loop->removeClient(lock); } if (m_loop_thread.joinable()) m_loop_thread.join(); assert(!m_loop); }; std::unique_ptr<interfaces::Init> connect(int fd, const char* exe_name) override { startLoop(exe_name); return mp::ConnectStream<messages::Init>(*m_loop, fd); } void serve(int fd, const char* exe_name, interfaces::Init& init) override { assert(!m_loop); mp::g_thread_context.thread_name = mp::ThreadName(exe_name); m_loop.emplace(exe_name, &IpcLogFn, &m_context); mp::ServeStream<messages::Init>(*m_loop, fd, init); m_loop->loop(); m_loop.reset(); } void addCleanup(std::type_index type, void* iface, std::function<void()> cleanup) override { mp::ProxyTypeRegister::types().at(type)(iface).cleanup.emplace_back(std::move(cleanup)); } Context& context() override { return m_context; } void startLoop(const char* exe_name) { if (m_loop) return; std::promise<void> promise; m_loop_thread = std::thread([&] { util::ThreadRename("capnp-loop"); m_loop.emplace(exe_name, &IpcLogFn, &m_context); { std::unique_lock<std::mutex> lock(m_loop->m_mutex); m_loop->addClient(lock); } promise.set_value(); m_loop->loop(); m_loop.reset(); }); promise.get_future().wait(); } Context m_context; std::thread m_loop_thread; std::optional<mp::EventLoop> m_loop; }; } // namespace std::unique_ptr<Protocol> MakeCapnpProtocol() { return std::make_unique<CapnpProtocol>(); } } // namespace capnp } // namespace ipc
0
bitcoin/src
bitcoin/src/minisketch/configure.ac
AC_INIT([minisketch], [0.0.1], [http://github.com/sipa/minisketch/]) m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])]) AC_PREREQ(2.60) AC_CONFIG_SRCDIR([src/minisketch.cpp]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_MACRO_DIR([build-aux/m4]) AM_INIT_AUTOMAKE([subdir-objects foreign]) LT_INIT LT_LANG([C++]) AC_LANG([C++]) AC_PATH_PROG(CCACHE,ccache) AC_ARG_ENABLE([ccache], [AS_HELP_STRING([--disable-ccache], [do not use ccache for building (default is to use if found)])], [use_ccache=$enableval], [use_ccache=auto]) AC_ARG_ENABLE(tests, AS_HELP_STRING([--enable-tests],[compile tests (default is yes)]), [use_tests=$enableval], [use_tests=yes]) AC_ARG_ENABLE(benchmark, AS_HELP_STRING([--enable-benchmark],[compile benchmark (default is no)]), [use_benchmark=$enableval], [use_benchmark=no]) m4_define([SUPPORTED_FIELDS], [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64]) AC_MSG_CHECKING([which field sizes to build]) AC_ARG_ENABLE([fields], AS_HELP_STRING([--enable-fields=LIST], [Comma-separated list of field sizes to build. Default=all. Available sizes:] m4_translit(m4_defn([SUPPORTED_FIELDS]), [,], [ ])), [], [enable_fields=SUPPORTED_FIELDS]) have_disabled_fields=no have_enabled_fields=no m4_foreach([FIELD], [SUPPORTED_FIELDS], [ case ",$enable_fields," in *,FIELD,*) have_enabled_fields=yes ;; *) AC_DEFINE(DISABLE_FIELD_[]FIELD, [1], [Define to 1 to remove support for field size] FIELD [.]) have_disabled_fields=yes ;; esac ]) AC_MSG_RESULT([$enable_fields]) if test "x$have_enabled_fields" = xno; then AC_MSG_ERROR([No field sizes are enabled.]) fi AX_CHECK_COMPILE_FLAG([-Werror],[CXXFLAG_WERROR="-Werror"],[CXXFLAG_WERROR=""]) AX_CXX_COMPILE_STDCXX([11], [noext], [mandatory]) enable_clmul= AX_CHECK_COMPILE_FLAG([-mpclmul],[[enable_clmul=yes]],,[[$CXXFLAG_WERROR]],[AC_LANG_PROGRAM([ #include <stdint.h> #include <x86intrin.h> ], [ __m128i a = _mm_cvtsi64_si128((uint64_t)7); __m128i b = _mm_clmulepi64_si128(a, a, 37); __m128i c = _mm_srli_epi64(b, 41); __m128i d = _mm_xor_si128(b, c); uint64_t e = _mm_cvtsi128_si64(d); return e == 0; ])]) if test x$enable_clmul = xyes; then CLMUL_CXXFLAGS="-mpclmul" AC_DEFINE(HAVE_CLMUL, 1, [Define this symbol if clmul instructions can be used]) fi AC_MSG_CHECKING(for working clz builtins) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [ unsigned a = __builtin_clz(1); unsigned long b = __builtin_clzl(1); unsigned long long c = __builtin_clzll(1); ])], [ AC_DEFINE(HAVE_CLZ, 1, [Define this symbol if clz builtins are present and working]) AC_MSG_RESULT(yes) ],[ AC_MSG_RESULT(no) ] ) AX_CHECK_LINK_FLAG([[-Wl,--exclude-libs,ALL]],[LDFLAGS="-Wl,--exclude-libs,ALL $LDFLAGS"]) case $host in *mingw*) dnl -static is interpreted by libtool, where it has a different meaning. dnl In libtool-speak, it's -all-static. AX_CHECK_LINK_FLAG([[-static]],[LIBTOOL_APP_LDFLAGS="$LIBTOOL_APP_LDFLAGS -all-static"]) ;; *) AX_CHECK_LINK_FLAG([[-static]],[LIBTOOL_APP_LDFLAGS="-static"]) ;; esac AX_CHECK_COMPILE_FLAG([-Wall],[WARN_CXXFLAGS="$WARN_CXXFLAGS -Wall"],,[[$CXXFLAG_WERROR]]) AX_CHECK_COMPILE_FLAG([-fvisibility=hidden],[CXXFLAGS="$CXXFLAGS -fvisibility=hidden"],[],[$CXXFLAG_WERROR]) ## Some compilers (gcc) ignore unknown -Wno-* options, but warn about all ## unknown options if any other warning is produced. Test the -Wfoo case, and ## set the -Wno-foo case if it works. AX_CHECK_COMPILE_FLAG([-Wshift-count-overflow],[NOWARN_CXXFLAGS="$NOWARN_CXXFLAGS -Wno-shift-count-overflow"],,[[$CXXFLAG_WERROR]]) if test "x$use_ccache" != "xno"; then AC_MSG_CHECKING(if ccache should be used) if test x$CCACHE = x; then if test "x$use_ccache" = "xyes"; then AC_MSG_ERROR([ccache not found.]); else use_ccache=no fi else use_ccache=yes CC="$ac_cv_path_CCACHE $CC" CXX="$ac_cv_path_CCACHE $CXX" fi AC_MSG_RESULT($use_ccache) fi VERIFY_DEFINES=-DMINISKETCH_VERIFY RELEASE_DEFINES= AC_CONFIG_FILES([ Makefile ]) AC_SUBST(CLMUL_CXXFLAGS) AC_SUBST(WARN_CXXFLAGS) AC_SUBST(NOWARN_CXXFLAGS) AC_SUBST(VERIFY_DEFINES) AC_SUBST(RELEASE_DEFINES) AC_SUBST(LIBTOOL_APP_LDFLAGS) AM_CONDITIONAL([ENABLE_CLMUL],[test x$enable_clmul = xyes]) AM_CONDITIONAL([USE_BENCHMARK], [test x"$use_benchmark" = x"yes"]) AM_CONDITIONAL([USE_TESTS], [test x"$use_tests" != x"no"]) AC_OUTPUT echo echo "Build Options:" echo " with benchmarks = $use_benchmark" echo " with tests = $use_tests" echo " enable clmul fields = $enable_clmul" echo " CXX = $CXX" echo " CXXFLAGS = $CXXFLAGS" echo " CPPFLAGS = $CPPFLAGS" echo " LDFLAGS = $LDFLAGS" if test "$have_disabled_fields" = "yes"; then echo echo "Only compiling in support for field sizes: $enable_fields" echo "WARNING: this means the library will lack support for other field sizes entirely" fi
0
bitcoin/src
bitcoin/src/minisketch/sources.mk
# - All variables are namespaced with MINISKETCH_ to avoid colliding with # downstream makefiles. # - All Variables ending in _HEADERS or _SOURCES confuse automake, so the # _INT postfix is applied. # - Convenience variables, for example a MINISKETCH_FIELDS_DIR should not be used # as they interfere with automatic dependency generation # - The %reldir% is the relative path from the Makefile.am. This allows # downstreams to use these variables without having to manually account for # the path change. MINISKETCH_INCLUDE_DIR_INT = %reldir%/include MINISKETCH_DIST_HEADERS_INT = MINISKETCH_DIST_HEADERS_INT += %reldir%/include/minisketch.h MINISKETCH_LIB_HEADERS_INT = MINISKETCH_LIB_HEADERS_INT += %reldir%/src/false_positives.h MINISKETCH_LIB_HEADERS_INT += %reldir%/src/fielddefines.h MINISKETCH_LIB_HEADERS_INT += %reldir%/src/int_utils.h MINISKETCH_LIB_HEADERS_INT += %reldir%/src/lintrans.h MINISKETCH_LIB_HEADERS_INT += %reldir%/src/sketch.h MINISKETCH_LIB_HEADERS_INT += %reldir%/src/sketch_impl.h MINISKETCH_LIB_HEADERS_INT += %reldir%/src/util.h MINISKETCH_LIB_SOURCES_INT = MINISKETCH_LIB_SOURCES_INT += %reldir%/src/minisketch.cpp MINISKETCH_FIELD_GENERIC_HEADERS_INT = MINISKETCH_FIELD_GENERIC_HEADERS_INT += %reldir%/src/fields/generic_common_impl.h MINISKETCH_FIELD_GENERIC_SOURCES_INT = MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_1byte.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_2bytes.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_3bytes.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_4bytes.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_5bytes.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_6bytes.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_7bytes.cpp MINISKETCH_FIELD_GENERIC_SOURCES_INT += %reldir%/src/fields/generic_8bytes.cpp MINISKETCH_FIELD_CLMUL_HEADERS_INT = MINISKETCH_FIELD_CLMUL_HEADERS_INT += %reldir%/src/fields/clmul_common_impl.h MINISKETCH_FIELD_CLMUL_SOURCES_INT = MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_1byte.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_2bytes.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_3bytes.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_4bytes.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_5bytes.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_6bytes.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_7bytes.cpp MINISKETCH_FIELD_CLMUL_SOURCES_INT += %reldir%/src/fields/clmul_8bytes.cpp MINISKETCH_BENCH_SOURCES_INT = MINISKETCH_BENCH_SOURCES_INT += %reldir%/src/bench.cpp MINISKETCH_TEST_SOURCES_INT = MINISKETCH_TEST_SOURCES_INT += %reldir%/src/test.cpp
0
bitcoin/src
bitcoin/src/minisketch/LICENSE
MIT License Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
bitcoin/src
bitcoin/src/minisketch/Makefile.am
ACLOCAL_AMFLAGS = -I build-aux/m4 AM_CXXFLAGS = $(WARN_CXXFLAGS) $(NOWARN_CXXFLAGS) include sources.mk include_HEADERS = $(MINISKETCH_DIST_HEADERS_INT) noinst_HEADERS = $(MINISKETCH_LIB_HEADERS_INT) $(MINISKETCH_FIELD_GENERIC_HEADERS_INT) $(MINISKETCH_FIELD_CLMUL_HEADERS_INT) LIBMINISKETCH = libminisketch.la LIBMINISKETCH_FIELD_GENERIC = libminisketch_field_generic.la if ENABLE_CLMUL LIBMINISKETCH_FIELD_CLMUL = libminisketch_field_clmul.la endif if USE_TESTS LIBMINISKETCH_VERIFY=libminisketch_verify.la LIBMINISKETCH_FIELD_GENERIC_VERIFY=libminisketch_field_generic_verify.la if ENABLE_CLMUL LIBMINISKETCH_FIELD_CLMUL_VERIFY=libminisketch_field_clmul_verify.la endif endif lib_LTLIBRARIES = lib_LTLIBRARIES += $(LIBMINISKETCH) noinst_LTLIBRARIES = noinst_LTLIBRARIES += $(LIBMINISKETCH_FIELD_GENERIC) noinst_LTLIBRARIES += $(LIBMINISKETCH_FIELD_GENERIC_VERIFY) noinst_LTLIBRARIES += $(LIBMINISKETCH_FIELD_CLMUL) noinst_LTLIBRARIES += $(LIBMINISKETCH_FIELD_CLMUL_VERIFY) noinst_LTLIBRARIES += $(LIBMINISKETCH_VERIFY) # Release libs libminisketch_field_generic_la_SOURCES = $(MINISKETCH_FIELD_GENERIC_SOURCES_INT) libminisketch_field_generic_la_CPPFLAGS = $(AM_CPPFLAGS) $(RELEASE_DEFINES) libminisketch_field_clmul_la_SOURCES = $(MINISKETCH_FIELD_CLMUL_SOURCES_INT) libminisketch_field_clmul_la_CPPFLAGS = $(AM_CPPFLAGS) $(RELEASE_DEFINES) libminisketch_field_clmul_la_CXXFLAGS = $(AM_CXXFLAGS) $(CLMUL_CXXFLAGS) libminisketch_la_SOURCES = $(MINISKETCH_LIB_SOURCES_INT) libminisketch_la_CPPFLAGS = $(AM_CPPFLAGS) $(RELEASE_DEFINES) libminisketch_la_LIBADD = $(LIBMINISKETCH_FIELD_CLMUL) $(LIBMINISKETCH_FIELD_GENERIC) # Libs with extra verification checks libminisketch_field_generic_verify_la_SOURCES = $(MINISKETCH_FIELD_GENERIC_SOURCES_INT) libminisketch_field_generic_verify_la_CPPFLAGS = $(AM_CPPFLAGS) $(VERIFY_DEFINES) libminisketch_field_clmul_verify_la_SOURCES = $(MINISKETCH_FIELD_CLMUL_SOURCES_INT) libminisketch_field_clmul_verify_la_CPPFLAGS = $(AM_CPPFLAGS) $(VERIFY_DEFINES) libminisketch_field_clmul_verify_la_CXXFLAGS = $(AM_CXXFLAGS) $(CLMUL_CXXFLAGS) libminisketch_verify_la_SOURCES = $(MINISKETCH_LIB_SOURCES_INT) libminisketch_verify_la_CPPFLAGS = $(AM_CPPFLAGS) $(VERIFY_DEFINES) libminisketch_verify_la_LIBADD = $(LIBMINISKETCH_FIELD_CLMUL_VERIFY) $(LIBMINISKETCH_FIELD_GENERIC_VERIFY) noinst_PROGRAMS = if USE_BENCHMARK noinst_PROGRAMS += bench endif if USE_TESTS noinst_PROGRAMS += test test-verify TESTS = test test-verify endif bench_SOURCES = $(MINISKETCH_BENCH_SOURCES_INT) bench_CPPFLAGS = $(AM_CPPFLAGS) $(RELEASE_DEFINES) bench_LDADD = $(LIBMINISKETCH) bench_LDFLAGS = $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) test_SOURCES = $(MINISKETCH_TEST_SOURCES_INT) test_CPPFLAGS = $(AM_CPPFLAGS) $(RELEASE_DEFINES) test_LDADD = $(LIBMINISKETCH) test_LDFLAGS = $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) test_verify_SOURCES = $(MINISKETCH_TEST_SOURCES_INT) test_verify_CPPFLAGS = $(AM_CPPFLAGS) $(VERIFY_DEFINES) test_verify_LDADD = $(LIBMINISKETCH_VERIFY) test_verify_LDFLAGS = $(AM_LDFLAGS) $(LIBTOOL_APP_LDFLAGS) EXTRA_DIST= EXTRA_DIST += LICENSE EXTRA_DIST += README.md EXTRA_DIST += doc/example.c EXTRA_DIST += doc/gen_params.sage EXTRA_DIST += doc/math.md EXTRA_DIST += doc/moduli.md EXTRA_DIST += doc/plot_bits.png EXTRA_DIST += doc/plot_capacity.png EXTRA_DIST += doc/plot_diff.png EXTRA_DIST += doc/plot_size.png EXTRA_DIST += doc/protocoltips.md EXTRA_DIST += tests/pyminisketch.py
0
bitcoin/src
bitcoin/src/minisketch/README.md
# Minisketch: a library for [BCH](https://en.wikipedia.org/wiki/BCH_code)-based set reconciliation <img align="right" src="doc/minisketch-vs.png" /> `libminisketch` is an optimized standalone MIT-licensed library with C API for constructing and decoding *set sketches*, which can be used for compact set reconciliation and other applications. It is an implementation of the PinSketch<sup>[[1]](#myfootnote1)</sup> algorithm. An explanation of the algorithm can be found [here](doc/math.md). ## Sketches for set reconciliation Sketches, as produced by this library, can be seen as "set checksums" with two peculiar properties: * Sketches have a predetermined capacity, and when the number of elements in the set is not higher than the capacity, `libminisketch` will always recover the entire set from the sketch. A sketch of *b*-bit elements with capacity *c* can be stored in *bc* bits. * The sketches of two sets can be combined by adding them (XOR) to obtain a sketch of the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) between the two sets (*i.e.*, all elements that occur in one but not both input sets). This makes them appropriate for a very bandwidth-efficient set reconciliation protocol. If Alice and Bob each have a set of elements, and they suspect that the sets largely but not entirely overlap, they can use the following protocol to let both parties learn all the elements: * Alice and Bob both compute a sketch of their set elements. * Alice sends her sketch to Bob. * Bob combines the two sketches, and obtains a sketch of the symmetric difference. * Bob tries to recover the elements from the difference sketch. * Bob sends every element in the difference that he has to Alice. This will always succeed when the size of the difference (elements that Alice has but Bob doesn't plus elements that Bob has but Alice doesn't) does not exceed the capacity of the sketch that Alice sent. The interesting part is that this works regardless of the actual set sizes—only the difference matters. If the elements are large, it may be preferable to compute the sketches over *hashes* of the set elements. In that case an additional step is added to the protocol, where Bob also sends the hash of every element he does not have to Alice, who responds with the requested elements. The doc/ directory has additional [tips for designing reconciliation protocols using libminisketch](doc/protocoltips.md). ## Evaluation <img src="doc/plot_capacity.png" width="432" height="324" /> <img src="doc/plot_diff.png" width="432" height="324" /> <img src="doc/plot_size.png" width="432" height="324" /> <img src="doc/plot_bits.png" width="432" height="324" /> **The first graph** above shows a benchmark of `libminisketch` against three other set reconciliation algorithms/implementations. The benchmarks were performed using a single core on a system with an Intel Core i7-7820HQ CPU with clock speed locked at 2.4 GHz. The diagram shows the time needed for merging of two sketches and decoding the result. The creation of a sketch on the same machine takes around 5 ns per capacity and per set element. The other implementations are: * [`pinsketch`](https://www.cs.bu.edu/~reyzin/code/fuzzy.html), the original PinSketch implementation. * [`cpisync`](https://github.com/trachten/cpisync), a software project which implements a number of set reconciliation algorithms and protocols. The included benchmark analyzes the non-probabilistic version of the original CPISync algorithm<sup>[[5]](#myfootnote5)</sup> only. * A high-performance custom IBLT implementation using 4 hash functions and 32-bit checksums. For the largest sizes currently of interest to the authors, such as a set of capacity 4096 with 1024 differences, `libminisketch` is forty-nine times faster than `pinsketch` and over eight thousand times faster than `cpisync`. `libminisketch` is fast enough on realistic set sizes for use on high-traffic network servers where computational resources are limited. Even where performance is latency-limited, small minisketches can be fast enough to improve performance. On the above i7-7820HQ, a set of 2500 30-bit entries with a difference of 20 elements can be communicated in less time with a minisketch than sending the raw set so long as the communications bandwidth is 1 gigabit per second or less; an eight-element difference can be communicated in better than one-fifth the time on a gigabit link. **The second graph** above shows the performance of the same algorithms on the same system, but this time keeping the capacity constant at 128, while varying the number of differences to reconcile between 1 and 128. It shows how `cpisync`'s reconciliation speed is mostly dependent on capacity, while `pinsketch`/`libminisketch` are more dependent on number of differences. **The third graph** above shows the size overhead of a typical IBLT scheme over the other algorithms (which are near-optimal bandwidth), for various levels of failure probability. IBLT takes tens of times the bandwidth of `libminisketch` sketches when the set difference size is small and the required failure rate is low. **The fourth graph** above shows the effect of the field size on speed in `libminisketch`. The three lines correspond to: * CLMUL 64-bit: Intel Core i7-7820HQ system at 2.4 GHz * Generic 64-bit: POWER9 CP9M06 system at 2.8 GHz (Talos II) * Generic 32-bit: Cortex-A53 at 1.2 GHz (Raspberry Pi 3B) It shows how CLMUL implementations are faster for certain fields (specifically, field sizes for which an irreducible polynomial of the form *x<sup>b</sup> + x + 1* over *GF(2)* exists, and to a lesser extent, fields which are a multiple of 8 bits). It also shows how (for now) a significant performance drop exists for fields larger than 32 bits on 32-bit platforms. Note that the three lines are not at the same scale (the Raspberry Pi 3B is around 10x slower for 32-bit fields than the Core i7; the POWER9 is around 1.3x slower). Below we compare the PinSketch algorithm (which `libminisketch` is an implementation of) with other set reconciliation algorithms: | Algorithm | Sketch size | Decode success | Decoding complexity | Difference type | Secure sketch | | ----------------------------------------------------- | ------------------------- | ---------------| ------------------- | --------------- | ------------- | | CPISync<sup>[[2]](#myfootnote2)</sup> | *(b+1)c* | Always | *O(n<sup>3</sup>)* | Both | Yes | | PinSketch<sup>[[1]](#myfootnote1)</sup> | *bc* | Always | *O(n<sup>2</sup>)* | Symmetric only | Yes | | IBLT<sup>[[6]](#myfootnote1)[[7]](#myfootnote1)</sup> | *&alpha;bc* (see graph 3) | Probabilistic | *O(n)* | Depends | No | * **Sketch size:** This column shows the size in bits of a sketch designed for reconciling *c* different *b*-bit elements. PinSketch and CPISync have a near-optimal<sup>[[11]](#myfootnote11)</sup> communication overhead, which in practice means the sketch size is very close (or equal to) *bc* bits. That is the same size as would be needed to transfer the elements of the difference naively (which is remarkable, as the difference isn't even known by the sender). For IBLT there is an overhead factor *&alpha;*, which depends on various design parameters, but is often between *2* and *10*. * **Decode success:** Whenever a sketch is designed with a capacity not lower than the actual difference size, CPISync and PinSketch guarantee that decoding of the difference will always succeed. IBLT always has a chance of failure, though that chance can be made arbitrarily small by increasing the communication overhead. * **Decoding complexity:** The space savings achieved by near-optimal algorithms come at a cost in performance, as their asymptotic decode complexity is quadratic or cubic, while IBLT is linear. This means that using near-optimal algorithms can be too expensive for applications where the difference is sufficiently large. * **Difference type:** PinSketch can only compute the symmetric difference from a merged sketch, while CPISync and IBLT can distinguish which side certain elements were missing on. When the decoder has access to one of the sets, this generally doesn't matter, as he can look up each of the elements in the symmetric difference with one of the sets. * **Secure sketch:** Whether the sketch satisfies the definition of a secure sketch<sup>[[1]](#myfootnote1)</sup>, which implies a minimal amount about a set can be extracted from a sketch by anyone who does not know most of the elements already. This makes the algorithm appropriate for applications like fingerprint authentication. ## Building The build system is very rudimentary for now, and [improvements](https://github.com/sipa/minisketch/pulls) are welcome. The following may work and produce a `libminisketch.a` file you can link against: ```bash git clone https://github.com/sipa/minisketch cd minisketch ./autogen.sh && ./configure && make ``` ## Usage In this section Alice and Bob are trying to find the difference between their sets. Alice has the set *[3000 ... 3009]*, while Bob has *[3002 ... 3011]*. First, Alice creates a sketch: ```c #include <stdio.h> #include <assert.h> #include "../include/minisketch.h" int main(void) { minisketch *sketch_a = minisketch_create(12, 0, 4); ``` The arguments are: * The field size *b*, which specifies the size of the elements being reconciled. With a field size *b*, the supported range of set elements is the integers from *1* to *2<sup>b</sub>* *- 1*, inclusive. Note that elements cannot be zero. * The implementation number. Implementation *0* is always supported, but more efficient algorithms may be available on some hardware. The serialized form of a sketch is independent of the implementation, so different implementations can interoperate. * The capacity *c*, which specifies how many differences the resulting sketch can reconcile. Then Alice adds her elements to her sketch. Note that adding the same element a second time removes it again, as sketches have set semantics, not multiset semantics. ```c for (int i = 3000; i < 3010; ++i) { minisketch_add_uint64(sketch_a, i); } ``` The next step is serializing the sketch into a byte array: ```c size_t sersize = minisketch_serialized_size(sketch_a); assert(sersize == 12 * 4 / 8); // 4 12-bit values is 6 bytes. unsigned char *buffer_a = malloc(sersize); minisketch_serialize(sketch_a, buffer_a); minisketch_destroy(sketch_a); ``` The contents of the buffer can then be submitted to Bob, who can create his own sketch: ```c minisketch *sketch_b = minisketch_create(12, 0, 4); // Bob's own sketch for (int i = 3002; i < 3012; ++i) { minisketch_add_uint64(sketch_b, i); } ``` After Bob receives Alice's serialized sketch, he can reconcile: ```c sketch_a = minisketch_create(12, 0, 4); // Alice's sketch minisketch_deserialize(sketch_a, buffer_a); // Load Alice's sketch free(buffer_a); // Merge the elements from sketch_a into sketch_b. The result is a sketch_b // which contains all elements that occurred in Alice's or Bob's sets, but not // in both. minisketch_merge(sketch_b, sketch_a); uint64_t differences[4]; ssize_t num_differences = minisketch_decode(sketch_b, 4, differences); minisketch_destroy(sketch_a); minisketch_destroy(sketch_b); if (num_differences < 0) { printf("More than 4 differences!\n"); } else { ssize_t i; for (i = 0; i < num_differences; ++i) { printf("%u is in only one of the two sets\n", (unsigned)differences[i]); } } } ``` In this example Bob would see output such as: ``` $ gcc -std=c99 -Wall -Wextra -o example ./doc/example.c -Lsrc/ -lminisketch -lstdc++ && ./example 3000 is in only one of the two sets 3011 is in only one of the two sets 3001 is in only one of the two sets 3010 is in only one of the two sets ``` The order of the output is arbitrary and will differ on different runs of minisketch_decode(). ## Applications Communications efficient set reconciliation has been proposed to optimize Bitcoin transaction distribution<sup>[[8]](#myfootnote8)</sup>, which would allow Bitcoin nodes to have many more peers while reducing bandwidth usage. It could also be used for Bitcoin block distribution<sup>[[9]](#myfootnote9)</sup>, particularly for very low bandwidth links such as satellite. A similar approach (CPISync) is used by PGP SKS keyservers to synchronize their databases efficiently. Secure sketches can also be used as helper data to reliably extract a consistent cryptographic key from fuzzy biometric data while leaking minimal information<sup>[[1]](#myfootnote1)</sup>. They can be combined with [dcnets](https://en.wikipedia.org/wiki/Dining_cryptographers_problem) to create cryptographic multiparty anonymous communication<sup>[[10]](#myfootnote10)</sup>. ## Implementation notes `libminisketch` is written in C++11, but has a [C API](include/minisketch.h) for compatibility reasons. Specific algorithms and optimizations used: * Finite field implementations: * A generic implementation using C unsigned integer bit operations, and one using the [CLMUL instruction](https://en.wikipedia.org/wiki/CLMUL_instruction_set) where available. The latter has specializations for different classes of fields that permit optimizations (those with trinomial irreducible polynomials, and those whose size is a multiple of 8 bits). * Precomputed tables for (repeated) squaring, and for solving equations of the form *x<sup>2</sup> + x = a*<sup>[[2]](#myfootnote2)</sup>. * Inverses are computed using an [exponentiation ladder](https://en.wikipedia.org/w/index.php?title=Exponentiation_by_squaring&oldid=868883860)<sup>[[12]](#myfootnote12)</sup> on systems where multiplications are relatively fast, and using an [extended GCD algorithm](https://en.wikipedia.org/w/index.php?title=Extended_Euclidean_algorithm&oldid=865802511#Computing_multiplicative_inverses_in_modular_structures) otherwise. * Repeated multiplications are accelerated using runtime precomputations on systems where multiplications are relatively slow. * The serialization of field elements always represents them as bits that are coefficients of the lowest-weight (using lexicographic order as tie breaker) irreducible polynomials over *GF(2)* (see [this list](doc/moduli.md)), but for some implementations they are converted to a different representation internally. * The sketch algorithms are specialized for each separate field implementation, permitting inlining and specific optimizations while avoiding dynamic allocations and branching costs. * Decoding of sketches uses the [Berlekamp-Massey algorithm](https://en.wikipedia.org/w/index.php?title=Berlekamp%E2%80%93Massey_algorithm&oldid=870768940)<sup>[[3]](#myfootnote3)</sup> to compute the characteristic polynomial. * Finding the roots of polynomials is done using the Berlekamp trace algorithm with explicit formula for quadratic polynomials<sup>[[4]](#myfootnote4)</sup>. The root finding is randomized to prevent adversarial inputs that intentionally trigger worst-case decode time. * A (possibly) novel optimization combines a test for unique roots with the Berlekamp trace algorithm. Some improvements that are still TODO: * Explicit formulas for the roots of polynomials of higher degree than 2 * Subquadratic multiplication and modulus algorithms * The [Half-GCD algorithm](http://mathworld.wolfram.com/Half-GCD.html) for faster GCDs * An interface for incremental decoding: most of the computation in most failed decodes can be reused when attempting to decode a longer sketch of the same set * Platform specific optimizations for platforms other than x86 * Avoid using slow uint64_t for calculations on 32-bit hosts * Optional IBLT / Hybrid and set entropy coder under the same interface ## References * <a name="myfootnote1">[1]</a> Dodis, Ostrovsky, Reyzin and Smith. *Fuzzy Extractors: How to Generate Strong Keys from Biometrics and Other Noisy Data.* SIAM Journal on Computing, volume 38, number 1, pages 97-139, 2008). [[URL]](http://eprint.iacr.org/2003/235) [[PDF]](https://eprint.iacr.org/2003/235.pdf) * <a name="myfootnote5">[5]</a> A. Trachtenberg, D. Starobinski and S. Agarwal. *Fast PDA synchronization using characteristic polynomial interpolation.* Proceedings, Twenty-First Annual Joint Conference of the IEEE Computer and Communications Societies, New York, NY, USA, 2002, pp. 1510-1519 vol.3. [[PDF]](https://pdfs.semanticscholar.org/43da/2070b6b7b2320a1fed2fd5e70e87332c9c5e.pdf) * <a name="myfootnote2">[2]</a> Cherly, Jørgen, Luis Gallardo, Leonid Vaserstein, and Ethel Wheland. *Solving quadratic equations over polynomial rings of characteristic two.* Publicacions Matemàtiques (1998): 131-142. [[PDF]](https://www.raco.cat/index.php/PublicacionsMatematiques/article/viewFile/37927/40412) * <a name="myfootnote3">[3]</a> J. Massey. *Shift-register synthesis and BCH decoding.* IEEE Transactions on Information Theory, vol. 15, no. 1, pp. 122-127, January 1969. [[PDF]](http://crypto.stanford.edu/~mironov/cs359/massey.pdf) * <a name="myfootnote4">[4]</a> Bhaskar Biswas, Vincent Herbert. *Efficient Root Finding of Polynomials over Fields of Characteristic 2.* 2009. hal-00626997. [[URL]](https://hal.archives-ouvertes.fr/hal-00626997) [[PDF]](https://hal.archives-ouvertes.fr/hal-00626997/document) * <a name="myfootnote6">[6]</a> Eppstein, David, Michael T. Goodrich, Frank Uyeda, and George Varghese. *What's the difference?: efficient set reconciliation without prior context.* ACM SIGCOMM Computer Communication Review, vol. 41, no. 4, pp. 218-229. ACM, 2011. [[PDF]](https://www.ics.uci.edu/~eppstein/pubs/EppGooUye-SIGCOMM-11.pdf) * <a name="myfootnote7">[7]</a> Goodrich, Michael T. and Michael Mitzenmacher. *Invertible bloom lookup tables.* 2011 49th Annual Allerton Conference on Communication, Control, and Computing (Allerton) (2011): 792-799. [[PDF]](https://arxiv.org/pdf/1101.2245.pdf) * <a name="myfootnote8">[8]</a> Maxwell, Gregory F. *[Blocksonly mode BW savings, the limits of efficient block xfer, and better relay](https://bitcointalk.org/index.php?topic=1377345.0)* Bitcointalk 2016, *[Technical notes on mempool synchronizing relay](https://nt4tn.net/tech-notes/2016.mempool_sync_relay.txt)* #bitcoin-wizards 2016. * <a name="myfootnote9">[9]</a> Maxwell, Gregory F. *[Block network coding](https://en.bitcoin.it/wiki/User:Gmaxwell/block_network_coding)* Bitcoin Wiki 2014, *[Technical notes on efficient block xfer](https://nt4tn.net/tech-notes/201512.efficient.block.xfer.txt)* #bitcoin-wizards 2015. * <a name="myfootnote10">[10]</a> Ruffing, Tim, Moreno-Sanchez, Pedro, Aniket, Kate, *P2P Mixing and Unlinkable Bitcoin Transactions* NDSS Symposium 2017 [[URL]](https://eprint.iacr.org/2016/824) [[PDF]](https://eprint.iacr.org/2016/824.pdf) * <a name="myfootnote11">[11]</a> Y. Misky, A. Trachtenberg, R. Zippel. *Set Reconciliation with Nearly Optimal Communication Complexity.* Cornell University, 2000. [[URL]](https://ecommons.cornell.edu/handle/1813/5803) [[PDF]](https://ecommons.cornell.edu/bitstream/handle/1813/5803/2000-1813.pdf) * <a name="myfootnote12">[12]</a> Itoh, Toshiya, and Shigeo Tsujii. "A fast algorithm for computing multiplicative inverses in GF (2m) using normal bases." Information and computation 78, no. 3 (1988): 171-177. [[URL]](https://www.sciencedirect.com/science/article/pii/0890540188900247)
0
bitcoin/src
bitcoin/src/minisketch/.cirrus.yml
env: BUILD: check HOST: MAKEFLAGS: -j4 BENCH: yes TESTRUNS: EXEC_CMD: ENABLE_FIELDS: cat_logs_snippet: &CAT_LOGS on_failure: cat_test_log_script: - cat test-suite.log || true cat_config_log_script: - cat config.log || true cat_test_env_script: - cat test_env.log || true cat_ci_env_script: - env merge_base_script_snippet: &MERGE_BASE merge_base_script: - if [ "$CIRRUS_PR" = "" ]; then exit 0; fi - git fetch $CIRRUS_REPO_CLONE_URL $CIRRUS_BASE_BRANCH - git config --global user.email "[email protected]" - git config --global user.name "ci" - git merge FETCH_HEAD # Merge base to detect silent merge conflicts env_matrix_snippet: &ENV_MATRIX_VALGRIND - env: ENABLE_FIELDS: "7,32,58" - env: BUILD: distcheck - env: EXEC_CMD: valgrind --error-exitcode=42 TESTRUNS: 1 BUILD: env_matrix_snippet: &ENV_MATRIX_SAN - env: ENABLE_FIELDS: 28 - env: BUILD: distcheck - env: CXXFLAGS: "-fsanitize=undefined -fno-omit-frame-pointer" LDFLAGS: "-fsanitize=undefined -fno-omit-frame-pointer" UBSAN_OPTIONS: "print_stacktrace=1:halt_on_error=1" BENCH: no env_matrix_snippet: &ENV_MATRIX_SAN_VALGRIND - env: ENABLE_FIELDS: "11,64,37" - env: BUILD: distcheck - env: EXEC_CMD: valgrind --error-exitcode=42 TESTRUNS: 1 BUILD: - env: CXXFLAGS: "-fsanitize=undefined -fno-omit-frame-pointer" LDFLAGS: "-fsanitize=undefined -fno-omit-frame-pointer" UBSAN_OPTIONS: "print_stacktrace=1:halt_on_error=1" BENCH: no task: name: "x86_64: Linux (Debian stable)" container: dockerfile: ci/linux-debian.Dockerfile memory: 2G cpu: 4 matrix: << : *ENV_MATRIX_SAN_VALGRIND matrix: - env: CC: gcc - env: CC: clang << : *MERGE_BASE test_script: - ./ci/cirrus.sh << : *CAT_LOGS task: name: "i686: Linux (Debian stable)" container: dockerfile: ci/linux-debian.Dockerfile memory: 2G cpu: 4 env: HOST: i686-linux-gnu matrix: << : *ENV_MATRIX_VALGRIND matrix: - env: CC: i686-linux-gnu-gcc - env: CC: clang --target=i686-pc-linux-gnu -isystem /usr/i686-linux-gnu/include test_script: - ./ci/cirrus.sh << : *CAT_LOGS task: name: "x86_64: macOS Catalina" macos_instance: image: catalina-base env: # Cirrus gives us a fixed number of 12 virtual CPUs. MAKEFLAGS: -j13 matrix: << : *ENV_MATRIX_SAN matrix: - env: CC: gcc-9 - env: CC: clang brew_script: - brew update - brew install automake libtool gcc@9 << : *MERGE_BASE test_script: - ./ci/cirrus.sh << : *CAT_LOGS task: name: "s390x (big-endian): Linux (Debian stable, QEMU)" container: dockerfile: ci/linux-debian.Dockerfile cpu: 4 memory: 2G env: EXEC_CMD: qemu-s390x -L /usr/s390x-linux-gnu HOST: s390x-linux-gnu BUILD: << : *MERGE_BASE test_script: # https://sourceware.org/bugzilla/show_bug.cgi?id=27008 - rm /etc/ld.so.cache - ./ci/cirrus.sh << : *CAT_LOGS task: name: "x86_64-w64-mingw32: Linux (Debian stable, Wine)" container: dockerfile: ci/linux-debian.Dockerfile cpu: 4 memory: 2G env: EXEC_CMD: wine HOST: x86_64-w64-mingw32 BUILD: << : *MERGE_BASE test_script: - ./ci/cirrus.sh << : *CAT_LOGS
0
bitcoin/src
bitcoin/src/minisketch/autogen.sh
#!/bin/sh # Copyright (c) 2013-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. set -e srcdir="$(dirname $0)" cd "$srcdir" if [ -z ${LIBTOOLIZE} ] && GLIBTOOLIZE="`which glibtoolize 2>/dev/null`"; then LIBTOOLIZE="${GLIBTOOLIZE}" export LIBTOOLIZE fi which autoreconf >/dev/null || \ (echo "configuration failed, please install autoconf first" && exit 1) autoreconf --install --force --warnings=all
0
bitcoin/src/minisketch/build-aux
bitcoin/src/minisketch/build-aux/m4/ax_check_preproc_flag.m4
# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_check_preproc_flag.html # =========================================================================== # # SYNOPSIS # # AX_CHECK_PREPROC_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) # # DESCRIPTION # # Check whether the given FLAG works with the current language's # preprocessor or gives an error. (Warnings, however, are ignored) # # ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on # success/failure. # # If EXTRA-FLAGS is defined, it is added to the preprocessor's default # flags when the check is done. The check is thus made with the flags: # "CPPFLAGS EXTRA-FLAGS FLAG". This can for example be used to force the # preprocessor to issue an error when a bad flag is given. # # INPUT gives an alternative input source to AC_PREPROC_IFELSE. # # NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this # macro in sync with AX_CHECK_{COMPILE,LINK}_FLAG. # # LICENSE # # Copyright (c) 2008 Guido U. Draheim <[email protected]> # Copyright (c) 2011 Maarten Bosmans <[email protected]> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 6 AC_DEFUN([AX_CHECK_PREPROC_FLAG], [AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]cppflags_$4_$1])dnl AC_CACHE_CHECK([whether _AC_LANG preprocessor accepts $1], CACHEVAR, [ ax_check_save_flags=$CPPFLAGS CPPFLAGS="$CPPFLAGS $4 $1" AC_PREPROC_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], [AS_VAR_SET(CACHEVAR,[yes])], [AS_VAR_SET(CACHEVAR,[no])]) CPPFLAGS=$ax_check_save_flags]) AS_VAR_IF(CACHEVAR,yes, [m4_default([$2], :)], [m4_default([$3], :)]) AS_VAR_POPDEF([CACHEVAR])dnl ])dnl AX_CHECK_PREPROC_FLAGS
0
bitcoin/src/minisketch/build-aux
bitcoin/src/minisketch/build-aux/m4/ax_check_link_flag.m4
# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_check_link_flag.html # =========================================================================== # # SYNOPSIS # # AX_CHECK_LINK_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) # # DESCRIPTION # # Check whether the given FLAG works with the linker or gives an error. # (Warnings, however, are ignored) # # ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on # success/failure. # # If EXTRA-FLAGS is defined, it is added to the linker's default flags # when the check is done. The check is thus made with the flags: "LDFLAGS # EXTRA-FLAGS FLAG". This can for example be used to force the linker to # issue an error when a bad flag is given. # # INPUT gives an alternative input source to AC_LINK_IFELSE. # # NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this # macro in sync with AX_CHECK_{PREPROC,COMPILE}_FLAG. # # LICENSE # # Copyright (c) 2008 Guido U. Draheim <[email protected]> # Copyright (c) 2011 Maarten Bosmans <[email protected]> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 6 AC_DEFUN([AX_CHECK_LINK_FLAG], [AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_ldflags_$4_$1])dnl AC_CACHE_CHECK([whether the linker accepts $1], CACHEVAR, [ ax_check_save_flags=$LDFLAGS LDFLAGS="$LDFLAGS $4 $1" AC_LINK_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], [AS_VAR_SET(CACHEVAR,[yes])], [AS_VAR_SET(CACHEVAR,[no])]) LDFLAGS=$ax_check_save_flags]) AS_VAR_IF(CACHEVAR,yes, [m4_default([$2], :)], [m4_default([$3], :)]) AS_VAR_POPDEF([CACHEVAR])dnl ])dnl AX_CHECK_LINK_FLAGS
0
bitcoin/src/minisketch/build-aux
bitcoin/src/minisketch/build-aux/m4/ax_check_compile_flag.m4
# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html # =========================================================================== # # SYNOPSIS # # AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT]) # # DESCRIPTION # # Check whether the given FLAG works with the current language's compiler # or gives an error. (Warnings, however, are ignored) # # ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on # success/failure. # # If EXTRA-FLAGS is defined, it is added to the current language's default # flags (e.g. CFLAGS) when the check is done. The check is thus made with # the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to # force the compiler to issue an error when a bad flag is given. # # INPUT gives an alternative input source to AC_COMPILE_IFELSE. # # NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this # macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG. # # LICENSE # # Copyright (c) 2008 Guido U. Draheim <[email protected]> # Copyright (c) 2011 Maarten Bosmans <[email protected]> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 6 AC_DEFUN([AX_CHECK_COMPILE_FLAG], [AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [ ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS _AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1" AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])], [AS_VAR_SET(CACHEVAR,[yes])], [AS_VAR_SET(CACHEVAR,[no])]) _AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags]) AS_VAR_IF(CACHEVAR,yes, [m4_default([$2], :)], [m4_default([$3], :)]) AS_VAR_POPDEF([CACHEVAR])dnl ])dnl AX_CHECK_COMPILE_FLAGS
0
bitcoin/src/minisketch/build-aux
bitcoin/src/minisketch/build-aux/m4/ax_cxx_compile_stdcxx.m4
# =========================================================================== # https://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx.html # =========================================================================== # # SYNOPSIS # # AX_CXX_COMPILE_STDCXX(VERSION, [ext|noext], [mandatory|optional]) # # DESCRIPTION # # Check for baseline language coverage in the compiler for the specified # version of the C++ standard. If necessary, add switches to CXX and # CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) # or '14' (for the C++14 standard). # # The second argument, if specified, indicates whether you insist on an # extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. # -std=c++11). If neither is specified, you get whatever works, with # preference for no added switch, and then for an extended mode. # # The third argument, if specified 'mandatory' or if left unspecified, # indicates that baseline support for the specified C++ standard is # required and that the macro should error out if no mode with that # support is found. If specified 'optional', then configuration proceeds # regardless, after defining HAVE_CXX${VERSION} if and only if a # supporting mode is found. # # LICENSE # # Copyright (c) 2008 Benjamin Kosnik <[email protected]> # Copyright (c) 2012 Zack Weinberg <[email protected]> # Copyright (c) 2013 Roy Stogner <[email protected]> # Copyright (c) 2014, 2015 Google Inc.; contributed by Alexey Sokolov <[email protected]> # Copyright (c) 2015 Paul Norman <[email protected]> # Copyright (c) 2015 Moritz Klammler <[email protected]> # Copyright (c) 2016, 2018 Krzesimir Nowak <[email protected]> # Copyright (c) 2019 Enji Cooper <[email protected]> # Copyright (c) 2020 Jason Merrill <[email protected]> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 12 dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro dnl (serial version number 13). AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], [$1], [14], [ax_cxx_compile_alternatives="14 1y"], [$1], [17], [ax_cxx_compile_alternatives="17 1z"], [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl m4_if([$2], [], [], [$2], [ext], [], [$2], [noext], [], [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX])])dnl m4_if([$3], [], [ax_cxx_compile_cxx$1_required=true], [$3], [mandatory], [ax_cxx_compile_cxx$1_required=true], [$3], [optional], [ax_cxx_compile_cxx$1_required=false], [m4_fatal([invalid third argument `$3' to AX_CXX_COMPILE_STDCXX])]) AC_LANG_PUSH([C++])dnl ac_success=no m4_if([$2], [], [dnl AC_CACHE_CHECK(whether $CXX supports C++$1 features by default, ax_cv_cxx_compile_cxx$1, [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], [ax_cv_cxx_compile_cxx$1=yes], [ax_cv_cxx_compile_cxx$1=no])]) if test x$ax_cv_cxx_compile_cxx$1 = xyes; then ac_success=yes fi]) m4_if([$2], [noext], [], [dnl if test x$ac_success = xno; then for alternative in ${ax_cxx_compile_alternatives}; do switch="-std=gnu++${alternative}" cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, $cachevar, [ac_save_CXX="$CXX" CXX="$CXX $switch" AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], [eval $cachevar=yes], [eval $cachevar=no]) CXX="$ac_save_CXX"]) if eval test x\$$cachevar = xyes; then CXX="$CXX $switch" if test -n "$CXXCPP" ; then CXXCPP="$CXXCPP $switch" fi ac_success=yes break fi done fi]) m4_if([$2], [ext], [], [dnl if test x$ac_success = xno; then dnl HP's aCC needs +std=c++11 according to: dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf dnl Cray's crayCC needs "-h std=c++11" for alternative in ${ax_cxx_compile_alternatives}; do for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, $cachevar, [ac_save_CXX="$CXX" CXX="$CXX $switch" AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_testbody_$1])], [eval $cachevar=yes], [eval $cachevar=no]) CXX="$ac_save_CXX"]) if eval test x\$$cachevar = xyes; then CXX="$CXX $switch" if test -n "$CXXCPP" ; then CXXCPP="$CXXCPP $switch" fi ac_success=yes break fi done if test x$ac_success = xyes; then break fi done fi]) AC_LANG_POP([C++]) if test x$ax_cxx_compile_cxx$1_required = xtrue; then if test x$ac_success = xno; then AC_MSG_ERROR([*** A compiler with support for C++$1 language features is required.]) fi fi if test x$ac_success = xno; then HAVE_CXX$1=0 AC_MSG_NOTICE([No compiler with C++$1 support was found]) else HAVE_CXX$1=1 AC_DEFINE(HAVE_CXX$1,1, [define if the compiler supports basic C++$1 syntax]) fi AC_SUBST(HAVE_CXX$1) ]) dnl Test body for checking C++11 support m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 ) dnl Test body for checking C++14 support m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 ) m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 ) dnl Tests for new features in C++11 m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ // If the compiler admits that it is not ready for C++11, why torture it? // Hopefully, this will speed up the test. #ifndef __cplusplus #error "This is not a C++ compiler" #elif __cplusplus < 201103L #error "This is not a C++11 compiler" #else namespace cxx11 { namespace test_static_assert { template <typename T> struct check { static_assert(sizeof(int) <= sizeof(T), "not big enough"); }; } namespace test_final_override { struct Base { virtual ~Base() {} virtual void f() {} }; struct Derived : public Base { virtual ~Derived() override {} virtual void f() override {} }; } namespace test_double_right_angle_brackets { template < typename T > struct check {}; typedef check<void> single_type; typedef check<check<void>> double_type; typedef check<check<check<void>>> triple_type; typedef check<check<check<check<void>>>> quadruple_type; } namespace test_decltype { int f() { int a = 1; decltype(a) b = 2; return a + b; } } namespace test_type_deduction { template < typename T1, typename T2 > struct is_same { static const bool value = false; }; template < typename T > struct is_same<T, T> { static const bool value = true; }; template < typename T1, typename T2 > auto add(T1 a1, T2 a2) -> decltype(a1 + a2) { return a1 + a2; } int test(const int c, volatile int v) { static_assert(is_same<int, decltype(0)>::value == true, ""); static_assert(is_same<int, decltype(c)>::value == false, ""); static_assert(is_same<int, decltype(v)>::value == false, ""); auto ac = c; auto av = v; auto sumi = ac + av + 'x'; auto sumf = ac + av + 1.0; static_assert(is_same<int, decltype(ac)>::value == true, ""); static_assert(is_same<int, decltype(av)>::value == true, ""); static_assert(is_same<int, decltype(sumi)>::value == true, ""); static_assert(is_same<int, decltype(sumf)>::value == false, ""); static_assert(is_same<int, decltype(add(c, v))>::value == true, ""); return (sumf > 0.0) ? sumi : add(c, v); } } namespace test_noexcept { int f() { return 0; } int g() noexcept { return 0; } static_assert(noexcept(f()) == false, ""); static_assert(noexcept(g()) == true, ""); } namespace test_constexpr { template < typename CharT > unsigned long constexpr strlen_c_r(const CharT *const s, const unsigned long acc) noexcept { return *s ? strlen_c_r(s + 1, acc + 1) : acc; } template < typename CharT > unsigned long constexpr strlen_c(const CharT *const s) noexcept { return strlen_c_r(s, 0UL); } static_assert(strlen_c("") == 0UL, ""); static_assert(strlen_c("1") == 1UL, ""); static_assert(strlen_c("example") == 7UL, ""); static_assert(strlen_c("another\0example") == 7UL, ""); } namespace test_rvalue_references { template < int N > struct answer { static constexpr int value = N; }; answer<1> f(int&) { return answer<1>(); } answer<2> f(const int&) { return answer<2>(); } answer<3> f(int&&) { return answer<3>(); } void test() { int i = 0; const int c = 0; static_assert(decltype(f(i))::value == 1, ""); static_assert(decltype(f(c))::value == 2, ""); static_assert(decltype(f(0))::value == 3, ""); } } namespace test_uniform_initialization { struct test { static const int zero {}; static const int one {1}; }; static_assert(test::zero == 0, ""); static_assert(test::one == 1, ""); } namespace test_lambdas { void test1() { auto lambda1 = [](){}; auto lambda2 = lambda1; lambda1(); lambda2(); } int test2() { auto a = [](int i, int j){ return i + j; }(1, 2); auto b = []() -> int { return '0'; }(); auto c = [=](){ return a + b; }(); auto d = [&](){ return c; }(); auto e = [a, &b](int x) mutable { const auto identity = [](int y){ return y; }; for (auto i = 0; i < a; ++i) a += b--; return x + identity(a + b); }(0); return a + b + c + d + e; } int test3() { const auto nullary = [](){ return 0; }; const auto unary = [](int x){ return x; }; using nullary_t = decltype(nullary); using unary_t = decltype(unary); const auto higher1st = [](nullary_t f){ return f(); }; const auto higher2nd = [unary](nullary_t f1){ return [unary, f1](unary_t f2){ return f2(unary(f1())); }; }; return higher1st(nullary) + higher2nd(nullary)(unary); } } namespace test_variadic_templates { template <int...> struct sum; template <int N0, int... N1toN> struct sum<N0, N1toN...> { static constexpr auto value = N0 + sum<N1toN...>::value; }; template <> struct sum<> { static constexpr auto value = 0; }; static_assert(sum<>::value == 0, ""); static_assert(sum<1>::value == 1, ""); static_assert(sum<23>::value == 23, ""); static_assert(sum<1, 2>::value == 3, ""); static_assert(sum<5, 5, 11>::value == 21, ""); static_assert(sum<2, 3, 5, 7, 11, 13>::value == 41, ""); } // http://stackoverflow.com/questions/13728184/template-aliases-and-sfinae // Clang 3.1 fails with headers of libstd++ 4.8.3 when using std::function // because of this. namespace test_template_alias_sfinae { struct foo {}; template<typename T> using member = typename T::member_type; template<typename T> void func(...) {} template<typename T> void func(member<T>*) {} void test(); void test() { func<foo>(0); } } } // namespace cxx11 #endif // __cplusplus >= 201103L ]]) dnl Tests for new features in C++14 m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ // If the compiler admits that it is not ready for C++14, why torture it? // Hopefully, this will speed up the test. #ifndef __cplusplus #error "This is not a C++ compiler" #elif __cplusplus < 201402L #error "This is not a C++14 compiler" #else namespace cxx14 { namespace test_polymorphic_lambdas { int test() { const auto lambda = [](auto&&... args){ const auto istiny = [](auto x){ return (sizeof(x) == 1UL) ? 1 : 0; }; const int aretiny[] = { istiny(args)... }; return aretiny[0]; }; return lambda(1, 1L, 1.0f, '1'); } } namespace test_binary_literals { constexpr auto ivii = 0b0000000000101010; static_assert(ivii == 42, "wrong value"); } namespace test_generalized_constexpr { template < typename CharT > constexpr unsigned long strlen_c(const CharT *const s) noexcept { auto length = 0UL; for (auto p = s; *p; ++p) ++length; return length; } static_assert(strlen_c("") == 0UL, ""); static_assert(strlen_c("x") == 1UL, ""); static_assert(strlen_c("test") == 4UL, ""); static_assert(strlen_c("another\0test") == 7UL, ""); } namespace test_lambda_init_capture { int test() { auto x = 0; const auto lambda1 = [a = x](int b){ return a + b; }; const auto lambda2 = [a = lambda1(x)](){ return a; }; return lambda2(); } } namespace test_digit_separators { constexpr auto ten_million = 100'000'000; static_assert(ten_million == 100000000, ""); } namespace test_return_type_deduction { auto f(int& x) { return x; } decltype(auto) g(int& x) { return x; } template < typename T1, typename T2 > struct is_same { static constexpr auto value = false; }; template < typename T > struct is_same<T, T> { static constexpr auto value = true; }; int test() { auto x = 0; static_assert(is_same<int, decltype(f(x))>::value, ""); static_assert(is_same<int&, decltype(g(x))>::value, ""); return x; } } } // namespace cxx14 #endif // __cplusplus >= 201402L ]]) dnl Tests for new features in C++17 m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ // If the compiler admits that it is not ready for C++17, why torture it? // Hopefully, this will speed up the test. #ifndef __cplusplus #error "This is not a C++ compiler" #elif __cplusplus < 201703L #error "This is not a C++17 compiler" #else #include <initializer_list> #include <utility> #include <type_traits> namespace cxx17 { namespace test_constexpr_lambdas { constexpr int foo = [](){return 42;}(); } namespace test::nested_namespace::definitions { } namespace test_fold_expression { template<typename... Args> int multiply(Args... args) { return (args * ... * 1); } template<typename... Args> bool all(Args... args) { return (args && ...); } } namespace test_extended_static_assert { static_assert (true); } namespace test_auto_brace_init_list { auto foo = {5}; auto bar {5}; static_assert(std::is_same<std::initializer_list<int>, decltype(foo)>::value); static_assert(std::is_same<int, decltype(bar)>::value); } namespace test_typename_in_template_template_parameter { template<template<typename> typename X> struct D; } namespace test_fallthrough_nodiscard_maybe_unused_attributes { int f1() { return 42; } [[nodiscard]] int f2() { [[maybe_unused]] auto unused = f1(); switch (f1()) { case 17: f1(); [[fallthrough]]; case 42: f1(); } return f1(); } } namespace test_extended_aggregate_initialization { struct base1 { int b1, b2 = 42; }; struct base2 { base2() { b3 = 42; } int b3; }; struct derived : base1, base2 { int d; }; derived d1 {{1, 2}, {}, 4}; // full initialization derived d2 {{}, {}, 4}; // value-initialized bases } namespace test_general_range_based_for_loop { struct iter { int i; int& operator* () { return i; } const int& operator* () const { return i; } iter& operator++() { ++i; return *this; } }; struct sentinel { int i; }; bool operator== (const iter& i, const sentinel& s) { return i.i == s.i; } bool operator!= (const iter& i, const sentinel& s) { return !(i == s); } struct range { iter begin() const { return {0}; } sentinel end() const { return {5}; } }; void f() { range r {}; for (auto i : r) { [[maybe_unused]] auto v = i; } } } namespace test_lambda_capture_asterisk_this_by_value { struct t { int i; int foo() { return [*this]() { return i; }(); } }; } namespace test_enum_class_construction { enum class byte : unsigned char {}; byte foo {42}; } namespace test_constexpr_if { template <bool cond> int f () { if constexpr(cond) { return 13; } else { return 42; } } } namespace test_selection_statement_with_initializer { int f() { return 13; } int f2() { if (auto i = f(); i > 0) { return 3; } switch (auto i = f(); i + 4) { case 17: return 2; default: return 1; } } } namespace test_template_argument_deduction_for_class_templates { template <typename T1, typename T2> struct pair { pair (T1 p1, T2 p2) : m1 {p1}, m2 {p2} {} T1 m1; T2 m2; }; void f() { [[maybe_unused]] auto p = pair{13, 42u}; } } namespace test_non_type_auto_template_parameters { template <auto n> struct B {}; B<5> b1; B<'a'> b2; } namespace test_structured_bindings { int arr[2] = { 1, 2 }; std::pair<int, int> pr = { 1, 2 }; auto f1() -> int(&)[2] { return arr; } auto f2() -> std::pair<int, int>& { return pr; } struct S { int x1 : 2; volatile double y1; }; S f3() { return {}; } auto [ x1, y1 ] = f1(); auto& [ xr1, yr1 ] = f1(); auto [ x2, y2 ] = f2(); auto& [ xr2, yr2 ] = f2(); const auto [ x3, y3 ] = f3(); } namespace test_exception_spec_type_system { struct Good {}; struct Bad {}; void g1() noexcept; void g2(); template<typename T> Bad f(T*, T*); template<typename T1, typename T2> Good f(T1*, T2*); static_assert (std::is_same_v<Good, decltype(f(g1, g2))>); } namespace test_inline_variables { template<class T> void f(T) {} template<class T> inline T g(T) { return T{}; } template<> inline void f<>(int) {} template<> int g<>(int) { return 5; } } } // namespace cxx17 #endif // __cplusplus < 201703L ]])
0
bitcoin/src/minisketch
bitcoin/src/minisketch/ci/linux-debian.Dockerfile
FROM debian:stable RUN dpkg --add-architecture i386 RUN dpkg --add-architecture s390x RUN apt-get update # dkpg-dev: to make pkg-config work in cross-builds RUN apt-get install --no-install-recommends --no-upgrade -y \ git ca-certificates \ make automake libtool pkg-config dpkg-dev valgrind qemu-user \ gcc g++ clang libc6-dbg \ gcc-i686-linux-gnu g++-i686-linux-gnu libc6-dev-i386-cross libc6-dbg:i386 \ g++-s390x-linux-gnu gcc-s390x-linux-gnu libc6-dev-s390x-cross libc6-dbg:s390x \ wine g++-mingw-w64-x86-64 # Run a dummy command in wine to make it set up configuration RUN wine true || true
0
bitcoin/src/minisketch
bitcoin/src/minisketch/ci/cirrus.sh
#!/bin/sh set -e set -x export LC_ALL=C env >> test_env.log $CC -v || true valgrind --version || true ./autogen.sh FIELDS= if [ -n "$ENABLE_FIELDS" ]; then FIELDS="--enable-fields=$ENABLE_FIELDS" fi ./configure --host="$HOST" --enable-benchmark="$BENCH" $FIELDS # We have set "-j<n>" in MAKEFLAGS. make # Print information about binaries so that we can see that the architecture is correct file test* || true file bench* || true file .libs/* || true if [ -n "$BUILD" ] then make "$BUILD" fi if [ -n "$EXEC_CMD" ]; then $EXEC_CMD ./test $TESTRUNS $EXEC_CMD ./test-verify $TESTRUNS fi if [ "$BENCH" = "yes" ]; then $EXEC_CMD ./bench fi
0
bitcoin/src/minisketch
bitcoin/src/minisketch/include/minisketch.h
#ifndef _MINISKETCH_H_ #define _MINISKETCH_H_ 1 #include <stdint.h> #include <stdlib.h> #ifdef _MSC_VER # include <BaseTsd.h> typedef SSIZE_T ssize_t; #else # include <unistd.h> #endif #ifndef MINISKETCH_API # if defined(_WIN32) # ifdef MINISKETCH_BUILD # define MINISKETCH_API __declspec(dllexport) # else # define MINISKETCH_API # endif # elif defined(__GNUC__) && (__GNUC__ >= 4) && defined(MINISKETCH_BUILD) # define MINISKETCH_API __attribute__ ((visibility ("default"))) # else # define MINISKETCH_API # endif #endif #ifdef __cplusplus # if __cplusplus >= 201103L # include <memory> # include <vector> # include <cassert> # if __cplusplus >= 201703L # include <optional> # endif // __cplusplus >= 201703L # endif // __cplusplus >= 201103L extern "C" { #endif // __cplusplus /** Opaque type for decoded sketches. */ typedef struct minisketch minisketch; /** Determine whether support for elements of `bits` bits was compiled in. */ MINISKETCH_API int minisketch_bits_supported(uint32_t bits); /** Determine the maximum number of implementations available. * * Multiple implementations may be available for a given element size, with * different performance characteristics on different hardware. * * Each implementation is identified by a number from 0 to the output of this * function call, inclusive. Note that not every combination of implementation * and element size may exist (see further). */ MINISKETCH_API uint32_t minisketch_implementation_max(void); /** Determine if the a combination of bits and implementation number is available. * * Returns 1 if it is, 0 otherwise. */ MINISKETCH_API int minisketch_implementation_supported(uint32_t bits, uint32_t implementation); /** Construct a sketch for a given element size, implementation and capacity. * * If the combination of `bits` and `implementation` is unavailable, or when * OOM occurs, NULL is returned. If minisketch_implementation_supported * returns 1 for the specified bits and implementation, this will always succeed * (except when allocation fails). * * If the result is not NULL, it must be destroyed using minisketch_destroy. */ MINISKETCH_API minisketch* minisketch_create(uint32_t bits, uint32_t implementation, size_t capacity); /** Get the element size of a sketch in bits. */ MINISKETCH_API uint32_t minisketch_bits(const minisketch* sketch); /** Get the capacity of a sketch. */ MINISKETCH_API size_t minisketch_capacity(const minisketch* sketch); /** Get the implementation of a sketch. */ MINISKETCH_API uint32_t minisketch_implementation(const minisketch* sketch); /** Set the seed for randomizing algorithm choices to a fixed value. * * By default, sketches are initialized with a random seed. This is important * to avoid scenarios where an attacker could force worst-case behavior. * * This function initializes the seed to a user-provided value (any 64-bit * integer is acceptable, regardless of field size). * * When seed is -1, a fixed internal value with predictable behavior is * used. It is only intended for testing. */ MINISKETCH_API void minisketch_set_seed(minisketch* sketch, uint64_t seed); /** Clone a sketch. * * The result must be destroyed using minisketch_destroy. */ MINISKETCH_API minisketch* minisketch_clone(const minisketch* sketch); /** Destroy a sketch. * * The pointer that was passed in may not be used anymore afterwards. */ MINISKETCH_API void minisketch_destroy(minisketch* sketch); /** Compute the size in bytes for serializing a given sketch. */ MINISKETCH_API size_t minisketch_serialized_size(const minisketch* sketch); /** Serialize a sketch to bytes. */ MINISKETCH_API void minisketch_serialize(const minisketch* sketch, unsigned char* output); /** Deserialize a sketch from bytes. */ MINISKETCH_API void minisketch_deserialize(minisketch* sketch, const unsigned char* input); /** Add an element to a sketch. * * If the element to be added is too large for the sketch, the most significant * bits of the element are dropped. More precisely, if the element size of * `sketch` is b bits, then this function adds the unsigned integer represented * by the b least significant bits of `element` to `sketch`. * * If the element to be added is 0 (after potentially dropping the most significant * bits), then this function is a no-op. Sketches cannot contain an element with * the value 0. * * Note that adding the same element a second time removes it again. */ MINISKETCH_API void minisketch_add_uint64(minisketch* sketch, uint64_t element); /** Merge the elements of another sketch into this sketch. * * After merging, `sketch` will contain every element that existed in one but not * both of the input sketches. It can be seen as an exclusive or operation on * the set elements. If the capacity of `other_sketch` is lower than `sketch`'s, * merging reduces the capacity of `sketch` to that of `other_sketch`. * * This function returns the capacity of `sketch` after merging has been performed * (where this capacity is at least 1), or 0 to indicate that merging has failed because * the two input sketches differ in their element size or implementation. If 0 is * returned, `sketch` (and its capacity) have not been modified. * * It is also possible to perform this operation directly on the serializations * of two sketches with the same element size and capacity by performing a bitwise XOR * of the serializations. */ MINISKETCH_API size_t minisketch_merge(minisketch* sketch, const minisketch* other_sketch); /** Decode a sketch. * * `output` is a pointer to an array of `max_element` uint64_t's, which will be * filled with the elements in this sketch. * * The return value is the number of decoded elements, or -1 if decoding failed. */ MINISKETCH_API ssize_t minisketch_decode(const minisketch* sketch, size_t max_elements, uint64_t* output); /** Compute the capacity needed to achieve a certain rate of false positives. * * A sketch with capacity c and no more than c elements can always be decoded * correctly. However, if it has more than c elements, or contains just random * bytes, it is possible that it will still decode, but the result will be * nonsense. This can be counteracted by increasing the capacity slightly. * * Given a field size bits, an intended number of elements that can be decoded * max_elements, and a false positive probability of 1 in 2**fpbits, this * function computes the necessary capacity. It is only guaranteed to be * accurate up to fpbits=256. */ MINISKETCH_API size_t minisketch_compute_capacity(uint32_t bits, size_t max_elements, uint32_t fpbits); /** Compute what max_elements can be decoded for a certain rate of false positives. * * This is the inverse operation of minisketch_compute_capacity. It determines, * given a field size bits, a capacity of a sketch, and an acceptable false * positive probability of 1 in 2**fpbits, what the maximum allowed * max_elements value is. If no value of max_elements would give the desired * false positive probability, 0 is returned. * * Note that this is not an exact inverse of minisketch_compute_capacity. For * example, with bits=32, fpbits=16, and max_elements=8, * minisketch_compute_capacity will return 9, as capacity 8 would only have a * false positive chance of 1 in 2^15.3. Increasing the capacity to 9 however * decreases the fp chance to 1 in 2^47.3, enough for max_elements=9 (with fp * chance of 1 in 2^18.5). Therefore, minisketch_compute_max_elements with * capacity=9 will return 9. */ MINISKETCH_API size_t minisketch_compute_max_elements(uint32_t bits, size_t capacity, uint32_t fpbits); #ifdef __cplusplus } #if __cplusplus >= 201103L /** Simple RAII C++11 wrapper around the minisketch API. */ class Minisketch { struct Deleter { void operator()(minisketch* ptr) const { minisketch_destroy(ptr); } }; std::unique_ptr<minisketch, Deleter> m_minisketch; public: /** Check whether the library supports fields of the given size. */ static bool BitsSupported(uint32_t bits) noexcept { return minisketch_bits_supported(bits); } /** Get the highest supported implementation number. */ static uint32_t MaxImplementation() noexcept { return minisketch_implementation_max(); } /** Check whether the library supports fields with a given size and implementation number. * If a particular field size `bits` is supported, implementation 0 is always supported for it. * Higher implementation numbers may or may not be available as well, up to MaxImplementation(). */ static bool ImplementationSupported(uint32_t bits, uint32_t implementation) noexcept { return minisketch_implementation_supported(bits, implementation); } /** Given field size and a maximum number of decodable elements n, compute what capacity c to * use so that sketches with more elements than n have a chance no higher than 2^-fpbits of * being decoded incorrectly (and will instead fail when decoding for up to n elements). * * See minisketch_compute_capacity for more details. */ static size_t ComputeCapacity(uint32_t bits, size_t max_elements, uint32_t fpbits) noexcept { return minisketch_compute_capacity(bits, max_elements, fpbits); } /** Reverse operation of ComputeCapacity. See minisketch_compute_max_elements. */ static size_t ComputeMaxElements(uint32_t bits, size_t capacity, uint32_t fpbits) noexcept { return minisketch_compute_max_elements(bits, capacity, fpbits); } /** Construct a clone of the specified sketch. */ Minisketch(const Minisketch& sketch) noexcept { if (sketch.m_minisketch) { m_minisketch = std::unique_ptr<minisketch, Deleter>(minisketch_clone(sketch.m_minisketch.get())); } } /** Make this Minisketch a clone of the specified one. */ Minisketch& operator=(const Minisketch& sketch) noexcept { if (sketch.m_minisketch) { m_minisketch = std::unique_ptr<minisketch, Deleter>(minisketch_clone(sketch.m_minisketch.get())); } return *this; } /** Check whether this Minisketch object is valid. */ explicit operator bool() const noexcept { return bool{m_minisketch}; } /** Construct an (invalid) Minisketch object. */ Minisketch() noexcept = default; /** Move constructor. */ Minisketch(Minisketch&&) noexcept = default; /** Move assignment. */ Minisketch& operator=(Minisketch&&) noexcept = default; /** Construct a Minisketch object with the specified parameters. * * If bits is not BitsSupported(), or the combination of bits and capacity is not * ImplementationSupported(), or OOM occurs internally, an invalid Minisketch * object will be constructed. Use operator bool() to check that this isn't the * case before performing any other operations. */ Minisketch(uint32_t bits, uint32_t implementation, size_t capacity) noexcept { m_minisketch = std::unique_ptr<minisketch, Deleter>(minisketch_create(bits, implementation, capacity)); } /** Create a Minisketch object sufficiently large for the specified number of elements at given fpbits. * It may construct an invalid object, which you may need to check for. */ static Minisketch CreateFP(uint32_t bits, uint32_t implementation, size_t max_elements, uint32_t fpbits) noexcept { return Minisketch(bits, implementation, ComputeCapacity(bits, max_elements, fpbits)); } /** Return the field size for a (valid) Minisketch object. */ uint32_t GetBits() const noexcept { return minisketch_bits(m_minisketch.get()); } /** Return the capacity for a (valid) Minisketch object. */ size_t GetCapacity() const noexcept { return minisketch_capacity(m_minisketch.get()); } /** Return the implementation number for a (valid) Minisketch object. */ uint32_t GetImplementation() const noexcept { return minisketch_implementation(m_minisketch.get()); } /** Set the seed for a (valid) Minisketch object. See minisketch_set_seed(). */ Minisketch& SetSeed(uint64_t seed) noexcept { minisketch_set_seed(m_minisketch.get(), seed); return *this; } /** Add (or remove, if already present) an element to a (valid) Minisketch object. * See minisketch_add_uint64(). */ Minisketch& Add(uint64_t element) noexcept { minisketch_add_uint64(m_minisketch.get(), element); return *this; } /** Merge sketch into *this; both have to be valid Minisketch objects. * See minisketch_merge for details. */ Minisketch& Merge(const Minisketch& sketch) noexcept { minisketch_merge(m_minisketch.get(), sketch.m_minisketch.get()); return *this; } /** Decode this (valid) Minisketch object into the result vector, up to as many elements as the * vector's size permits. */ bool Decode(std::vector<uint64_t>& result) const { ssize_t ret = minisketch_decode(m_minisketch.get(), result.size(), result.data()); if (ret == -1) return false; result.resize(ret); return true; } /** Get the serialized size in bytes for this (valid) Minisketch object.. */ size_t GetSerializedSize() const noexcept { return minisketch_serialized_size(m_minisketch.get()); } /** Serialize this (valid) Minisketch object as a byte vector. */ std::vector<unsigned char> Serialize() const { std::vector<unsigned char> result(GetSerializedSize()); minisketch_serialize(m_minisketch.get(), result.data()); return result; } /** Deserialize into this (valid) Minisketch from an object containing its bytes (which has data() * and size() members). */ template<typename T> Minisketch& Deserialize( const T& obj, typename std::enable_if< std::is_convertible<typename std::remove_pointer<decltype(obj.data())>::type (*)[], const unsigned char (*)[]>::value && std::is_convertible<decltype(obj.size()), std::size_t>::value, std::nullptr_t >::type = nullptr) noexcept { assert(GetSerializedSize() == obj.size()); minisketch_deserialize(m_minisketch.get(), obj.data()); return *this; } #if __cplusplus >= 201703L /** C++17 only: like Decode(), but up to a specified number of elements into an optional vector. */ std::optional<std::vector<uint64_t>> Decode(size_t max_elements) const { std::vector<uint64_t> result(max_elements); ssize_t ret = minisketch_decode(m_minisketch.get(), max_elements, result.data()); if (ret == -1) return {}; result.resize(ret); return result; } /** C++17 only: similar to Decode(), but with specified false positive probability. */ std::optional<std::vector<uint64_t>> DecodeFP(uint32_t fpbits) const { return Decode(ComputeMaxElements(GetBits(), GetCapacity(), fpbits)); } #endif // __cplusplus >= 201703L }; #endif // __cplusplus >= 201103L #endif // __cplusplus #endif // _MINISKETCH_H_
0
bitcoin/src/minisketch
bitcoin/src/minisketch/tests/pyminisketch.py
#!/usr/bin/env python3 # Copyright (c) 2020 Pieter Wuille # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. """Native Python (slow) reimplementation of libminisketch' algorithms.""" import random import unittest # Irreducible polynomials over GF(2) to use (represented as integers). # # Most fields can be defined by multiple such polynomials. Minisketch uses the one with the minimal # number of nonzero coefficients, and tie-breaking by picking the lexicographically first among # those. # # All polynomials for degrees 2 through 64 (inclusive) are given. GF2_MODULI = [ None, None, 2**2 + 2**1 + 1, 2**3 + 2**1 + 1, 2**4 + 2**1 + 1, 2**5 + 2**2 + 1, 2**6 + 2**1 + 1, 2**7 + 2**1 + 1, 2**8 + 2**4 + 2**3 + 2**1 + 1, 2**9 + 2**1 + 1, 2**10 + 2**3 + 1, 2**11 + 2**2 + 1, 2**12 + 2**3 + 1, 2**13 + 2**4 + 2**3 + 2**1 + 1, 2**14 + 2**5 + 1, 2**15 + 2**1 + 1, 2**16 + 2**5 + 2**3 + 2**1 + 1, 2**17 + 2**3 + 1, 2**18 + 2**3 + 1, 2**19 + 2**5 + 2**2 + 2**1 + 1, 2**20 + 2**3 + 1, 2**21 + 2**2 + 1, 2**22 + 2**1 + 1, 2**23 + 2**5 + 1, 2**24 + 2**4 + 2**3 + 2**1 + 1, 2**25 + 2**3 + 1, 2**26 + 2**4 + 2**3 + 2**1 + 1, 2**27 + 2**5 + 2**2 + 2**1 + 1, 2**28 + 2**1 + 1, 2**29 + 2**2 + 1, 2**30 + 2**1 + 1, 2**31 + 2**3 + 1, 2**32 + 2**7 + 2**3 + 2**2 + 1, 2**33 + 2**10 + 1, 2**34 + 2**7 + 1, 2**35 + 2**2 + 1, 2**36 + 2**9 + 1, 2**37 + 2**6 + 2**4 + 2**1 + 1, 2**38 + 2**6 + 2**5 + 2**1 + 1, 2**39 + 2**4 + 1, 2**40 + 2**5 + 2**4 + 2**3 + 1, 2**41 + 2**3 + 1, 2**42 + 2**7 + 1, 2**43 + 2**6 + 2**4 + 2**3 + 1, 2**44 + 2**5 + 1, 2**45 + 2**4 + 2**3 + 2**1 + 1, 2**46 + 2**1 + 1, 2**47 + 2**5 + 1, 2**48 + 2**5 + 2**3 + 2**2 + 1, 2**49 + 2**9 + 1, 2**50 + 2**4 + 2**3 + 2**2 + 1, 2**51 + 2**6 + 2**3 + 2**1 + 1, 2**52 + 2**3 + 1, 2**53 + 2**6 + 2**2 + 2**1 + 1, 2**54 + 2**9 + 1, 2**55 + 2**7 + 1, 2**56 + 2**7 + 2**4 + 2**2 + 1, 2**57 + 2**4 + 1, 2**58 + 2**19 + 1, 2**59 + 2**7 + 2**4 + 2**2 + 1, 2**60 + 2**1 + 1, 2**61 + 2**5 + 2**2 + 2**1 + 1, 2**62 + 2**29 + 1, 2**63 + 2**1 + 1, 2**64 + 2**4 + 2**3 + 2**1 + 1 ] class GF2Ops: """Class to perform GF(2^field_size) operations on elements represented as integers. Given that elements are represented as integers, addition is simply xor, and not exposed here. """ def __init__(self, field_size): """Construct a GF2Ops object for the specified field size.""" self.field_size = field_size self._modulus = GF2_MODULI[field_size] assert self._modulus is not None def mul2(self, x): """Multiply x by 2 in GF(2^field_size).""" x <<= 1 if x >> self.field_size: x ^= self._modulus return x def mul(self, x, y): """Multiply x by y in GF(2^field_size).""" ret = 0 while y: if y & 1: ret ^= x y >>= 1 x = self.mul2(x) return ret def sqr(self, x): """Square x in GF(2^field_size).""" return self.mul(x, x) def inv(self, x): """Compute the inverse of x in GF(2^field_size).""" assert x != 0 # Use the extended polynomial Euclidean GCD algorithm on (modulus, x), over GF(2). # See https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor. t1, t2 = 0, 1 r1, r2 = self._modulus, x r1l, r2l = self.field_size + 1, r2.bit_length() while r2: q = r1l - r2l r1 ^= r2 << q t1 ^= t2 << q r1l = r1.bit_length() if r1 < r2: t1, t2 = t2, t1 r1, r2 = r2, r1 r1l, r2l = r2l, r1l assert r1 == 1 return t1 class TestGF2Ops(unittest.TestCase): """Test class for basic arithmetic properties of GF2Ops.""" def field_size_test(self, field_size): """Test operations for given field_size.""" gf = GF2Ops(field_size) for i in range(100): x = random.randrange(1 << field_size) y = random.randrange(1 << field_size) x2 = gf.mul2(x) xy = gf.mul(x, y) self.assertEqual(x2, gf.mul(x, 2)) # mul2(x) == x*2 self.assertEqual(x2, gf.mul(2, x)) # mul2(x) == 2*x self.assertEqual(xy == 0, x == 0 or y == 0) self.assertEqual(xy == x, y == 1 or x == 0) self.assertEqual(xy == y, x == 1 or y == 0) self.assertEqual(xy, gf.mul(y, x)) # x*y == y*x if i < 10: xp = x for _ in range(field_size): xp = gf.sqr(xp) self.assertEqual(xp, x) # x^(2^field_size) == x if y != 0: yi = gf.inv(y) self.assertEqual(y == yi, y == 1) # y==1/x iff y==1 self.assertEqual(gf.mul(y, yi), 1) # y*(1/y) == 1 yii = gf.inv(yi) self.assertEqual(y, yii) # 1/(1/y) == y if x != 0: xi = gf.inv(x) xyi = gf.inv(xy) self.assertEqual(xyi, gf.mul(xi, yi)) # (1/x)*(1/y) == 1/(x*y) def test(self): """Run tests.""" for field_size in range(2, 65): self.field_size_test(field_size) # The operations below operate on polynomials over GF(2^field_size), represented as lists of # integers: # # [a, b, c, ...] = a + b*x + c*x^2 + ... # # As an invariant, there are never any trailing zeroes in the list representation. # # Examples: # * [] = 0 # * [3] = 3 # * [0, 1] = x # * [2, 0, 5] = 5*x^2 + 2 def poly_monic(poly, gf): """Return a monic version of the polynomial poly.""" # Multiply every coefficient with the inverse of the top coefficient. inv = gf.inv(poly[-1]) return [gf.mul(inv, v) for v in poly] def poly_divmod(poly, mod, gf): """Return the polynomial (quotient, remainder) of poly divided by mod.""" assert len(mod) > 0 and mod[-1] == 1 # Require monic mod. if len(poly) < len(mod): return ([], poly) val = list(poly) div = [0 for _ in range(len(val) - len(mod) + 1)] while len(val) >= len(mod): term = val[-1] div[len(val) - len(mod)] = term # If the highest coefficient in val is nonzero, subtract a multiple of mod from it. val.pop() if term != 0: for x in range(len(mod) - 1): val[1 + x - len(mod)] ^= gf.mul(term, mod[x]) # Prune trailing zero coefficients. while len(val) > 0 and val[-1] == 0: val.pop() return div, val def poly_gcd(a, b, gf): """Return the polynomial GCD of a and b.""" if len(a) < len(b): a, b = b, a # Use Euclid's algorithm to find the GCD of a and b. # see https://en.wikipedia.org/wiki/Polynomial_greatest_common_divisor#Euclid's_algorithm. while len(b) > 0: b = poly_monic(b, gf) (_, b), a = poly_divmod(a, b, gf), b return a def poly_sqr(poly, gf): """Return the square of polynomial poly.""" if len(poly) == 0: return [] # In characteristic-2 fields, thanks to Frobenius' endomorphism ((a + b)^2 = a^2 + b^2), # squaring a polynomial is easy: square all the coefficients and interleave with zeroes. # E.g., (3 + 5*x + 17*x^2)^2 = 3^2 + (5*x)^2 + (17*x^2)^2. # See https://en.wikipedia.org/wiki/Frobenius_endomorphism. return [0 if i & 1 else gf.sqr(poly[i // 2]) for i in range(2 * len(poly) - 1)] def poly_tracemod(poly, param, gf): """Compute y + y^2 + y^4 + ... + y^(2^(field_size-1)) mod poly, where y = param*x.""" out = [0, param] for _ in range(gf.field_size - 1): # In each loop iteration i, we start with out = y + y^2 + ... + y^(2^i). By squaring that we # transform it into out = y^2 + y^4 + ... + y^(2^(i+1)). out = poly_sqr(out, gf) # Thus, we just need to add y again to it to get out = y + ... + y^(2^(i+1)). while len(out) < 2: out.append(0) out[1] = param # Finally take a modulus to keep the intermediary polynomials small. _, out = poly_divmod(out, poly, gf) return out def poly_frobeniusmod(poly, gf): """Compute x^(2^field_size) mod poly.""" out = [0, 1] for _ in range(gf.field_size): _, out = poly_divmod(poly_sqr(out, gf), poly, gf) return out def poly_find_roots(poly, gf): """Find the roots of poly if fully factorizable with unique roots, [] otherwise.""" assert len(poly) > 0 # If the polynomial is constant (and nonzero), it has no roots. if len(poly) == 1: return [] # Make the polynomial monic (which doesn't change its roots). poly = poly_monic(poly, gf) # If the polynomial is of the form x+a, return a. if len(poly) == 2: return [poly[0]] # Otherwise, first test that poly can be completely factored into unique roots. The polynomial # x^(2^fieldsize)-x has every field element once as root. Thus we want to know that that is a # multiple of poly. Compute x^(field_size) mod poly, which needs to equal x if that is the case # (unless poly has degree <= 1, but that case is handled above). if poly_frobeniusmod(poly, gf) != [0, 1]: return [] def rec_split(poly, randv): """Recursively split poly using the Berlekamp trace algorithm.""" # See https://hal.archives-ouvertes.fr/hal-00626997/document. assert len(poly) > 1 and poly[-1] == 1 # Require a monic poly. # If poly is of the form x+a, its root is a. if len(poly) == 2: return [poly[0]] # Try consecutive randomization factors randv, until one is found that factors poly. while True: # Compute the trace of (randv*x) mod poly. This is a polynomial that maps half of the # domain to 0, and the other half to 1. Which half that is is controlled by randv. # By taking it modulo poly, we only add a multiple of poly. Thus the result has at least # the shared roots of the trace polynomial and poly still, but may have others. trace = poly_tracemod(poly, randv, gf) # Using the set {2^i*a for i=0..fieldsize-1} gives optimally independent randv values # (no more than fieldsize are ever needed). randv = gf.mul2(randv) # Now take the GCD of this trace polynomial with poly. The result is a polynomial # that only has the shared roots of the trace polynomial and poly as roots. gcd = poly_gcd(trace, poly, gf) # If the result has a degree higher than 1, and lower than that of poly, we found a # useful factorization. if len(gcd) != len(poly) and len(gcd) > 1: break # Otherwise, continue with another randv. # Find the actual factors: the monic version of the GCD above, and poly divided by it. factor1 = poly_monic(gcd, gf) factor2, _ = poly_divmod(poly, gcd, gf) # Recurse. return rec_split(factor1, randv) + rec_split(factor2, randv) # Invoke the recursive splitting with a random initial factor, and sort the results. return sorted(rec_split(poly, random.randrange(1, 1 << gf.field_size))) class TestPolyFindRoots(unittest.TestCase): """Test class for poly_find_roots.""" def field_size_test(self, field_size): """Run tests for given field_size.""" gf = GF2Ops(field_size) for test_size in [0, 1, 2, 3, 10]: roots = [random.randrange(1 << field_size) for _ in range(test_size)] roots_set = set(roots) # Construct a polynomial with all elements of roots as roots (with multiplicity). poly = [1] for root in roots: new_poly = [0] + poly for n, c in enumerate(poly): new_poly[n] ^= gf.mul(c, root) poly = new_poly # Invoke the root finding algorithm. found_roots = poly_find_roots(poly, gf) # The result must match the input, unless any roots were repeated. if len(roots) == len(roots_set): self.assertEqual(found_roots, sorted(roots)) else: self.assertEqual(found_roots, []) def test(self): """Run tests.""" for field_size in range(2, 65): self.field_size_test(field_size) def berlekamp_massey(syndromes, gf): """Implement the Berlekamp-Massey algorithm. Takes as input a sequence of GF(2^field_size) elements, and returns the shortest LSFR that generates it, represented as a polynomial. """ # See https://en.wikipedia.org/wiki/Berlekamp%E2%80%93Massey_algorithm. current = [1] prev = [1] b_inv = 1 for n, discrepancy in enumerate(syndromes): # Compute discrepancy for i in range(1, len(current)): discrepancy ^= gf.mul(syndromes[n - i], current[i]) # Correct if discrepancy is nonzero. if discrepancy: x = n + 1 - (len(current) - 1) - (len(prev) - 1) if 2 * (len(current) - 1) <= n: tmp = list(current) current.extend(0 for _ in range(len(prev) + x - len(current))) mul = gf.mul(discrepancy, b_inv) for i, v in enumerate(prev): current[i + x] ^= gf.mul(mul, v) prev = tmp b_inv = gf.inv(discrepancy) else: mul = gf.mul(discrepancy, b_inv) for i, v in enumerate(prev): current[i + x] ^= gf.mul(mul, v) return current class Minisketch: """A Minisketch sketch. This represents a sketch of a certain capacity, with elements of a certain bit size. """ def __init__(self, field_size, capacity): """Initialize an empty sketch with the specified field_size size and capacity.""" self.field_size = field_size self.capacity = capacity self.odd_syndromes = [0] * capacity self.gf = GF2Ops(field_size) def add(self, element): """Add an element to this sketch. 1 <= element < 2**field_size.""" sqr = self.gf.sqr(element) for pos in range(self.capacity): self.odd_syndromes[pos] ^= element element = self.gf.mul(sqr, element) def serialized_size(self): """Compute how many bytes a serialization of this sketch will be in size.""" return (self.capacity * self.field_size + 7) // 8 def serialize(self): """Serialize this sketch to bytes.""" val = 0 for i in range(self.capacity): val |= self.odd_syndromes[i] << (self.field_size * i) return val.to_bytes(self.serialized_size(), 'little') def deserialize(self, byte_data): """Deserialize a byte array into this sketch, overwriting its contents.""" assert len(byte_data) == self.serialized_size() val = int.from_bytes(byte_data, 'little') for i in range(self.capacity): self.odd_syndromes[i] = (val >> (self.field_size * i)) & ((1 << self.field_size) - 1) def clone(self): """Return a clone of this sketch.""" ret = Minisketch(self.field_size, self.capacity) ret.odd_syndromes = list(self.odd_syndromes) ret.gf = self.gf return ret def merge(self, other): """Merge a sketch with another sketch. Corresponds to XOR'ing their serializations.""" assert self.capacity == other.capacity assert self.field_size == other.field_size for i in range(self.capacity): self.odd_syndromes[i] ^= other.odd_syndromes[i] def decode(self, max_count=None): """Decode the contents of this sketch. Returns either a list of elements or None if undecodable. """ # We know the odd syndromes s1=x+y+..., s3=x^3+y^3+..., s5=..., and reconstruct the even # syndromes from this: # * s2 = x^2+y^2+.... = (x+y+...)^2 = s1^2 # * s4 = x^4+y^4+.... = (x^2+y^2+...)^2 = s2^2 # * s6 = x^6+y^6+.... = (x^3+y^3+...)^2 = s3^2 all_syndromes = [0 for _ in range(2 * len(self.odd_syndromes))] for i in range(len(self.odd_syndromes)): all_syndromes[i * 2] = self.odd_syndromes[i] all_syndromes[i * 2 + 1] = self.gf.sqr(all_syndromes[i]) # Given the syndromes, find the polynomial that generates them. poly = berlekamp_massey(all_syndromes, self.gf) # Deal with failure and trivial cases. if len(poly) == 0: return None if len(poly) == 1: return [] if max_count is not None and len(poly) > 1 + max_count: return None # If the polynomial can be factored into (1-m1*x)*(1-m2*x)*...*(1-mn*x), then {m1,m2,...,mn} # is our set. As each factor (1-m*x) has 1/m as root, we're really just looking for the # inverses of the roots. We find these by reversing the order of the coefficients, and # finding the roots. roots = poly_find_roots(list(reversed(poly)), self.gf) if len(roots) == 0: return None return roots class TestMinisketch(unittest.TestCase): """Test class for Minisketch.""" @classmethod def construct_data(cls, field_size, num_a_only, num_b_only, num_both): """Construct two random lists of elements in [1..2**field_size-1]. Each list will have unique elements that don't appear in the other (num_a_only in the first and num_b_only in the second), and num_both elements will appear in both.""" sample = [] # Simulate random.sample here (which doesn't work with ranges over 2**63). for _ in range(num_a_only + num_b_only + num_both): while True: r = random.randrange(1, 1 << field_size) if r not in sample: sample.append(r) break full_a = sample[:num_a_only + num_both] full_b = sample[num_a_only:] random.shuffle(full_a) random.shuffle(full_b) return full_a, full_b def field_size_capacity_test(self, field_size, capacity): """Test Minisketch methods for a specific field and capacity.""" used_capacity = random.randrange(capacity + 1) num_a = random.randrange(used_capacity + 1) num_both = random.randrange(min(2 * capacity, (1 << field_size) - 1 - used_capacity) + 1) full_a, full_b = self.construct_data(field_size, num_a, used_capacity - num_a, num_both) sketch_a = Minisketch(field_size, capacity) sketch_b = Minisketch(field_size, capacity) for v in full_a: sketch_a.add(v) for v in full_b: sketch_b.add(v) sketch_combined = sketch_a.clone() sketch_b_ser = sketch_b.serialize() sketch_b_received = Minisketch(field_size, capacity) sketch_b_received.deserialize(sketch_b_ser) sketch_combined.merge(sketch_b_received) decode = sketch_combined.decode() self.assertEqual(decode, sorted(set(full_a) ^ set(full_b))) def test(self): """Run tests.""" for field_size in range(2, 65): for capacity in [0, 1, 2, 5, 10, field_size]: self.field_size_capacity_test(field_size, min(capacity, (1 << field_size) - 1)) if __name__ == '__main__': unittest.main()
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/log2_factorial.sage
import bisect INPUT_BITS = 32 TABLE_BITS = 5 INT_BITS = 64 EXACT_FPBITS = 256 F = RealField(100) # overkill def BestOverApproxInvLog2(mulof, maxd): """ Compute denominator of an approximation of 1/log(2). Specifically, find the value of d (<= maxd, and a multiple of mulof) such that ceil(d/log(2))/d is the best approximation of 1/log(2). """ dist=1 best=0 # Precomputed denominators that lead to good approximations of 1/log(2) for d in [1, 2, 9, 70, 131, 192, 445, 1588, 4319, 11369, 18419, 25469, 287209, 836158, 3057423, 8336111, 21950910, 35565709, 49180508, 161156323, 273132138, 385107953, 882191721]: kd = lcm(mulof, d) if kd <= maxd: n = ceil(kd / log(2)) dis = F((n / kd) - 1 / log(2)) if dis < dist: dist = dis best = kd return best LOG2_TABLE = [] A = 0 B = 0 C = 0 D = 0 K = 0 def Setup(k): global LOG2_TABLE, A, B, C, D, K K = k LOG2_TABLE = [] for i in range(2 ** TABLE_BITS): LOG2_TABLE.append(int(floor(F(K * log(1 + i / 2**TABLE_BITS, 2))))) # Maximum for (2*x+1)*LogK2(x) max_T = (2^(INPUT_BITS + 1) - 1) * (INPUT_BITS*K - 1) # Maximum for A max_A = (2^INT_BITS - 1) // max_T D = BestOverApproxInvLog2(2 * K, max_A * 2 * K) A = D // (2 * K) B = int(ceil(F(D/log(2)))) C = int(floor(F(D*log(2*pi,2)/2))) def LogK2(n): assert(n >= 1 and n < (1 << INPUT_BITS)) bits = Integer(n).nbits() return K * (bits - 1) + LOG2_TABLE[((n << (INPUT_BITS - bits)) >> (INPUT_BITS - TABLE_BITS - 1)) - 2**TABLE_BITS] def Log2Fact(n): # Use formula (A*(2*x+1)*LogK2(x) - B*x + C) / D return (A*(2*n+1)*LogK2(n) - B*n + C) // D + (n < 3) RES = [int(F(log(factorial(i),2))) for i in range(EXACT_FPBITS * 10)] best_worst_ratio = 0 for K in range(1, 10000): Setup(K) assert(LogK2(1) == 0) assert(LogK2(2) == K) assert(LogK2(4) == 2 * K) good = True worst_ratio = 1 for i in range(1, EXACT_FPBITS * 10): exact = RES[i] approx = Log2Fact(i) if not (approx <= exact and ((approx == exact) or (approx >= EXACT_FPBITS and exact >= EXACT_FPBITS))): good = False break if worst_ratio * exact > approx: worst_ratio = approx / exact if good and worst_ratio > best_worst_ratio: best_worst_ratio = worst_ratio print("Formula: (%i*(2*x+1)*floor(%i*log2(x)) - %i*x + %i) / %i; log(max_ratio)=%f" % (A, K, B, C, D, RR(-log(worst_ratio)))) print("LOG2K_TABLE: %r" % LOG2_TABLE)
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/math.md
# The mathematics of Minisketch sketches This is an unconventional mathematical overview of the PinSketch algorithm without references to coding theory<sup>[[1]](#myfootnote1)</sup>. ## Set sketches A sketch, for the purpose of this description, can be seen as a "set checksum" with two peculiar properties: * Sketches have a predetermined capacity, and when the number of elements in the set is not higher than the capacity, minisketch will always recover the entire set from the sketch. A sketch of *b*-bit elements with capacity *c* can be stored in *bc* bits. * The sketches of two sets can be combined by adding them (XOR) to obtain a sketch of the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) between the two sets (*i.e.*, all elements that occur in one but not both input sets). This overview explains how sets can be converted into a sketch and how a set can be recovered from a sketch. ## From field elements to sketches **Data entries as field elements** Every integer in the range *[1...2<sup>b</sup>-1]* (the acceptable data elements for a Minisketch sketch with field size *b*) can be mapped to a nonzero field element of *GF(2<sup>b</sup>)*. In this [finite field](https://en.wikipedia.org/wiki/Finite_field), we can add and multiply elements together, with many of the expected properties for those operations. Addition (and subtraction!) of field elements corresponds to bitwise XOR of the integers they correspond to, though multiplication is more involved. **Sets as power series** We define a function *S* which maps field elements *m* to the following [formal power series](https://en.wikipedia.org/wiki/Formal_power_series) (similar to a polynomial, except there can be an infinite number of terms, and we don't care about concepts like convergence as we're never going to actually evaluate it for a specific value of *x*): * *S(m) = 1 + mx + m<sup>2</sup>x<sup>2</sup> + m<sup>3</sup>x<sup>3</sup> + ...*. We then extend this function to operate on sets of field elements, by adding together the images of every set element. If *M = {m<sub>1</sub>, m<sub>2</sub>, ... }*: * *S(M) = S({m<sub>1</sub>,m<sub>2</sub>,...}) = S(m<sub>1</sub>) + S(m<sub>2</sub>) + ... = (1 + 1 + ...) + (m<sub>1</sub> + m<sub>2</sub> + ...)x + (m<sub>1</sub><sup>2</sup> + m<sub>2</sub><sup>2</sup> + ...)x<sup>2</sup> + (m<sub>1</sub><sup>3</sup> + ...* Because in our field addition corresponds to XOR of integers, it holds for every *a* that *a + a = 0*. This carries over to the *S* function, meaning that *S(a) + S(a) = 0* for every *a*. This means that the coefficients of these power series have the second of the properties we desire from a sketch, namely that an efficient operation exists to combine two sketches such that the result is a sketch of the symmetric difference of the sets. It holds that *S({m<sub>1</sub>,m<sub>2</sub>}) + S({m<sub>2</sub>,m<sub>3</sub>}) = S(m<sub>1</sub>) + (S(m<sub>2</sub>) + S(m<sub>2</sub>)) + S(m<sub>3</sub>) = S(m<sub>1</sub>) + S(m<sub>3</sub>) = S({m<sub>1</sub>,m<sub>3</sub>})*. The question is whether we can also efficiently recover the elements from their power series' coefficients. **An infinity of coefficients is hard** To make reasoning about these power series easier, notice that the series for a single element is in fact a [geometric series](https://en.wikipedia.org/wiki/Geometric_series). If we were working over real numbers rather than a finite field and *|mx| < 1*, it would converge to *(1 - mx)<sup>-1</sup>*. Convergence has no meaning in formal power series, however it is still the case that: * *(1 - mx) S(m) = 1* You can verify this by seeing that every coefficient except the constant one gets cancelled out by the multiplication. This can be generalized to the series for multiple set elements. For two elements we have: * *(1 - m<sub>1</sub>x) (1 - m<sub>2</sub>x) S({m<sub>1</sub>,m<sub>2</sub>}) = (1 - m<sub>1</sub>x) (1 - m<sub>2</sub>x) (S(m<sub>1</sub>) + S(m<sub>2</sub>)) = (1 - m<sub>2</sub>x) + (1 - m<sub>1</sub>x)* And for three: * *(1 - m<sub>1</sub>x) (1 - m<sub>2</sub>x) (1 - m<sub>3</sub>x) S({m<sub>1</sub>,m<sub>2</sub>,m<sub>3</sub>}) = (1 - m<sub>1</sub>x) (1 - m<sub>2</sub>x) (1 - m<sub>3</sub>x) (S(m<sub>1</sub>) + S(m<sub>2</sub>) + S(m<sub>3</sub>)) = (1 - m<sub>2</sub>x)(1 - m<sub>3</sub>x) + (1 - m<sub>1</sub>x)(1 - m<sub>3</sub>x) + (1 - m<sub>1</sub>x)(1 - m<sub>2</sub>x)* In each case, we notice that multiplying *S(M)* with *(1 - m<sub>i</sub>x)* for each element *m<sub>i</sub> &isin; M* results in a polynomial of degree *n-1*. **Solving for the set elements** The above insight lets us build a solver that extracts the set elements from the coefficients of a power series. If we can find a polynomial *L* that is the product of *n* different *(1 - m<sub>i</sub>x)* factors for various values of *m<sub>i</sub>*, such that *P = S(M)L* is an *n-1* degree polynomial, then those values *m<sub>i</sub>* are the elements of *M*. The coefficients of *P* are nontrivial expressions of the set elements themselves. However, we can just focus on the coefficients of degree *n* and higher in *P*, as those are all 0. Let *s<sub>i</sub>* be the coefficients of *S(M)*, and *l<sub>i</sub>* the coefficients of L. In other words, *S(M) = s<sub>0</sub> + s<sub>1</sub>x + s<sub>2</sub>x<sup>2</sup> + s<sub>3</sub>x<sup>3</sup> + ...* and *L = l<sub>0</sub> + l<sub>1</sub>x + l<sub>2</sub>x<sup>2</sup> + l<sub>3</sub>x<sup>3</sup> + ... + l<sub>n</sub>x<sup>n</sup>*. Note that *l<sub>0</sub> = 1*, as it is the product of all the *1* terms in the *(1 - m<sub>i</sub>x)* factors. Here are the equations for the coefficients of *S(M)L* of degree *n+1* through *2n*: * *s<sub>n+1</sub> + s<sub>n+0</sub>l<sub>1</sub> + s<sub>n-1</sub>l<sub>2</sub> + s<sub>n-2</sub>l<sub>3</sub> + ... + s<sub>1</sub>l<sub>n</sub> = 0* * *s<sub>n+2</sub> + s<sub>n+1</sub>l<sub>1</sub> + s<sub>n+0</sub>l<sub>2</sub> + s<sub>n-1</sub>l<sub>3</sub> + ... + s<sub>2</sub>l<sub>n</sub> = 0* * *s<sub>n+3</sub> + s<sub>n+2</sub>l<sub>1</sub> + s<sub>n+1</sub>l<sub>2</sub> + s<sub>n+0</sub>l<sub>3</sub> + ... + s<sub>3</sub>l<sub>n</sub> = 0* * ... * *s<sub>2n</sub> + s<sub>2n-1</sub>l<sub>1</sub> + s<sub>2n-2</sub>l<sub>2</sub> + s<sub>2n-3</sub>l<sub>3</sub> + ... + s<sub>n</sub>l<sub>n</sub> = 0* These are *n* linear equations with *n* unknowns (the *l<sub>i<sub>* values, for *i=1..n*), which can be solved using [Gaussian elimination](https://en.wikipedia.org/wiki/Gaussian_elimination). After doing so, we have the coefficients of *L*, which can then be [factored](https://en.wikipedia.org/wiki/Factorization_of_polynomials_over_finite_fields) into first degree factors of the form *(1 - m<sub>i</sub>x)*. The resulting *m* values are our set elements. **Putting it all together** Interestingly, only *2n* coefficients of *S(M)* were needed for solving the set of equations above. This means we have our answer: the coefficients *1* through *2n* of *S(M)*, or the list *[m<sub>1</sub> + m<sub>2</sub> + ..., m<sub>1</sub><sup>2</sup> + m<sub>2</sub><sup>2</sup> + ..., ..., m<sub>1</sub><sup>2n</sup> + m<sub>2</sub><sup>2n</sup> + ...]* functions as a sketch, satisfying the two properties we want: * Sketches can be combined to form the sketch of their symmetric difference, by simply pairwise adding the list elements together. * With *2n* list elements we can efficiently recover *n* elements from a sketch. **Capacity and difference** The approach above only works when the number of elements *n* in the sketch is known. Of course we want to support cases where only an upper bound on the number of elements in the sketch is known, the capacity *c*. Given that we can reconstruct a set of size *c* from a sketch with *2c* terms, we should be able to reconstruct a set of size *n* too as long as *n &le; c*. This is simply a matter of trying to solve the above set of equations assuming values of *n* that count down from *c* until a solution is found for one. This is known as the [Peterson-Gorenstein-Zierler algorithm](https://en.wikipedia.org/wiki/BCH_code#Peterson%E2%80%93Gorenstein%E2%80%93Zierler_algorithm). ## Optimizations **Halving the sketch size** We can in fact only include the odd terms in the sketch, and reconstruct the even ones before solving the equation to find *L*. This means the size of a sketch becomes just *c* field elements, the same size as would be needed to send its contents naively. To see how this is possible, we need the [Frobenius endomorphism](https://en.wikipedia.org/wiki/Frobenius_endomorphism), which in short states that in fields where *x + x = 0* it holds that *(x + y)<sup>2</sup> = x<sup>2</sup> + y<sup>2</sup>* for every *x* and *y* (the dream of every high school math student!). This means that: * *s<sub>2</sub> = m<sub>1</sub><sup>2</sup> + m<sub>2</sub><sup>2</sup> + ... = (m<sub>1</sub> + m<sub>2</sub> + ...)<sup>2</sup> = s<sub>1</sub><sup>2</sup>*. * *s<sub>4</sub> = m<sub>1</sub><sup>4</sup> + m<sub>2</sub><sup>4</sup> + ... = (m<sub>1</sub><sup>2</sup> + m<sub>2</sub><sup>2</sup> + ...)<sup>2</sup> = s<sub>2</sub><sup>2</sup>*. * *s<sub>6</sub> = m<sub>1</sub><sup>6</sup> + m<sub>2</sub><sup>6</sup> + ... = (m<sub>1</sub><sup>3</sup> + m<sub>2</sub><sup>3</sup> + ...)<sup>2</sup> = s<sub>3</sub><sup>2</sup>*. * ... In other words, we only need to send *s<sub>1</sub>, s<sub>3</sub>, s<sub>5</sub>, ..., s<sub>2n-1</sub>* to recover all *2n* *s<sub>i</sub>* values, and proceed with reconstruction. **Quadratic performance rather than cubic** Using Gaussian elimination to solve the set of equations above for the *l<sub>i</sub>* values requires *O(n<sup>3</sup>)* field operations. However, due to the special structure in the equations (look at the repeated *s<sub>i</sub>* values), it can be solved in *O(n<sup>2</sup>)* time using a number of techniques, including the [Berlekamp-Massey algorithm](https://en.wikipedia.org/wiki/Berlekamp%E2%80%93Massey_algorithm) (BM). **Roots instead of factorization** As explained above, the polynomial *L* can be factored into *(1 - m<sub>i</sub>x)* factors, where the values *m<sub>i</sub>* are the set elements. However, since we know that a decodable sketch must result in a polynomial that is fully factorizable into degree-*1* factors, we can instead use a more efficient root-finding algorithm rather than a factorization algorithm. As the root of each *(1 - m<sub>i</sub>x)* factor is *m<sub>i</sub><sup>-1</sup>*, we conclude that the set elements are in fact the inverses of the roots of *L*. **Avoiding inversions** As inversions are a relatively expensive operation, it would be useful to avoid them. Say that we're trying to find the inverses of the roots of *L = 1 + l<sub>1</sub>x + l<sub>2</sub>x<sup>2</sup> + ... + l<sub>n</sub>x<sup>n</sup>*, then we're really interested in the solutions *y* for *1 + l<sub>1</sub>y<sup>-1</sup> + l<sub>2</sub>y<sup>-2</sup> + ... + l<sub>n</sub>y<sup>-n</sup> = 0*. By multiplying both sides in the equations with *y<sup>n</sup>*, we find *l<sub>n</sub> + l<sub>n-1</sub>y + l<sub>n-2</sub>y<sup>2</sup> + ... + y<sup>n</sup> = 0*. In other words, we can find the inverses of the roots of *L* by instead factoring the polynomial with the coefficients of *L* in reverse order. * <a name="myfootnote1">[1]</a> For those familiar with coding theory: PinSketch communicates a set difference by encoding the set members as errors in a binary [BCH](https://en.wikipedia.org/wiki/BCH_code) codeword 2<sup>bits</sup> in size and sends the syndromes. The linearity of the syndromes provides all the properties needed for a sketch. Sketch decoding is simply finding the error locations. Decode is much faster than an ordinary BCH decoder for such a large codeword because the need to take a discrete log is avoided by storing the set in the roots directly instead of in an exponent (logically permuting the bits of the codeword).
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/gen_basefpbits.sage
# Require exact values up to FPBITS = 256 # Overkill accuracy F = RealField(400) def BaseFPBits(bits, capacity): return bits * capacity - int(ceil(F(log(sum(binomial(2**bits - 1, i) for i in range(capacity+1)), 2)))) def Log2Factorial(capacity): return int(floor(log(factorial(capacity), 2))) print("uint64_t BaseFPBits(uint32_t bits, uint32_t capacity) {") print(" // Correction table for low bits/capacities") TBLS={} FARS={} SKIPS={} for bits in range(1, 32): TBL = [] for capacity in range(1, min(2**bits, FPBITS)): exact = BaseFPBits(bits, capacity) approx = Log2Factorial(capacity) TBL.append((exact, approx)) MIN = 10000000000 while len(TBL) and ((TBL[-1][0] == TBL[-1][1]) or (TBL[-1][0] >= FPBITS and TBL[-1][1] >= FPBITS)): MIN = min(MIN, TBL[-1][0] - TBL[-1][1]) TBL.pop() while len(TBL) and (TBL[-1][0] - TBL[-1][1] == MIN): TBL.pop() SKIP = 0 while SKIP < len(TBL) and TBL[SKIP][0] == TBL[SKIP][1]: SKIP += 1 DIFFS = [TBL[i][0] - TBL[i][1] for i in range(SKIP, len(TBL))] if len(DIFFS) > 0 and len(DIFFS) * Integer(max(DIFFS)).nbits() > 64: print(" static constexpr uint8_t ADD%i[] = {%s};" % (bits, ", ".join(("%i" % (TBL[i][0] - TBL[i][1])) for i in range(SKIP, len(TBL))))) TBLS[bits] = DIFFS FARS[bits] = MIN SKIPS[bits] = SKIP print("") print(" if (capacity == 0) return 0;") print(" uint64_t ret = 0;") print(" if (bits < 32 && capacity >= (1U << bits)) {") print(" ret = uint64_t{bits} * (capacity - (1U << bits) + 1);") print(" capacity = (1U << bits) - 1;") print(" }") print(" ret += Log2Factorial(capacity);") print(" switch (bits) {") for bits in sorted(TBLS.keys()): if len(TBLS[bits]) == 0: continue width = Integer(max(TBLS[bits])).nbits() if len(TBLS[bits]) == 1: add = "%i" % TBLS[bits][0] elif len(TBLS[bits]) * width <= 64: code = sum((2**(width*i) * TBLS[bits][i]) for i in range(len(TBLS[bits]))) if width == 1: add = "(0x%x >> (capacity - %i)) & 1" % (code, 1 + SKIPS[bits]) else: add = "(0x%x >> %i * (capacity - %i)) & %i" % (code, width, 1 + SKIPS[bits], 2**width - 1) else: add = "ADD%i[capacity - %i]" % (bits, 1 + SKIPS[bits]) if len(TBLS[bits]) + SKIPS[bits] == 2**bits - 1: print(" case %i: return ret + (capacity <= %i ? 0 : %s);" % (bits, SKIPS[bits], add)) else: print(" case %i: return ret + (capacity <= %i ? 0 : capacity > %i ? %i : %s);" % (bits, SKIPS[bits], len(TBLS[bits]) + SKIPS[bits], FARS[bits], add)) print(" default: return ret;") print(" }") print("}") print("void TestBaseFPBits() {") print(" static constexpr uint16_t TBL[20][100] = {%s};" % (", ".join("{" + ", ".join(("%i" % BaseFPBits(bits, capacity)) for capacity in range(0, 100)) + "}" for bits in range(1, 21)))) print(" for (int bits = 1; bits <= 20; ++bits) {") print(" for (int capacity = 0; capacity < 100; ++capacity) {") print(" uint64_t computed = BaseFPBits(bits, capacity), exact = TBL[bits - 1][capacity];") print(" CHECK(exact == computed || (exact >= 256 && computed >= 256));") print(" }") print(" }") print("}")
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/example.c
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #include <stdio.h> #include <assert.h> #include "../include/minisketch.h" int main(void) { minisketch *sketch_a = minisketch_create(12, 0, 4); for (int i = 3000; i < 3010; ++i) { minisketch_add_uint64(sketch_a, i); } size_t sersize = minisketch_serialized_size(sketch_a); assert(sersize == 12 * 4 / 8); // 4 12-bit values is 6 bytes. unsigned char *buffer_a = malloc(sersize); minisketch_serialize(sketch_a, buffer_a); minisketch_destroy(sketch_a); minisketch *sketch_b = minisketch_create(12, 0, 4); // Bob's own sketch for (int i = 3002; i < 3012; ++i) { minisketch_add_uint64(sketch_b, i); } sketch_a = minisketch_create(12, 0, 4); // Alice's sketch minisketch_deserialize(sketch_a, buffer_a); // Load Alice's sketch free(buffer_a); // Merge the elements from sketch_a into sketch_b. The result is a sketch_b // which contains all elements that occurred in Alice's or Bob's sets, but not // in both. minisketch_merge(sketch_b, sketch_a); uint64_t differences[4]; ssize_t num_differences = minisketch_decode(sketch_b, 4, differences); minisketch_destroy(sketch_a); minisketch_destroy(sketch_b); if (num_differences < 0) { printf("More than 4 differences!\n"); } else { ssize_t i; for (i = 0; i < num_differences; ++i) { printf("%u is in only one of the two sets\n", (unsigned)differences[i]); } } }
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/gen_params.sage
#!/usr/bin/env sage r""" Generate finite field parameters for minisketch. This script selects the finite fields used by minisketch for various sizes and generates the required tables for the implementation. The output (after formatting) can be found in src/fields/*.cpp. """ B.<b> = GF(2) P.<p> = B[] def apply_map(m, v): r = 0 i = 0 while v != 0: if (v & 1): r ^^= m[i] i += 1 v >>= 1 return r def recurse_moduli(acc, maxweight, maxdegree): for pos in range(maxweight, maxdegree + 1, 1): poly = acc + p^pos if maxweight == 1: if poly.is_irreducible(): return (pos, poly) else: (deg, ret) = recurse_moduli(poly, maxweight - 1, pos - 1) if ret is not None: return (pos, ret) return (None, None) def compute_moduli(bits): # Return all optimal irreducible polynomials for GF(2^bits) # The result is a list of tuples (weight, degree of second-highest nonzero coefficient, polynomial) maxdegree = bits - 1 result = [] for weight in range(1, bits, 2): deg, res = None, None while True: ret = recurse_moduli(p^bits + 1, weight, maxdegree) if ret[0] is not None: (deg, res) = ret maxdegree = deg - 1 else: break if res is not None: result.append((weight + 2, deg, res)) return result def bits_to_int(vals): ret = 0 base = 1 for val in vals: ret += Integer(val) * base base *= 2 return ret def sqr_table(f, bits, n=1): ret = [] for i in range(bits): ret.append((f^(2^n*i)).integer_representation()) return ret # Compute x**(2**n) def pow2(x, n): for i in range(n): x = x**2 return x def qrt_table(F, f, bits): # Table for solving x2 + x = a # This implements the technique from https://www.raco.cat/index.php/PublicacionsMatematiques/article/viewFile/37927/40412, Lemma 1 for i in range(bits): if (f**i).trace() != 0: u = f**i ret = [] for i in range(0, bits): d = f^i y = sum(pow2(d, j) * sum(pow2(u, k) for k in range(j)) for j in range(1, bits)) ret.append(y.integer_representation() ^^ (y.integer_representation() & 1)) return ret def conv_tables(F, NF, bits): # Generate a F(2) linear projection that maps elements from one field # to an isomorphic field with a different modulus. f = F.gen() fp = f.minimal_polynomial() assert(fp == F.modulus()) nfp = fp.change_ring(NF) nf = sorted(nfp.roots(multiplicities=False))[0] ret = [] matrepr = [[B(0) for x in range(bits)] for y in range(bits)] for i in range(bits): val = (nf**i).integer_representation() ret.append(val) for j in range(bits): matrepr[j][i] = B((val >> j) & 1) mat = Matrix(matrepr).inverse().transpose() ret2 = [] for i in range(bits): ret2.append(bits_to_int(mat[i])) for t in range(100): f1a = F.random_element() f1b = F.random_element() f1r = f1a * f1b f2a = NF.fetch_int(apply_map(ret, f1a.integer_representation())) f2b = NF.fetch_int(apply_map(ret, f1b.integer_representation())) f2r = NF.fetch_int(apply_map(ret, f1r.integer_representation())) f2s = f2a * f2b assert(f2r == f2s) for t in range(100): f2a = NF.random_element() f2b = NF.random_element() f2r = f2a * f2b f1a = F.fetch_int(apply_map(ret2, f2a.integer_representation())) f1b = F.fetch_int(apply_map(ret2, f2b.integer_representation())) f1r = F.fetch_int(apply_map(ret2, f2r.integer_representation())) f1s = f1a * f1b assert(f1r == f1s) return (ret, ret2) def fmt(i,typ): if i == 0: return "0" else: return "0x%x" % i def lintranstype(typ, bits, maxtbl): gsize = min(maxtbl, bits) array_size = (bits + gsize - 1) // gsize bits_list = [] total = 0 for i in range(array_size): rsize = (bits - total + array_size - i - 1) // (array_size - i) total += rsize bits_list.append(rsize) return "RecLinTrans<%s, %s>" % (typ, ", ".join("%i" % x for x in bits_list)) INT=0 CLMUL=1 CLMUL_TRI=2 MD=3 def print_modulus_md(mod): ret = "" pos = mod.degree() for c in reversed(list(mod)): if c: if ret: ret += " + " if pos == 0: ret += "1" elif pos == 1: ret += "x" else: ret += "x<sup>%i</sup>" % pos pos -= 1 return ret def pick_modulus(bits, style): # Choose the lexicographicly-first lowest-weight modulus # optionally subject to implementation specific constraints. moduli = compute_moduli(bits) if style == INT or style == MD: multi_sqr = False need_trans = False elif style == CLMUL: # Fast CLMUL reduction requires that bits + the highest # set bit are less than 66. moduli = list(filter((lambda x: bits+x[1] <= 66), moduli)) + moduli multi_sqr = True need_trans = True if not moduli or moduli[0][2].change_ring(ZZ)(2) == 3 + 2**bits: # For modulus 3, CLMUL_TRI is obviously better. return None elif style == CLMUL_TRI: moduli = list(filter(lambda x: bits+x[1] <= 66, moduli)) + moduli moduli = list(filter(lambda x: x[0] == 3, moduli)) multi_sqr = True need_trans = True else: assert(False) if not moduli: return None return moduli[0][2] def print_result(bits, style): if style == INT: multi_sqr = False need_trans = False table_id = "%i" % bits elif style == MD: pass elif style == CLMUL: multi_sqr = True need_trans = True table_id = "%i" % bits elif style == CLMUL_TRI: multi_sqr = True need_trans = True table_id = "TRI%i" % bits else: assert(False) nmodulus = pick_modulus(bits, INT) modulus = pick_modulus(bits, style) if modulus is None: return if style == MD: print("* *%s*" % print_modulus_md(modulus)) return if bits > 32: typ = "uint64_t" elif bits > 16: typ = "uint32_t" elif bits > 8: typ = "uint16_t" else: typ = "uint8_t" ttyp = lintranstype(typ, bits, 4) rtyp = lintranstype(typ, bits, 6) F.<f> = GF(2**bits, modulus=modulus) include_table = True if style != INT and style != CLMUL: cmodulus = pick_modulus(bits, CLMUL) if cmodulus == modulus: include_table = False table_id = "%i" % bits if include_table: print("typedef %s StatTable%s;" % (rtyp, table_id)) rtyp = "StatTable%s" % table_id if (style == INT): print("typedef %s DynTable%s;" % (ttyp, table_id)) ttyp = "DynTable%s" % table_id if need_trans: if modulus != nmodulus: # If the bitstream modulus is not the best modulus for # this implementation a conversion table will be needed. ctyp = rtyp NF.<nf> = GF(2**bits, modulus=nmodulus) ctables = conv_tables(NF, F, bits) loadtbl = "&LOAD_TABLE_%s" % table_id savetbl = "&SAVE_TABLE_%s" % table_id if include_table: print("constexpr %s LOAD_TABLE_%s({%s});" % (ctyp, table_id, ", ".join([fmt(x,typ) for x in ctables[0]]))) print("constexpr %s SAVE_TABLE_%s({%s});" % (ctyp, table_id, ", ".join([fmt(x,typ) for x in ctables[1]]))) else: ctyp = "IdTrans" loadtbl = "&ID_TRANS" savetbl = "&ID_TRANS" else: assert(modulus == nmodulus) if include_table: print("constexpr %s SQR_TABLE_%s({%s});" % (rtyp, table_id, ", ".join([fmt(x,typ) for x in sqr_table(f, bits, 1)]))) if multi_sqr: # Repeated squaring is a linearised polynomial so in F(2^n) it is # F(2) linear and can be computed by a simple bit-matrix. # Repeated squaring is especially useful in powering ladders such as # for inversion. # When certain repeated squaring tables are not in use, use the QRT # table instead to make the C++ compiler happy (it always has the # same type). sqr2 = "&QRT_TABLE_%s" % table_id sqr4 = "&QRT_TABLE_%s" % table_id sqr8 = "&QRT_TABLE_%s" % table_id sqr16 = "&QRT_TABLE_%s" % table_id if ((bits - 1) >= 4): if include_table: print("constexpr %s SQR2_TABLE_%s({%s});" % (rtyp, table_id, ", ".join([fmt(x,typ) for x in sqr_table(f, bits, 2)]))) sqr2 = "&SQR2_TABLE_%s" % table_id if ((bits - 1) >= 8): if include_table: print("constexpr %s SQR4_TABLE_%s({%s});" % (rtyp, table_id, ", ".join([fmt(x,typ) for x in sqr_table(f, bits, 4)]))) sqr4 = "&SQR4_TABLE_%s" % table_id if ((bits - 1) >= 16): if include_table: print("constexpr %s SQR8_TABLE_%s({%s});" % (rtyp, table_id, ", ".join([fmt(x,typ) for x in sqr_table(f, bits, 8)]))) sqr8 = "&SQR8_TABLE_%s" % table_id if ((bits - 1) >= 32): if include_table: print("constexpr %s SQR16_TABLE_%s({%s});" % (rtyp, table_id, ", ".join([fmt(x,typ) for x in sqr_table(f, bits, 16)]))) sqr16 = "&SQR16_TABLE_%s" % table_id if include_table: print("constexpr %s QRT_TABLE_%s({%s});" % (rtyp, table_id, ", ".join([fmt(x,typ) for x in qrt_table(F, f, bits)]))) modulus_weight = modulus.hamming_weight() modulus_degree = (modulus - p**bits).degree() modulus_int = (modulus - p**bits).change_ring(ZZ)(2) lfsr = "" if style == INT: print("typedef Field<%s, %i, %i, %s, %s, &SQR_TABLE_%s, &QRT_TABLE_%s%s> Field%i;" % (typ, bits, modulus_int, rtyp, ttyp, table_id, table_id, lfsr, bits)) elif style == CLMUL: print("typedef Field<%s, %i, %i, %s, &SQR_TABLE_%s, %s, %s, %s, %s, &QRT_TABLE_%s, %s, %s, %s%s> Field%i;" % (typ, bits, modulus_int, rtyp, table_id, sqr2, sqr4, sqr8, sqr16, table_id, ctyp, loadtbl, savetbl, lfsr, bits)) elif style == CLMUL_TRI: print("typedef FieldTri<%s, %i, %i, %s, &SQR_TABLE_%s, %s, %s, %s, %s, &QRT_TABLE_%s, %s, %s, %s> FieldTri%i;" % (typ, bits, modulus_degree, rtyp, table_id, sqr2, sqr4, sqr8, sqr16, table_id, ctyp, loadtbl, savetbl, bits)) else: assert(False) for bits in range(2, 65): print("#ifdef ENABLE_FIELD_INT_%i" % bits) print("// %i bit field" % bits) print_result(bits, INT) print("#endif") print("") for bits in range(2, 65): print("#ifdef ENABLE_FIELD_INT_%i" % bits) print("// %i bit field" % bits) print_result(bits, CLMUL) print_result(bits, CLMUL_TRI) print("#endif") print("") for bits in range(2, 65): print_result(bits, MD)
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/protocoltips.md
# Tips for designing protocols using `libminisketch` Sending a sketch is less efficient than just sending your whole set with efficient entropy coding if the number of differences is larger than *log<sub>2</sub>( 2<sup>b</sup> choose set_size ) / b*. In most applications your set can be hashed to entries just large enough to make the probability of collision negligible. This can be a considerable speedup and bandwidth savings. Short hashes (<128 bits) should be salted with an unpredictable value to prevent malicious inputs from intentionally causing collisions. Salting also allows an entry missed due to a collision to be reconciled on a later run with a different salt. Pre-hashing may not be possible in some applications, such as where there is only one-way communication, where the confidentiality of entry origin matters, or where security depends on the total absence of collisions. Some element sizes are faster to decode than others; see the benchmarks in the readme. Almost all the computational burden of reconciliation is in minisketch_decode(). Denial-of-service attacks can be mitigated by arranging protocol flow so that a party requests a sketch and decodes it rather than a construction where the participants will decode unsolicited sketches. Decode times can be constrained by limiting sketch capacity or via the max_count argument to minisketch_decode(). In most cases you don't actually know the size of the set difference in advance, but often you know a lower bound on it (the difference in set sizes). * There are difference size estimation techniques such as min-wise hashing<sup>[[1]](#myfootnote1)</sup> or random projections<sup>[[2]](#myfootnote2)</sup>, but complex estimators can end up using more bandwidth than they save. * It may be useful to always overestimate the sketch size needed to amortize communications overheads (*e.g.* packet headers, round trip delays). * If the total data sent would end up leaving you better off having just sent the whole set, per above, then you can send the set in response to a failure but leave out as many elements as the size of the previously sent sketch. The receiver can decode the partial set and use the data they already have to complete it, reducing bandwidth waste. * Additional elements can be sent for a sketch as few as one at a time with little decode cost until enough data is received to decode. This is most easily implemented by always computing the largest sketch size and sending it incrementally as needed. * Because sketches are linear you can adaptively subdivide to decode an overfull set. The sender uses a hash function to select approximately half their set members and sends a sketch of those members. The receiver can do the same and combine the result with the initially sent sketch to get two sketches with roughly half the number of members and attempt to decode them. Repeat recursively on failure. This adaptive subdivision procedure makes decode time essentially linear at the cost of communications inefficiency. Minisketches can also be used as the cells in an IBLT for similar reasons. Less efficient reconciliation techniques like IBLT or adaptive subdivision, or overheads like complex estimators effectively lower the threshold where sending the whole set efficiently would use less bandwidth. When the number of differences is more than 2<sup>b/2-1</sup> an alternative sketch encoding is possible that is somewhat smaller, but requires a table of size 2<sup>b</sup>; contact the authors if you have an application where that might be useful. ## References * <a name="myfootnote1">[1]</a> Broder, A. *On the Resemblance and Containment of Documents* Proceedings of the Compression and Complexity of Sequences 1997 [[PDF]](https://www.cs.princeton.edu/courses/archive/spring13/cos598C/broder97resemblance.pdf) * <a name="myfootnote2">[2]</a> Feigenbaum, Joan and Kannan, Sampath and Strauss, Martin J. and Viswanathan, Mahesh. *An Approximate L1-Difference Algorithm for Massive Data Streams* SIAM J. Comput. 2003 [[PDF]](http://www.cs.yale.edu/homes/jf/FKSV1.pdf)
0
bitcoin/src/minisketch
bitcoin/src/minisketch/doc/moduli.md
These are the irreducible polynomials over *GF(2)* used to represent field elements: * *x<sup>2</sup> + x + 1* * *x<sup>3</sup> + x + 1* * *x<sup>4</sup> + x + 1* * *x<sup>5</sup> + x<sup>2</sup> + 1* * *x<sup>6</sup> + x + 1* * *x<sup>7</sup> + x + 1* * *x<sup>8</sup> + x<sup>4</sup> + x<sup>3</sup> + x + 1* * *x<sup>9</sup> + x + 1* * *x<sup>10</sup> + x<sup>3</sup> + 1* * *x<sup>11</sup> + x<sup>2</sup> + 1* * *x<sup>12</sup> + x<sup>3</sup> + 1* * *x<sup>13</sup> + x<sup>4</sup> + x<sup>3</sup> + x + 1* * *x<sup>14</sup> + x<sup>5</sup> + 1* * *x<sup>15</sup> + x + 1* * *x<sup>16</sup> + x<sup>5</sup> + x<sup>3</sup> + x + 1* * *x<sup>17</sup> + x<sup>3</sup> + 1* * *x<sup>18</sup> + x<sup>3</sup> + 1* * *x<sup>19</sup> + x<sup>5</sup> + x<sup>2</sup> + x + 1* * *x<sup>20</sup> + x<sup>3</sup> + 1* * *x<sup>21</sup> + x<sup>2</sup> + 1* * *x<sup>22</sup> + x + 1* * *x<sup>23</sup> + x<sup>5</sup> + 1* * *x<sup>24</sup> + x<sup>4</sup> + x<sup>3</sup> + x + 1* * *x<sup>25</sup> + x<sup>3</sup> + 1* * *x<sup>26</sup> + x<sup>4</sup> + x<sup>3</sup> + x + 1* * *x<sup>27</sup> + x<sup>5</sup> + x<sup>2</sup> + x + 1* * *x<sup>28</sup> + x + 1* * *x<sup>29</sup> + x<sup>2</sup> + 1* * *x<sup>30</sup> + x + 1* * *x<sup>31</sup> + x<sup>3</sup> + 1* * *x<sup>32</sup> + x<sup>7</sup> + x<sup>3</sup> + x<sup>2</sup> + 1* * *x<sup>33</sup> + x<sup>10</sup> + 1* * *x<sup>34</sup> + x<sup>7</sup> + 1* * *x<sup>35</sup> + x<sup>2</sup> + 1* * *x<sup>36</sup> + x<sup>9</sup> + 1* * *x<sup>37</sup> + x<sup>6</sup> + x<sup>4</sup> + x + 1* * *x<sup>38</sup> + x<sup>6</sup> + x<sup>5</sup> + x + 1* * *x<sup>39</sup> + x<sup>4</sup> + 1* * *x<sup>40</sup> + x<sup>5</sup> + x<sup>4</sup> + x<sup>3</sup> + 1* * *x<sup>41</sup> + x<sup>3</sup> + 1* * *x<sup>42</sup> + x<sup>7</sup> + 1* * *x<sup>43</sup> + x<sup>6</sup> + x<sup>4</sup> + x<sup>3</sup> + 1* * *x<sup>44</sup> + x<sup>5</sup> + 1* * *x<sup>45</sup> + x<sup>4</sup> + x<sup>3</sup> + x + 1* * *x<sup>46</sup> + x + 1* * *x<sup>47</sup> + x<sup>5</sup> + 1* * *x<sup>48</sup> + x<sup>5</sup> + x<sup>3</sup> + x<sup>2</sup> + 1* * *x<sup>49</sup> + x<sup>9</sup> + 1* * *x<sup>50</sup> + x<sup>4</sup> + x<sup>3</sup> + x<sup>2</sup> + 1* * *x<sup>51</sup> + x<sup>6</sup> + x<sup>3</sup> + x + 1* * *x<sup>52</sup> + x<sup>3</sup> + 1* * *x<sup>53</sup> + x<sup>6</sup> + x<sup>2</sup> + x + 1* * *x<sup>54</sup> + x<sup>9</sup> + 1* * *x<sup>55</sup> + x<sup>7</sup> + 1* * *x<sup>56</sup> + x<sup>7</sup> + x<sup>4</sup> + x<sup>2</sup> + 1* * *x<sup>57</sup> + x<sup>4</sup> + 1* * *x<sup>58</sup> + x<sup>19</sup> + 1* * *x<sup>59</sup> + x<sup>7</sup> + x<sup>4</sup> + x<sup>2</sup> + 1* * *x<sup>60</sup> + x + 1* * *x<sup>61</sup> + x<sup>5</sup> + x<sup>2</sup> + x + 1* * *x<sup>62</sup> + x<sup>29</sup> + 1* * *x<sup>63</sup> + x + 1* * *x<sup>64</sup> + x<sup>4</sup> + x<sup>3</sup> + x + 1*
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/minisketch.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #include <new> #define MINISKETCH_BUILD #ifdef _MINISKETCH_H_ # error "minisketch.h cannot be included before minisketch.cpp" #endif #include "../include/minisketch.h" #include "false_positives.h" #include "fielddefines.h" #include "sketch.h" #ifdef HAVE_CLMUL # ifdef _MSC_VER # include <intrin.h> # else # include <cpuid.h> # endif #endif Sketch* ConstructGeneric1Byte(int bits, int implementation); Sketch* ConstructGeneric2Bytes(int bits, int implementation); Sketch* ConstructGeneric3Bytes(int bits, int implementation); Sketch* ConstructGeneric4Bytes(int bits, int implementation); Sketch* ConstructGeneric5Bytes(int bits, int implementation); Sketch* ConstructGeneric6Bytes(int bits, int implementation); Sketch* ConstructGeneric7Bytes(int bits, int implementation); Sketch* ConstructGeneric8Bytes(int bits, int implementation); #ifdef HAVE_CLMUL Sketch* ConstructClMul1Byte(int bits, int implementation); Sketch* ConstructClMul2Bytes(int bits, int implementation); Sketch* ConstructClMul3Bytes(int bits, int implementation); Sketch* ConstructClMul4Bytes(int bits, int implementation); Sketch* ConstructClMul5Bytes(int bits, int implementation); Sketch* ConstructClMul6Bytes(int bits, int implementation); Sketch* ConstructClMul7Bytes(int bits, int implementation); Sketch* ConstructClMul8Bytes(int bits, int implementation); Sketch* ConstructClMulTri1Byte(int bits, int implementation); Sketch* ConstructClMulTri2Bytes(int bits, int implementation); Sketch* ConstructClMulTri3Bytes(int bits, int implementation); Sketch* ConstructClMulTri4Bytes(int bits, int implementation); Sketch* ConstructClMulTri5Bytes(int bits, int implementation); Sketch* ConstructClMulTri6Bytes(int bits, int implementation); Sketch* ConstructClMulTri7Bytes(int bits, int implementation); Sketch* ConstructClMulTri8Bytes(int bits, int implementation); #endif namespace { enum class FieldImpl { GENERIC = 0, #ifdef HAVE_CLMUL CLMUL, CLMUL_TRI, #endif }; #ifdef HAVE_CLMUL static inline bool EnableClmul() { #ifdef _MSC_VER int regs[4]; __cpuid(regs, 1); return (regs[2] & 0x2); #else uint32_t eax, ebx, ecx, edx; return (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx & 0x2)); #endif } #endif Sketch* Construct(int bits, int impl) { switch (FieldImpl(impl)) { case FieldImpl::GENERIC: switch ((bits + 7) / 8) { case 1: return ConstructGeneric1Byte(bits, impl); case 2: return ConstructGeneric2Bytes(bits, impl); case 3: return ConstructGeneric3Bytes(bits, impl); case 4: return ConstructGeneric4Bytes(bits, impl); case 5: return ConstructGeneric5Bytes(bits, impl); case 6: return ConstructGeneric6Bytes(bits, impl); case 7: return ConstructGeneric7Bytes(bits, impl); case 8: return ConstructGeneric8Bytes(bits, impl); default: return nullptr; } break; #ifdef HAVE_CLMUL case FieldImpl::CLMUL: if (EnableClmul()) { switch ((bits + 7) / 8) { case 1: return ConstructClMul1Byte(bits, impl); case 2: return ConstructClMul2Bytes(bits, impl); case 3: return ConstructClMul3Bytes(bits, impl); case 4: return ConstructClMul4Bytes(bits, impl); case 5: return ConstructClMul5Bytes(bits, impl); case 6: return ConstructClMul6Bytes(bits, impl); case 7: return ConstructClMul7Bytes(bits, impl); case 8: return ConstructClMul8Bytes(bits, impl); default: return nullptr; } } break; case FieldImpl::CLMUL_TRI: if (EnableClmul()) { switch ((bits + 7) / 8) { case 1: return ConstructClMulTri1Byte(bits, impl); case 2: return ConstructClMulTri2Bytes(bits, impl); case 3: return ConstructClMulTri3Bytes(bits, impl); case 4: return ConstructClMulTri4Bytes(bits, impl); case 5: return ConstructClMulTri5Bytes(bits, impl); case 6: return ConstructClMulTri6Bytes(bits, impl); case 7: return ConstructClMulTri7Bytes(bits, impl); case 8: return ConstructClMulTri8Bytes(bits, impl); default: return nullptr; } } break; #endif } return nullptr; } } extern "C" { int minisketch_bits_supported(uint32_t bits) { #ifdef ENABLE_FIELD_INT_2 if (bits == 2) return true; #endif #ifdef ENABLE_FIELD_INT_3 if (bits == 3) return true; #endif #ifdef ENABLE_FIELD_INT_4 if (bits == 4) return true; #endif #ifdef ENABLE_FIELD_INT_5 if (bits == 5) return true; #endif #ifdef ENABLE_FIELD_INT_6 if (bits == 6) return true; #endif #ifdef ENABLE_FIELD_INT_7 if (bits == 7) return true; #endif #ifdef ENABLE_FIELD_INT_8 if (bits == 8) return true; #endif #ifdef ENABLE_FIELD_INT_9 if (bits == 9) return true; #endif #ifdef ENABLE_FIELD_INT_10 if (bits == 10) return true; #endif #ifdef ENABLE_FIELD_INT_11 if (bits == 11) return true; #endif #ifdef ENABLE_FIELD_INT_12 if (bits == 12) return true; #endif #ifdef ENABLE_FIELD_INT_13 if (bits == 13) return true; #endif #ifdef ENABLE_FIELD_INT_14 if (bits == 14) return true; #endif #ifdef ENABLE_FIELD_INT_15 if (bits == 15) return true; #endif #ifdef ENABLE_FIELD_INT_16 if (bits == 16) return true; #endif #ifdef ENABLE_FIELD_INT_17 if (bits == 17) return true; #endif #ifdef ENABLE_FIELD_INT_18 if (bits == 18) return true; #endif #ifdef ENABLE_FIELD_INT_19 if (bits == 19) return true; #endif #ifdef ENABLE_FIELD_INT_20 if (bits == 20) return true; #endif #ifdef ENABLE_FIELD_INT_21 if (bits == 21) return true; #endif #ifdef ENABLE_FIELD_INT_22 if (bits == 22) return true; #endif #ifdef ENABLE_FIELD_INT_23 if (bits == 23) return true; #endif #ifdef ENABLE_FIELD_INT_24 if (bits == 24) return true; #endif #ifdef ENABLE_FIELD_INT_25 if (bits == 25) return true; #endif #ifdef ENABLE_FIELD_INT_26 if (bits == 26) return true; #endif #ifdef ENABLE_FIELD_INT_27 if (bits == 27) return true; #endif #ifdef ENABLE_FIELD_INT_28 if (bits == 28) return true; #endif #ifdef ENABLE_FIELD_INT_29 if (bits == 29) return true; #endif #ifdef ENABLE_FIELD_INT_30 if (bits == 30) return true; #endif #ifdef ENABLE_FIELD_INT_31 if (bits == 31) return true; #endif #ifdef ENABLE_FIELD_INT_32 if (bits == 32) return true; #endif #ifdef ENABLE_FIELD_INT_33 if (bits == 33) return true; #endif #ifdef ENABLE_FIELD_INT_34 if (bits == 34) return true; #endif #ifdef ENABLE_FIELD_INT_35 if (bits == 35) return true; #endif #ifdef ENABLE_FIELD_INT_36 if (bits == 36) return true; #endif #ifdef ENABLE_FIELD_INT_37 if (bits == 37) return true; #endif #ifdef ENABLE_FIELD_INT_38 if (bits == 38) return true; #endif #ifdef ENABLE_FIELD_INT_39 if (bits == 39) return true; #endif #ifdef ENABLE_FIELD_INT_40 if (bits == 40) return true; #endif #ifdef ENABLE_FIELD_INT_41 if (bits == 41) return true; #endif #ifdef ENABLE_FIELD_INT_42 if (bits == 42) return true; #endif #ifdef ENABLE_FIELD_INT_43 if (bits == 43) return true; #endif #ifdef ENABLE_FIELD_INT_44 if (bits == 44) return true; #endif #ifdef ENABLE_FIELD_INT_45 if (bits == 45) return true; #endif #ifdef ENABLE_FIELD_INT_46 if (bits == 46) return true; #endif #ifdef ENABLE_FIELD_INT_47 if (bits == 47) return true; #endif #ifdef ENABLE_FIELD_INT_48 if (bits == 48) return true; #endif #ifdef ENABLE_FIELD_INT_49 if (bits == 49) return true; #endif #ifdef ENABLE_FIELD_INT_50 if (bits == 50) return true; #endif #ifdef ENABLE_FIELD_INT_51 if (bits == 51) return true; #endif #ifdef ENABLE_FIELD_INT_52 if (bits == 52) return true; #endif #ifdef ENABLE_FIELD_INT_53 if (bits == 53) return true; #endif #ifdef ENABLE_FIELD_INT_54 if (bits == 54) return true; #endif #ifdef ENABLE_FIELD_INT_55 if (bits == 55) return true; #endif #ifdef ENABLE_FIELD_INT_56 if (bits == 56) return true; #endif #ifdef ENABLE_FIELD_INT_57 if (bits == 57) return true; #endif #ifdef ENABLE_FIELD_INT_58 if (bits == 58) return true; #endif #ifdef ENABLE_FIELD_INT_59 if (bits == 59) return true; #endif #ifdef ENABLE_FIELD_INT_60 if (bits == 60) return true; #endif #ifdef ENABLE_FIELD_INT_61 if (bits == 61) return true; #endif #ifdef ENABLE_FIELD_INT_62 if (bits == 62) return true; #endif #ifdef ENABLE_FIELD_INT_63 if (bits == 63) return true; #endif #ifdef ENABLE_FIELD_INT_64 if (bits == 64) return true; #endif return false; } uint32_t minisketch_implementation_max() { uint32_t ret = 0; #ifdef HAVE_CLMUL ret += 2; #endif return ret; } int minisketch_implementation_supported(uint32_t bits, uint32_t implementation) { if (!minisketch_bits_supported(bits) || implementation > minisketch_implementation_max()) { return 0; } try { Sketch* sketch = Construct(bits, implementation); if (sketch) { delete sketch; return 1; } } catch (const std::bad_alloc&) {} return 0; } minisketch* minisketch_create(uint32_t bits, uint32_t implementation, size_t capacity) { try { Sketch* sketch = Construct(bits, implementation); if (sketch) { try { sketch->Init(capacity); } catch (const std::bad_alloc&) { delete sketch; throw; } sketch->Ready(); } return (minisketch*)sketch; } catch (const std::bad_alloc&) { return nullptr; } } uint32_t minisketch_bits(const minisketch* sketch) { const Sketch* s = (const Sketch*)sketch; s->Check(); return s->Bits(); } size_t minisketch_capacity(const minisketch* sketch) { const Sketch* s = (const Sketch*)sketch; s->Check(); return s->Syndromes(); } uint32_t minisketch_implementation(const minisketch* sketch) { const Sketch* s = (const Sketch*)sketch; s->Check(); return s->Implementation(); } minisketch* minisketch_clone(const minisketch* sketch) { const Sketch* s = (const Sketch*)sketch; s->Check(); Sketch* r = (Sketch*) minisketch_create(s->Bits(), s->Implementation(), s->Syndromes()); if (r) { r->Merge(s); } return (minisketch*) r; } void minisketch_destroy(minisketch* sketch) { if (sketch) { Sketch* s = (Sketch*)sketch; s->UnReady(); delete s; } } size_t minisketch_serialized_size(const minisketch* sketch) { const Sketch* s = (const Sketch*)sketch; s->Check(); size_t bits = s->Bits(); size_t syndromes = s->Syndromes(); return (bits * syndromes + 7) / 8; } void minisketch_serialize(const minisketch* sketch, unsigned char* output) { const Sketch* s = (const Sketch*)sketch; s->Check(); s->Serialize(output); } void minisketch_deserialize(minisketch* sketch, const unsigned char* input) { Sketch* s = (Sketch*)sketch; s->Check(); s->Deserialize(input); } void minisketch_add_uint64(minisketch* sketch, uint64_t element) { Sketch* s = (Sketch*)sketch; s->Check(); s->Add(element); } size_t minisketch_merge(minisketch* sketch, const minisketch* other_sketch) { Sketch* s1 = (Sketch*)sketch; const Sketch* s2 = (const Sketch*)other_sketch; s1->Check(); s2->Check(); if (s1->Bits() != s2->Bits()) return 0; if (s1->Implementation() != s2->Implementation()) return 0; return s1->Merge(s2); } ssize_t minisketch_decode(const minisketch* sketch, size_t max_elements, uint64_t* output) { const Sketch* s = (const Sketch*)sketch; s->Check(); return s->Decode(max_elements, output); } void minisketch_set_seed(minisketch* sketch, uint64_t seed) { Sketch* s = (Sketch*)sketch; s->Check(); s->SetSeed(seed); } size_t minisketch_compute_capacity(uint32_t bits, size_t max_elements, uint32_t fpbits) { return ComputeCapacity(bits, max_elements, fpbits); } size_t minisketch_compute_max_elements(uint32_t bits, size_t capacity, uint32_t fpbits) { return ComputeMaxElements(bits, capacity, fpbits); } }
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/fielddefines.h
/********************************************************************** * Copyright (c) 2021 Cory Fields * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_FIELDDEFINES_H_ #define _MINISKETCH_FIELDDEFINES_H_ /* This file translates external defines ENABLE_FIELD_FOO, DISABLE_FIELD_FOO, and DISABLE_DEFAULT_FIELDS to internal ones: ENABLE_FIELD_INT_FOO. Only the resulting internal includes should be used. Default: All fields enabled -DDISABLE_FIELD_3: All fields except 3 are enabled -DENABLE_FIELD_3: All fields enabled -DDISABLE_DEFAULT_FIELDS: Error, no fields enabled -DDISABLE_DEFAULT_FIELDS -DENABLE_FIELD_3: Only field 3 enabled -DDISABLE_DEFAULT_FIELDS -DENABLE_FIELD_2 -DENABLE_FIELD_3: Only fields 2 and 3 are enabled -DDISABLE_DEFAULT_FIELDS -DENABLE_FIELD_2 -DENABLE_FIELD_3 -DDISABLE_FIELD_3: Only field 2 enabled */ #ifdef DISABLE_DEFAULT_FIELDS #if defined(ENABLE_FIELD_2) && !defined(DISABLE_FIELD_2) #define ENABLE_FIELD_INT_2 #endif #if defined(ENABLE_FIELD_3) && !defined(DISABLE_FIELD_3) #define ENABLE_FIELD_INT_3 #endif #if defined(ENABLE_FIELD_4) && !defined(DISABLE_FIELD_4) #define ENABLE_FIELD_INT_4 #endif #if defined(ENABLE_FIELD_5) && !defined(DISABLE_FIELD_5) #define ENABLE_FIELD_INT_5 #endif #if defined(ENABLE_FIELD_6) && !defined(DISABLE_FIELD_6) #define ENABLE_FIELD_INT_6 #endif #if defined(ENABLE_FIELD_7) && !defined(DISABLE_FIELD_7) #define ENABLE_FIELD_INT_7 #endif #if defined(ENABLE_FIELD_8) && !defined(DISABLE_FIELD_8) #define ENABLE_FIELD_INT_8 #endif #if defined(ENABLE_FIELD_9) && !defined(DISABLE_FIELD_9) #define ENABLE_FIELD_INT_9 #endif #if defined(ENABLE_FIELD_10) && !defined(DISABLE_FIELD_10) #define ENABLE_FIELD_INT_10 #endif #if defined(ENABLE_FIELD_11) && !defined(DISABLE_FIELD_11) #define ENABLE_FIELD_INT_11 #endif #if defined(ENABLE_FIELD_12) && !defined(DISABLE_FIELD_12) #define ENABLE_FIELD_INT_12 #endif #if defined(ENABLE_FIELD_13) && !defined(DISABLE_FIELD_13) #define ENABLE_FIELD_INT_13 #endif #if defined(ENABLE_FIELD_14) && !defined(DISABLE_FIELD_14) #define ENABLE_FIELD_INT_14 #endif #if defined(ENABLE_FIELD_15) && !defined(DISABLE_FIELD_15) #define ENABLE_FIELD_INT_15 #endif #if defined(ENABLE_FIELD_16) && !defined(DISABLE_FIELD_16) #define ENABLE_FIELD_INT_16 #endif #if defined(ENABLE_FIELD_17) && !defined(DISABLE_FIELD_17) #define ENABLE_FIELD_INT_17 #endif #if defined(ENABLE_FIELD_18) && !defined(DISABLE_FIELD_18) #define ENABLE_FIELD_INT_18 #endif #if defined(ENABLE_FIELD_19) && !defined(DISABLE_FIELD_19) #define ENABLE_FIELD_INT_19 #endif #if defined(ENABLE_FIELD_20) && !defined(DISABLE_FIELD_20) #define ENABLE_FIELD_INT_20 #endif #if defined(ENABLE_FIELD_21) && !defined(DISABLE_FIELD_21) #define ENABLE_FIELD_INT_21 #endif #if defined(ENABLE_FIELD_22) && !defined(DISABLE_FIELD_22) #define ENABLE_FIELD_INT_22 #endif #if defined(ENABLE_FIELD_23) && !defined(DISABLE_FIELD_23) #define ENABLE_FIELD_INT_23 #endif #if defined(ENABLE_FIELD_24) && !defined(DISABLE_FIELD_24) #define ENABLE_FIELD_INT_24 #endif #if defined(ENABLE_FIELD_25) && !defined(DISABLE_FIELD_25) #define ENABLE_FIELD_INT_25 #endif #if defined(ENABLE_FIELD_26) && !defined(DISABLE_FIELD_26) #define ENABLE_FIELD_INT_26 #endif #if defined(ENABLE_FIELD_27) && !defined(DISABLE_FIELD_27) #define ENABLE_FIELD_INT_27 #endif #if defined(ENABLE_FIELD_28) && !defined(DISABLE_FIELD_28) #define ENABLE_FIELD_INT_28 #endif #if defined(ENABLE_FIELD_29) && !defined(DISABLE_FIELD_29) #define ENABLE_FIELD_INT_29 #endif #if defined(ENABLE_FIELD_30) && !defined(DISABLE_FIELD_30) #define ENABLE_FIELD_INT_30 #endif #if defined(ENABLE_FIELD_31) && !defined(DISABLE_FIELD_31) #define ENABLE_FIELD_INT_31 #endif #if defined(ENABLE_FIELD_32) && !defined(DISABLE_FIELD_32) #define ENABLE_FIELD_INT_32 #endif #if defined(ENABLE_FIELD_33) && !defined(DISABLE_FIELD_33) #define ENABLE_FIELD_INT_33 #endif #if defined(ENABLE_FIELD_34) && !defined(DISABLE_FIELD_34) #define ENABLE_FIELD_INT_34 #endif #if defined(ENABLE_FIELD_35) && !defined(DISABLE_FIELD_35) #define ENABLE_FIELD_INT_35 #endif #if defined(ENABLE_FIELD_36) && !defined(DISABLE_FIELD_36) #define ENABLE_FIELD_INT_36 #endif #if defined(ENABLE_FIELD_37) && !defined(DISABLE_FIELD_37) #define ENABLE_FIELD_INT_37 #endif #if defined(ENABLE_FIELD_38) && !defined(DISABLE_FIELD_38) #define ENABLE_FIELD_INT_38 #endif #if defined(ENABLE_FIELD_39) && !defined(DISABLE_FIELD_39) #define ENABLE_FIELD_INT_39 #endif #if defined(ENABLE_FIELD_40) && !defined(DISABLE_FIELD_40) #define ENABLE_FIELD_INT_40 #endif #if defined(ENABLE_FIELD_41) && !defined(DISABLE_FIELD_41) #define ENABLE_FIELD_INT_41 #endif #if defined(ENABLE_FIELD_42) && !defined(DISABLE_FIELD_42) #define ENABLE_FIELD_INT_42 #endif #if defined(ENABLE_FIELD_43) && !defined(DISABLE_FIELD_43) #define ENABLE_FIELD_INT_43 #endif #if defined(ENABLE_FIELD_44) && !defined(DISABLE_FIELD_44) #define ENABLE_FIELD_INT_44 #endif #if defined(ENABLE_FIELD_45) && !defined(DISABLE_FIELD_45) #define ENABLE_FIELD_INT_45 #endif #if defined(ENABLE_FIELD_46) && !defined(DISABLE_FIELD_46) #define ENABLE_FIELD_INT_46 #endif #if defined(ENABLE_FIELD_47) && !defined(DISABLE_FIELD_47) #define ENABLE_FIELD_INT_47 #endif #if defined(ENABLE_FIELD_48) && !defined(DISABLE_FIELD_48) #define ENABLE_FIELD_INT_48 #endif #if defined(ENABLE_FIELD_49) && !defined(DISABLE_FIELD_49) #define ENABLE_FIELD_INT_49 #endif #if defined(ENABLE_FIELD_50) && !defined(DISABLE_FIELD_50) #define ENABLE_FIELD_INT_50 #endif #if defined(ENABLE_FIELD_51) && !defined(DISABLE_FIELD_51) #define ENABLE_FIELD_INT_51 #endif #if defined(ENABLE_FIELD_52) && !defined(DISABLE_FIELD_52) #define ENABLE_FIELD_INT_52 #endif #if defined(ENABLE_FIELD_53) && !defined(DISABLE_FIELD_53) #define ENABLE_FIELD_INT_53 #endif #if defined(ENABLE_FIELD_54) && !defined(DISABLE_FIELD_54) #define ENABLE_FIELD_INT_54 #endif #if defined(ENABLE_FIELD_55) && !defined(DISABLE_FIELD_55) #define ENABLE_FIELD_INT_55 #endif #if defined(ENABLE_FIELD_56) && !defined(DISABLE_FIELD_56) #define ENABLE_FIELD_INT_56 #endif #if defined(ENABLE_FIELD_57) && !defined(DISABLE_FIELD_57) #define ENABLE_FIELD_INT_57 #endif #if defined(ENABLE_FIELD_58) && !defined(DISABLE_FIELD_58) #define ENABLE_FIELD_INT_58 #endif #if defined(ENABLE_FIELD_59) && !defined(DISABLE_FIELD_59) #define ENABLE_FIELD_INT_59 #endif #if defined(ENABLE_FIELD_60) && !defined(DISABLE_FIELD_60) #define ENABLE_FIELD_INT_60 #endif #if defined(ENABLE_FIELD_61) && !defined(DISABLE_FIELD_61) #define ENABLE_FIELD_INT_61 #endif #if defined(ENABLE_FIELD_62) && !defined(DISABLE_FIELD_62) #define ENABLE_FIELD_INT_62 #endif #if defined(ENABLE_FIELD_63) && !defined(DISABLE_FIELD_63) #define ENABLE_FIELD_INT_63 #endif #if defined(ENABLE_FIELD_64) && !defined(DISABLE_FIELD_64) #define ENABLE_FIELD_INT_64 #endif #else #if !defined(DISABLE_FIELD_2) #define ENABLE_FIELD_INT_2 #endif #if !defined(DISABLE_FIELD_3) #define ENABLE_FIELD_INT_3 #endif #if !defined(DISABLE_FIELD_4) #define ENABLE_FIELD_INT_4 #endif #if !defined(DISABLE_FIELD_5) #define ENABLE_FIELD_INT_5 #endif #if !defined(DISABLE_FIELD_6) #define ENABLE_FIELD_INT_6 #endif #if !defined(DISABLE_FIELD_7) #define ENABLE_FIELD_INT_7 #endif #if !defined(DISABLE_FIELD_8) #define ENABLE_FIELD_INT_8 #endif #if !defined(DISABLE_FIELD_9) #define ENABLE_FIELD_INT_9 #endif #if !defined(DISABLE_FIELD_10) #define ENABLE_FIELD_INT_10 #endif #if !defined(DISABLE_FIELD_11) #define ENABLE_FIELD_INT_11 #endif #if !defined(DISABLE_FIELD_12) #define ENABLE_FIELD_INT_12 #endif #if !defined(DISABLE_FIELD_13) #define ENABLE_FIELD_INT_13 #endif #if !defined(DISABLE_FIELD_14) #define ENABLE_FIELD_INT_14 #endif #if !defined(DISABLE_FIELD_15) #define ENABLE_FIELD_INT_15 #endif #if !defined(DISABLE_FIELD_16) #define ENABLE_FIELD_INT_16 #endif #if !defined(DISABLE_FIELD_17) #define ENABLE_FIELD_INT_17 #endif #if !defined(DISABLE_FIELD_18) #define ENABLE_FIELD_INT_18 #endif #if !defined(DISABLE_FIELD_19) #define ENABLE_FIELD_INT_19 #endif #if !defined(DISABLE_FIELD_20) #define ENABLE_FIELD_INT_20 #endif #if !defined(DISABLE_FIELD_21) #define ENABLE_FIELD_INT_21 #endif #if !defined(DISABLE_FIELD_22) #define ENABLE_FIELD_INT_22 #endif #if !defined(DISABLE_FIELD_23) #define ENABLE_FIELD_INT_23 #endif #if !defined(DISABLE_FIELD_24) #define ENABLE_FIELD_INT_24 #endif #if !defined(DISABLE_FIELD_25) #define ENABLE_FIELD_INT_25 #endif #if !defined(DISABLE_FIELD_26) #define ENABLE_FIELD_INT_26 #endif #if !defined(DISABLE_FIELD_27) #define ENABLE_FIELD_INT_27 #endif #if !defined(DISABLE_FIELD_28) #define ENABLE_FIELD_INT_28 #endif #if !defined(DISABLE_FIELD_29) #define ENABLE_FIELD_INT_29 #endif #if !defined(DISABLE_FIELD_30) #define ENABLE_FIELD_INT_30 #endif #if !defined(DISABLE_FIELD_31) #define ENABLE_FIELD_INT_31 #endif #if !defined(DISABLE_FIELD_32) #define ENABLE_FIELD_INT_32 #endif #if !defined(DISABLE_FIELD_33) #define ENABLE_FIELD_INT_33 #endif #if !defined(DISABLE_FIELD_34) #define ENABLE_FIELD_INT_34 #endif #if !defined(DISABLE_FIELD_35) #define ENABLE_FIELD_INT_35 #endif #if !defined(DISABLE_FIELD_36) #define ENABLE_FIELD_INT_36 #endif #if !defined(DISABLE_FIELD_37) #define ENABLE_FIELD_INT_37 #endif #if !defined(DISABLE_FIELD_38) #define ENABLE_FIELD_INT_38 #endif #if !defined(DISABLE_FIELD_39) #define ENABLE_FIELD_INT_39 #endif #if !defined(DISABLE_FIELD_40) #define ENABLE_FIELD_INT_40 #endif #if !defined(DISABLE_FIELD_41) #define ENABLE_FIELD_INT_41 #endif #if !defined(DISABLE_FIELD_42) #define ENABLE_FIELD_INT_42 #endif #if !defined(DISABLE_FIELD_43) #define ENABLE_FIELD_INT_43 #endif #if !defined(DISABLE_FIELD_44) #define ENABLE_FIELD_INT_44 #endif #if !defined(DISABLE_FIELD_45) #define ENABLE_FIELD_INT_45 #endif #if !defined(DISABLE_FIELD_46) #define ENABLE_FIELD_INT_46 #endif #if !defined(DISABLE_FIELD_47) #define ENABLE_FIELD_INT_47 #endif #if !defined(DISABLE_FIELD_48) #define ENABLE_FIELD_INT_48 #endif #if !defined(DISABLE_FIELD_49) #define ENABLE_FIELD_INT_49 #endif #if !defined(DISABLE_FIELD_50) #define ENABLE_FIELD_INT_50 #endif #if !defined(DISABLE_FIELD_51) #define ENABLE_FIELD_INT_51 #endif #if !defined(DISABLE_FIELD_52) #define ENABLE_FIELD_INT_52 #endif #if !defined(DISABLE_FIELD_53) #define ENABLE_FIELD_INT_53 #endif #if !defined(DISABLE_FIELD_54) #define ENABLE_FIELD_INT_54 #endif #if !defined(DISABLE_FIELD_55) #define ENABLE_FIELD_INT_55 #endif #if !defined(DISABLE_FIELD_56) #define ENABLE_FIELD_INT_56 #endif #if !defined(DISABLE_FIELD_57) #define ENABLE_FIELD_INT_57 #endif #if !defined(DISABLE_FIELD_58) #define ENABLE_FIELD_INT_58 #endif #if !defined(DISABLE_FIELD_59) #define ENABLE_FIELD_INT_59 #endif #if !defined(DISABLE_FIELD_60) #define ENABLE_FIELD_INT_60 #endif #if !defined(DISABLE_FIELD_61) #define ENABLE_FIELD_INT_61 #endif #if !defined(DISABLE_FIELD_62) #define ENABLE_FIELD_INT_62 #endif #if !defined(DISABLE_FIELD_63) #define ENABLE_FIELD_INT_63 #endif #if !defined(DISABLE_FIELD_64) #define ENABLE_FIELD_INT_64 #endif #endif #if !defined(ENABLE_FIELD_INT_2) && \ !defined(ENABLE_FIELD_INT_3) && \ !defined(ENABLE_FIELD_INT_4) && \ !defined(ENABLE_FIELD_INT_5) && \ !defined(ENABLE_FIELD_INT_6) && \ !defined(ENABLE_FIELD_INT_7) && \ !defined(ENABLE_FIELD_INT_8) && \ !defined(ENABLE_FIELD_INT_9) && \ !defined(ENABLE_FIELD_INT_10) && \ !defined(ENABLE_FIELD_INT_11) && \ !defined(ENABLE_FIELD_INT_12) && \ !defined(ENABLE_FIELD_INT_13) && \ !defined(ENABLE_FIELD_INT_14) && \ !defined(ENABLE_FIELD_INT_15) && \ !defined(ENABLE_FIELD_INT_16) && \ !defined(ENABLE_FIELD_INT_17) && \ !defined(ENABLE_FIELD_INT_18) && \ !defined(ENABLE_FIELD_INT_19) && \ !defined(ENABLE_FIELD_INT_20) && \ !defined(ENABLE_FIELD_INT_21) && \ !defined(ENABLE_FIELD_INT_22) && \ !defined(ENABLE_FIELD_INT_23) && \ !defined(ENABLE_FIELD_INT_24) && \ !defined(ENABLE_FIELD_INT_25) && \ !defined(ENABLE_FIELD_INT_26) && \ !defined(ENABLE_FIELD_INT_27) && \ !defined(ENABLE_FIELD_INT_28) && \ !defined(ENABLE_FIELD_INT_29) && \ !defined(ENABLE_FIELD_INT_30) && \ !defined(ENABLE_FIELD_INT_31) && \ !defined(ENABLE_FIELD_INT_32) && \ !defined(ENABLE_FIELD_INT_33) && \ !defined(ENABLE_FIELD_INT_34) && \ !defined(ENABLE_FIELD_INT_35) && \ !defined(ENABLE_FIELD_INT_36) && \ !defined(ENABLE_FIELD_INT_37) && \ !defined(ENABLE_FIELD_INT_38) && \ !defined(ENABLE_FIELD_INT_39) && \ !defined(ENABLE_FIELD_INT_40) && \ !defined(ENABLE_FIELD_INT_41) && \ !defined(ENABLE_FIELD_INT_42) && \ !defined(ENABLE_FIELD_INT_43) && \ !defined(ENABLE_FIELD_INT_44) && \ !defined(ENABLE_FIELD_INT_45) && \ !defined(ENABLE_FIELD_INT_46) && \ !defined(ENABLE_FIELD_INT_47) && \ !defined(ENABLE_FIELD_INT_48) && \ !defined(ENABLE_FIELD_INT_49) && \ !defined(ENABLE_FIELD_INT_50) && \ !defined(ENABLE_FIELD_INT_51) && \ !defined(ENABLE_FIELD_INT_52) && \ !defined(ENABLE_FIELD_INT_53) && \ !defined(ENABLE_FIELD_INT_54) && \ !defined(ENABLE_FIELD_INT_55) && \ !defined(ENABLE_FIELD_INT_56) && \ !defined(ENABLE_FIELD_INT_57) && \ !defined(ENABLE_FIELD_INT_58) && \ !defined(ENABLE_FIELD_INT_59) && \ !defined(ENABLE_FIELD_INT_60) && \ !defined(ENABLE_FIELD_INT_61) && \ !defined(ENABLE_FIELD_INT_62) && \ !defined(ENABLE_FIELD_INT_63) && \ !defined(ENABLE_FIELD_INT_64) #error No fields enabled #endif #if defined(ENABLE_FIELD_INT_2) || \ defined(ENABLE_FIELD_INT_3) || \ defined(ENABLE_FIELD_INT_4) || \ defined(ENABLE_FIELD_INT_5) || \ defined(ENABLE_FIELD_INT_6) || \ defined(ENABLE_FIELD_INT_7) || \ defined(ENABLE_FIELD_INT_8) #define ENABLE_FIELD_BYTES_INT_1 #endif #if defined(ENABLE_FIELD_INT_9) || \ defined(ENABLE_FIELD_INT_10) || \ defined(ENABLE_FIELD_INT_11) || \ defined(ENABLE_FIELD_INT_12) || \ defined(ENABLE_FIELD_INT_13) || \ defined(ENABLE_FIELD_INT_14) || \ defined(ENABLE_FIELD_INT_15) || \ defined(ENABLE_FIELD_INT_16) #define ENABLE_FIELD_BYTES_INT_2 #endif #if defined(ENABLE_FIELD_INT_17) || \ defined(ENABLE_FIELD_INT_18) || \ defined(ENABLE_FIELD_INT_19) || \ defined(ENABLE_FIELD_INT_20) || \ defined(ENABLE_FIELD_INT_21) || \ defined(ENABLE_FIELD_INT_22) || \ defined(ENABLE_FIELD_INT_23) || \ defined(ENABLE_FIELD_INT_24) #define ENABLE_FIELD_BYTES_INT_3 #endif #if defined(ENABLE_FIELD_INT_25) || \ defined(ENABLE_FIELD_INT_26) || \ defined(ENABLE_FIELD_INT_27) || \ defined(ENABLE_FIELD_INT_28) || \ defined(ENABLE_FIELD_INT_29) || \ defined(ENABLE_FIELD_INT_30) || \ defined(ENABLE_FIELD_INT_31) || \ defined(ENABLE_FIELD_INT_32) #define ENABLE_FIELD_BYTES_INT_4 #endif #if defined(ENABLE_FIELD_INT_33) || \ defined(ENABLE_FIELD_INT_34) || \ defined(ENABLE_FIELD_INT_35) || \ defined(ENABLE_FIELD_INT_36) || \ defined(ENABLE_FIELD_INT_37) || \ defined(ENABLE_FIELD_INT_38) || \ defined(ENABLE_FIELD_INT_39) || \ defined(ENABLE_FIELD_INT_40) #define ENABLE_FIELD_BYTES_INT_5 #endif #if defined(ENABLE_FIELD_INT_41) || \ defined(ENABLE_FIELD_INT_42) || \ defined(ENABLE_FIELD_INT_43) || \ defined(ENABLE_FIELD_INT_44) || \ defined(ENABLE_FIELD_INT_45) || \ defined(ENABLE_FIELD_INT_46) || \ defined(ENABLE_FIELD_INT_47) || \ defined(ENABLE_FIELD_INT_48) #define ENABLE_FIELD_BYTES_INT_6 #endif #if defined(ENABLE_FIELD_INT_49) || \ defined(ENABLE_FIELD_INT_50) || \ defined(ENABLE_FIELD_INT_51) || \ defined(ENABLE_FIELD_INT_52) || \ defined(ENABLE_FIELD_INT_53) || \ defined(ENABLE_FIELD_INT_54) || \ defined(ENABLE_FIELD_INT_55) || \ defined(ENABLE_FIELD_INT_56) #define ENABLE_FIELD_BYTES_INT_7 #endif #if defined(ENABLE_FIELD_INT_57) || \ defined(ENABLE_FIELD_INT_58) || \ defined(ENABLE_FIELD_INT_59) || \ defined(ENABLE_FIELD_INT_60) || \ defined(ENABLE_FIELD_INT_61) || \ defined(ENABLE_FIELD_INT_62) || \ defined(ENABLE_FIELD_INT_63) || \ defined(ENABLE_FIELD_INT_64) #define ENABLE_FIELD_BYTES_INT_8 #endif #endif // _MINISKETCH_FIELDDEFINES_H_
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/int_utils.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_INT_UTILS_H_ #define _MINISKETCH_INT_UTILS_H_ #include <stdlib.h> #include <limits> #include <algorithm> #include <type_traits> #ifdef _MSC_VER # include <intrin.h> #endif template<int bits> static constexpr inline uint64_t Rot(uint64_t x) { return (x << bits) | (x >> (64 - bits)); } static inline void SipHashRound(uint64_t& v0, uint64_t& v1, uint64_t& v2, uint64_t& v3) { v0 += v1; v1 = Rot<13>(v1); v1 ^= v0; v0 = Rot<32>(v0); v2 += v3; v3 = Rot<16>(v3); v3 ^= v2; v0 += v3; v3 = Rot<21>(v3); v3 ^= v0; v2 += v1; v1 = Rot<17>(v1); v1 ^= v2; v2 = Rot<32>(v2); } inline uint64_t SipHash(uint64_t k0, uint64_t k1, uint64_t data) { uint64_t v0 = 0x736f6d6570736575ULL ^ k0; uint64_t v1 = 0x646f72616e646f6dULL ^ k1; uint64_t v2 = 0x6c7967656e657261ULL ^ k0; uint64_t v3 = 0x7465646279746573ULL ^ k1 ^ data; SipHashRound(v0, v1, v2, v3); SipHashRound(v0, v1, v2, v3); v0 ^= data; v3 ^= 0x800000000000000ULL; SipHashRound(v0, v1, v2, v3); SipHashRound(v0, v1, v2, v3); v0 ^= 0x800000000000000ULL; v2 ^= 0xFF; SipHashRound(v0, v1, v2, v3); SipHashRound(v0, v1, v2, v3); SipHashRound(v0, v1, v2, v3); SipHashRound(v0, v1, v2, v3); return v0 ^ v1 ^ v2 ^ v3; } class BitWriter { unsigned char state = 0; int offset = 0; unsigned char* out; public: BitWriter(unsigned char* output) : out(output) {} template<int BITS, typename I> inline void Write(I val) { int bits = BITS; if (bits + offset >= 8) { state |= ((val & ((I(1) << (8 - offset)) - 1)) << offset); *(out++) = state; val >>= (8 - offset); bits -= 8 - offset; offset = 0; state = 0; } while (bits >= 8) { *(out++) = val & 255; val >>= 8; bits -= 8; } state |= ((val & ((I(1) << bits) - 1)) << offset); offset += bits; } inline void Flush() { if (offset) { *(out++) = state; state = 0; offset = 0; } } }; class BitReader { unsigned char state = 0; int offset = 0; const unsigned char* in; public: BitReader(const unsigned char* input) : in(input) {} template<int BITS, typename I> inline I Read() { int bits = BITS; if (offset >= bits) { I ret = state & ((1 << bits) - 1); state >>= bits; offset -= bits; return ret; } I val = state; int out = offset; while (out + 8 <= bits) { val |= ((I(*(in++))) << out); out += 8; } if (out < bits) { unsigned char c = *(in++); val |= (c & ((I(1) << (bits - out)) - 1)) << out; state = c >> (bits - out); offset = 8 - (bits - out); } else { state = 0; offset = 0; } return val; } }; /** Return a value of type I with its `bits` lowest bits set (bits must be > 0). */ template<int BITS, typename I> constexpr inline I Mask() { return ((I((I(-1)) << (std::numeric_limits<I>::digits - BITS))) >> (std::numeric_limits<I>::digits - BITS)); } /** Compute the smallest power of two that is larger than val. */ template<typename I> static inline int CountBits(I val, int max) { #ifdef _MSC_VER (void)max; unsigned long index; unsigned char ret; if (std::numeric_limits<I>::digits <= 32) { ret = _BitScanReverse(&index, val); } else { ret = _BitScanReverse64(&index, val); } if (!ret) return 0; return index + 1; #elif HAVE_CLZ (void)max; if (val == 0) return 0; if (std::numeric_limits<unsigned>::digits >= std::numeric_limits<I>::digits) { return std::numeric_limits<unsigned>::digits - __builtin_clz(val); } else if (std::numeric_limits<unsigned long>::digits >= std::numeric_limits<I>::digits) { return std::numeric_limits<unsigned long>::digits - __builtin_clzl(val); } else { return std::numeric_limits<unsigned long long>::digits - __builtin_clzll(val); } #else while (max && (val >> (max - 1) == 0)) --max; return max; #endif } template<typename I, int BITS> class BitsInt { private: static_assert(std::is_integral<I>::value && std::is_unsigned<I>::value, "BitsInt requires an unsigned integer type"); static_assert(BITS > 0 && BITS <= std::numeric_limits<I>::digits, "BitsInt requires 1 <= Bits <= representation type size"); static constexpr I MASK = Mask<BITS, I>(); public: typedef I Repr; static constexpr int SIZE = BITS; static void inline Swap(I& a, I& b) { std::swap(a, b); } static constexpr inline bool IsZero(I a) { return a == 0; } static constexpr inline I Mask(I val) { return val & MASK; } static constexpr inline I Shift(I val, int bits) { return ((val << bits) & MASK); } static constexpr inline I UnsafeShift(I val, int bits) { return (val << bits); } template<int Offset, int Count> static constexpr inline int MidBits(I val) { static_assert(Count > 0, "BITSInt::MidBits needs Count > 0"); static_assert(Count + Offset <= BITS, "BitsInt::MidBits overflow of Count+Offset"); return (val >> Offset) & ((I(1) << Count) - 1); } template<int Count> static constexpr inline int TopBits(I val) { static_assert(Count > 0, "BitsInt::TopBits needs Count > 0"); static_assert(Count <= BITS, "BitsInt::TopBits needs Offset <= BITS"); return val >> (BITS - Count); } static inline constexpr I CondXorWith(I val, bool cond, I v) { return val ^ (-I(cond) & v); } template<I MOD> static inline constexpr I CondXorWith(I val, bool cond) { return val ^ (-I(cond) & MOD); } static inline int Bits(I val, int max) { return CountBits<I>(val, max); } }; /** Class which implements a stateless LFSR for generic moduli. */ template<typename F, uint32_t MOD> struct LFSR { typedef typename F::Repr I; /** Shift a value `a` up once, treating it as an `N`-bit LFSR, with pattern `MOD`. */ static inline constexpr I Call(const I& a) { return F::template CondXorWith<MOD>(F::Shift(a, 1), F::template TopBits<1>(a)); } }; /** Helper class for carryless multiplications. */ template<typename I, int N, typename L, typename F, int K> struct GFMulHelper; template<typename I, int N, typename L, typename F> struct GFMulHelper<I, N, L, F, 0> { static inline constexpr I Run(const I& a, const I& b) { return I(0); } }; template<typename I, int N, typename L, typename F, int K> struct GFMulHelper { static inline constexpr I Run(const I& a, const I& b) { return F::CondXorWith(GFMulHelper<I, N, L, F, K - 1>::Run(L::Call(a), b), F::template MidBits<N - K, 1>(b), a); } }; /** Compute the carry-less multiplication of a and b, with N bits, using L as LFSR type. */ template<typename I, int N, typename L, typename F> inline constexpr I GFMul(const I& a, const I& b) { return GFMulHelper<I, N, L, F, N>::Run(a, b); } /** Compute the inverse of x using an extgcd algorithm. */ template<typename I, typename F, int BITS, uint32_t MOD> inline I InvExtGCD(I x) { if (F::IsZero(x)) return x; I t(0), newt(1); I r(MOD), newr = x; int rlen = BITS + 1, newrlen = F::Bits(newr, BITS); while (newr) { int q = rlen - newrlen; r ^= F::Shift(newr, q); t ^= F::UnsafeShift(newt, q); rlen = F::Bits(r, rlen - 1); if (r < newr) { F::Swap(t, newt); F::Swap(r, newr); std::swap(rlen, newrlen); } } return t; } /** Compute the inverse of x1 using an exponentiation ladder. * * The `MUL` argument is a multiplication function, `SQR` is a squaring function, and the `SQRi` arguments * compute x**(2**i). */ template<typename I, typename F, int BITS, I (*MUL)(I, I), I (*SQR)(I), I (*SQR2)(I), I(*SQR4)(I), I(*SQR8)(I), I(*SQR16)(I)> inline I InvLadder(I x1) { static constexpr int INV_EXP = BITS - 1; I x2 = (INV_EXP >= 2) ? MUL(SQR(x1), x1) : I(); I x4 = (INV_EXP >= 4) ? MUL(SQR2(x2), x2) : I(); I x8 = (INV_EXP >= 8) ? MUL(SQR4(x4), x4) : I(); I x16 = (INV_EXP >= 16) ? MUL(SQR8(x8), x8) : I(); I x32 = (INV_EXP >= 32) ? MUL(SQR16(x16), x16) : I(); I r; if (INV_EXP >= 32) { r = x32; } else if (INV_EXP >= 16) { r = x16; } else if (INV_EXP >= 8) { r = x8; } else if (INV_EXP >= 4) { r = x4; } else if (INV_EXP >= 2) { r = x2; } else { r = x1; } if (INV_EXP >= 32 && (INV_EXP & 16)) r = MUL(SQR16(r), x16); if (INV_EXP >= 16 && (INV_EXP & 8)) r = MUL(SQR8(r), x8); if (INV_EXP >= 8 && (INV_EXP & 4)) r = MUL(SQR4(r), x4); if (INV_EXP >= 4 && (INV_EXP & 2)) r = MUL(SQR2(r), x2); if (INV_EXP >= 2 && (INV_EXP & 1)) r = MUL(SQR(r), x1); return SQR(r); } #endif
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/lintrans.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_LINTRANS_H_ #define _MINISKETCH_LINTRANS_H_ #include "int_utils.h" /** A type to represent integers in the type system. */ template<int N> struct Num {}; /** A Linear N-bit transformation over the field I. */ template<typename I, int N> class LinTrans { private: I table[1 << N]; public: LinTrans() = default; /* Construct a transformation over 3 to 8 bits, using the images of each bit. */ constexpr LinTrans(I a, I b) : table{I(0), I(a), I(b), I(a ^ b)} {} constexpr LinTrans(I a, I b, I c) : table{I(0), I(a), I(b), I(a ^ b), I(c), I(a ^ c), I(b ^ c), I(a ^ b ^ c)} {} constexpr LinTrans(I a, I b, I c, I d) : table{I(0), I(a), I(b), I(a ^ b), I(c), I(a ^ c), I(b ^ c), I(a ^ b ^ c), I(d), I(a ^ d), I(b ^ d), I(a ^ b ^ d), I(c ^ d), I(a ^ c ^ d), I(b ^ c ^ d), I(a ^ b ^ c ^ d)} {} constexpr LinTrans(I a, I b, I c, I d, I e) : table{I(0), I(a), I(b), I(a ^ b), I(c), I(a ^ c), I(b ^ c), I(a ^ b ^ c), I(d), I(a ^ d), I(b ^ d), I(a ^ b ^ d), I(c ^ d), I(a ^ c ^ d), I(b ^ c ^ d), I(a ^ b ^ c ^ d), I(e), I(a ^ e), I(b ^ e), I(a ^ b ^ e), I(c ^ e), I(a ^ c ^ e), I(b ^ c ^ e), I(a ^ b ^ c ^ e), I(d ^ e), I(a ^ d ^ e), I(b ^ d ^ e), I(a ^ b ^ d ^ e), I(c ^ d ^ e), I(a ^ c ^ d ^ e), I(b ^ c ^ d ^ e), I(a ^ b ^ c ^ d ^ e)} {} constexpr LinTrans(I a, I b, I c, I d, I e, I f) : table{I(0), I(a), I(b), I(a ^ b), I(c), I(a ^ c), I(b ^ c), I(a ^ b ^ c), I(d), I(a ^ d), I(b ^ d), I(a ^ b ^ d), I(c ^ d), I(a ^ c ^ d), I(b ^ c ^ d), I(a ^ b ^ c ^ d), I(e), I(a ^ e), I(b ^ e), I(a ^ b ^ e), I(c ^ e), I(a ^ c ^ e), I(b ^ c ^ e), I(a ^ b ^ c ^ e), I(d ^ e), I(a ^ d ^ e), I(b ^ d ^ e), I(a ^ b ^ d ^ e), I(c ^ d ^ e), I(a ^ c ^ d ^ e), I(b ^ c ^ d ^ e), I(a ^ b ^ c ^ d ^ e), I(f), I(a ^ f), I(b^ f), I(a ^ b ^ f), I(c^ f), I(a ^ c ^ f), I(b ^ c ^ f), I(a ^ b ^ c ^ f), I(d ^ f), I(a ^ d ^ f), I(b ^ d ^ f), I(a ^ b ^ d ^ f), I(c ^ d ^ f), I(a ^ c ^ d ^ f), I(b ^ c ^ d ^ f), I(a ^ b ^ c ^ d ^ f), I(e ^ f), I(a ^ e ^ f), I(b ^ e ^ f), I(a ^ b ^ e ^ f), I(c ^ e ^ f), I(a ^ c ^ e ^ f), I(b ^ c ^ e ^ f), I(a ^ b ^ c ^ e ^ f), I(d ^ e ^ f), I(a ^ d ^ e ^ f), I(b ^ d ^ e ^ f), I(a ^ b ^ d ^ e ^ f), I(c ^ d ^ e ^ f), I(a ^ c ^ d ^ e ^ f), I(b ^ c ^ d ^ e ^ f), I(a ^ b ^ c ^ d ^ e ^ f)} {} constexpr LinTrans(I a, I b, I c, I d, I e, I f, I g) : table{I(0), I(a), I(b), I(a ^ b), I(c), I(a ^ c), I(b ^ c), I(a ^ b ^ c), I(d), I(a ^ d), I(b ^ d), I(a ^ b ^ d), I(c ^ d), I(a ^ c ^ d), I(b ^ c ^ d), I(a ^ b ^ c ^ d), I(e), I(a ^ e), I(b ^ e), I(a ^ b ^ e), I(c ^ e), I(a ^ c ^ e), I(b ^ c ^ e), I(a ^ b ^ c ^ e), I(d ^ e), I(a ^ d ^ e), I(b ^ d ^ e), I(a ^ b ^ d ^ e), I(c ^ d ^ e), I(a ^ c ^ d ^ e), I(b ^ c ^ d ^ e), I(a ^ b ^ c ^ d ^ e), I(f), I(a ^ f), I(b^ f), I(a ^ b ^ f), I(c^ f), I(a ^ c ^ f), I(b ^ c ^ f), I(a ^ b ^ c ^ f), I(d ^ f), I(a ^ d ^ f), I(b ^ d ^ f), I(a ^ b ^ d ^ f), I(c ^ d ^ f), I(a ^ c ^ d ^ f), I(b ^ c ^ d ^ f), I(a ^ b ^ c ^ d ^ f), I(e ^ f), I(a ^ e ^ f), I(b ^ e ^ f), I(a ^ b ^ e ^ f), I(c ^ e ^ f), I(a ^ c ^ e ^ f), I(b ^ c ^ e ^ f), I(a ^ b ^ c ^ e ^ f), I(d ^ e ^ f), I(a ^ d ^ e ^ f), I(b ^ d ^ e ^ f), I(a ^ b ^ d ^ e ^ f), I(c ^ d ^ e ^ f), I(a ^ c ^ d ^ e ^ f), I(b ^ c ^ d ^ e ^ f), I(a ^ b ^ c ^ d ^ e ^ f), I(g), I(a ^ g), I(b ^ g), I(a ^ b ^ g), I(c ^ g), I(a ^ c ^ g), I(b ^ c ^ g), I(a ^ b ^ c ^ g), I(d ^ g), I(a ^ d ^ g), I(b ^ d ^ g), I(a ^ b ^ d ^ g), I(c ^ d ^ g), I(a ^ c ^ d ^ g), I(b ^ c ^ d ^ g), I(a ^ b ^ c ^ d ^ g), I(e ^ g), I(a ^ e ^ g), I(b ^ e ^ g), I(a ^ b ^ e ^ g), I(c ^ e ^ g), I(a ^ c ^ e ^ g), I(b ^ c ^ e ^ g), I(a ^ b ^ c ^ e ^ g), I(d ^ e ^ g), I(a ^ d ^ e ^ g), I(b ^ d ^ e ^ g), I(a ^ b ^ d ^ e ^ g), I(c ^ d ^ e ^ g), I(a ^ c ^ d ^ e ^ g), I(b ^ c ^ d ^ e ^ g), I(a ^ b ^ c ^ d ^ e ^ g), I(f ^ g), I(a ^ f ^ g), I(b^ f ^ g), I(a ^ b ^ f ^ g), I(c^ f ^ g), I(a ^ c ^ f ^ g), I(b ^ c ^ f ^ g), I(a ^ b ^ c ^ f ^ g), I(d ^ f ^ g), I(a ^ d ^ f ^ g), I(b ^ d ^ f ^ g), I(a ^ b ^ d ^ f ^ g), I(c ^ d ^ f ^ g), I(a ^ c ^ d ^ f ^ g), I(b ^ c ^ d ^ f ^ g), I(a ^ b ^ c ^ d ^ f ^ g), I(e ^ f ^ g), I(a ^ e ^ f ^ g), I(b ^ e ^ f ^ g), I(a ^ b ^ e ^ f ^ g), I(c ^ e ^ f ^ g), I(a ^ c ^ e ^ f ^ g), I(b ^ c ^ e ^ f ^ g), I(a ^ b ^ c ^ e ^ f ^ g), I(d ^ e ^ f ^ g), I(a ^ d ^ e ^ f ^ g), I(b ^ d ^ e ^ f ^ g), I(a ^ b ^ d ^ e ^ f ^ g), I(c ^ d ^ e ^ f ^ g), I(a ^ c ^ d ^ e ^ f ^ g), I(b ^ c ^ d ^ e ^ f ^ g), I(a ^ b ^ c ^ d ^ e ^ f ^ g)} {} constexpr LinTrans(I a, I b, I c, I d, I e, I f, I g, I h) : table{I(0), I(a), I(b), I(a ^ b), I(c), I(a ^ c), I(b ^ c), I(a ^ b ^ c), I(d), I(a ^ d), I(b ^ d), I(a ^ b ^ d), I(c ^ d), I(a ^ c ^ d), I(b ^ c ^ d), I(a ^ b ^ c ^ d), I(e), I(a ^ e), I(b ^ e), I(a ^ b ^ e), I(c ^ e), I(a ^ c ^ e), I(b ^ c ^ e), I(a ^ b ^ c ^ e), I(d ^ e), I(a ^ d ^ e), I(b ^ d ^ e), I(a ^ b ^ d ^ e), I(c ^ d ^ e), I(a ^ c ^ d ^ e), I(b ^ c ^ d ^ e), I(a ^ b ^ c ^ d ^ e), I(f), I(a ^ f), I(b^ f), I(a ^ b ^ f), I(c^ f), I(a ^ c ^ f), I(b ^ c ^ f), I(a ^ b ^ c ^ f), I(d ^ f), I(a ^ d ^ f), I(b ^ d ^ f), I(a ^ b ^ d ^ f), I(c ^ d ^ f), I(a ^ c ^ d ^ f), I(b ^ c ^ d ^ f), I(a ^ b ^ c ^ d ^ f), I(e ^ f), I(a ^ e ^ f), I(b ^ e ^ f), I(a ^ b ^ e ^ f), I(c ^ e ^ f), I(a ^ c ^ e ^ f), I(b ^ c ^ e ^ f), I(a ^ b ^ c ^ e ^ f), I(d ^ e ^ f), I(a ^ d ^ e ^ f), I(b ^ d ^ e ^ f), I(a ^ b ^ d ^ e ^ f), I(c ^ d ^ e ^ f), I(a ^ c ^ d ^ e ^ f), I(b ^ c ^ d ^ e ^ f), I(a ^ b ^ c ^ d ^ e ^ f), I(g), I(a ^ g), I(b ^ g), I(a ^ b ^ g), I(c ^ g), I(a ^ c ^ g), I(b ^ c ^ g), I(a ^ b ^ c ^ g), I(d ^ g), I(a ^ d ^ g), I(b ^ d ^ g), I(a ^ b ^ d ^ g), I(c ^ d ^ g), I(a ^ c ^ d ^ g), I(b ^ c ^ d ^ g), I(a ^ b ^ c ^ d ^ g), I(e ^ g), I(a ^ e ^ g), I(b ^ e ^ g), I(a ^ b ^ e ^ g), I(c ^ e ^ g), I(a ^ c ^ e ^ g), I(b ^ c ^ e ^ g), I(a ^ b ^ c ^ e ^ g), I(d ^ e ^ g), I(a ^ d ^ e ^ g), I(b ^ d ^ e ^ g), I(a ^ b ^ d ^ e ^ g), I(c ^ d ^ e ^ g), I(a ^ c ^ d ^ e ^ g), I(b ^ c ^ d ^ e ^ g), I(a ^ b ^ c ^ d ^ e ^ g), I(f ^ g), I(a ^ f ^ g), I(b^ f ^ g), I(a ^ b ^ f ^ g), I(c^ f ^ g), I(a ^ c ^ f ^ g), I(b ^ c ^ f ^ g), I(a ^ b ^ c ^ f ^ g), I(d ^ f ^ g), I(a ^ d ^ f ^ g), I(b ^ d ^ f ^ g), I(a ^ b ^ d ^ f ^ g), I(c ^ d ^ f ^ g), I(a ^ c ^ d ^ f ^ g), I(b ^ c ^ d ^ f ^ g), I(a ^ b ^ c ^ d ^ f ^ g), I(e ^ f ^ g), I(a ^ e ^ f ^ g), I(b ^ e ^ f ^ g), I(a ^ b ^ e ^ f ^ g), I(c ^ e ^ f ^ g), I(a ^ c ^ e ^ f ^ g), I(b ^ c ^ e ^ f ^ g), I(a ^ b ^ c ^ e ^ f ^ g), I(d ^ e ^ f ^ g), I(a ^ d ^ e ^ f ^ g), I(b ^ d ^ e ^ f ^ g), I(a ^ b ^ d ^ e ^ f ^ g), I(c ^ d ^ e ^ f ^ g), I(a ^ c ^ d ^ e ^ f ^ g), I(b ^ c ^ d ^ e ^ f ^ g), I(a ^ b ^ c ^ d ^ e ^ f ^ g), I(h), I(a ^ h), I(b ^ h), I(a ^ b ^ h), I(c ^ h), I(a ^ c ^ h), I(b ^ c ^ h), I(a ^ b ^ c ^ h), I(d ^ h), I(a ^ d ^ h), I(b ^ d ^ h), I(a ^ b ^ d ^ h), I(c ^ d ^ h), I(a ^ c ^ d ^ h), I(b ^ c ^ d ^ h), I(a ^ b ^ c ^ d ^ h), I(e ^ h), I(a ^ e ^ h), I(b ^ e ^ h), I(a ^ b ^ e ^ h), I(c ^ e ^ h), I(a ^ c ^ e ^ h), I(b ^ c ^ e ^ h), I(a ^ b ^ c ^ e ^ h), I(d ^ e ^ h), I(a ^ d ^ e ^ h), I(b ^ d ^ e ^ h), I(a ^ b ^ d ^ e ^ h), I(c ^ d ^ e ^ h), I(a ^ c ^ d ^ e ^ h), I(b ^ c ^ d ^ e ^ h), I(a ^ b ^ c ^ d ^ e ^ h), I(f ^ h), I(a ^ f ^ h), I(b^ f ^ h), I(a ^ b ^ f ^ h), I(c^ f ^ h), I(a ^ c ^ f ^ h), I(b ^ c ^ f ^ h), I(a ^ b ^ c ^ f ^ h), I(d ^ f ^ h), I(a ^ d ^ f ^ h), I(b ^ d ^ f ^ h), I(a ^ b ^ d ^ f ^ h), I(c ^ d ^ f ^ h), I(a ^ c ^ d ^ f ^ h), I(b ^ c ^ d ^ f ^ h), I(a ^ b ^ c ^ d ^ f ^ h), I(e ^ f ^ h), I(a ^ e ^ f ^ h), I(b ^ e ^ f ^ h), I(a ^ b ^ e ^ f ^ h), I(c ^ e ^ f ^ h), I(a ^ c ^ e ^ f ^ h), I(b ^ c ^ e ^ f ^ h), I(a ^ b ^ c ^ e ^ f ^ h), I(d ^ e ^ f ^ h), I(a ^ d ^ e ^ f ^ h), I(b ^ d ^ e ^ f ^ h), I(a ^ b ^ d ^ e ^ f ^ h), I(c ^ d ^ e ^ f ^ h), I(a ^ c ^ d ^ e ^ f ^ h), I(b ^ c ^ d ^ e ^ f ^ h), I(a ^ b ^ c ^ d ^ e ^ f ^ h), I(g ^ h), I(a ^ g ^ h), I(b ^ g ^ h), I(a ^ b ^ g ^ h), I(c ^ g ^ h), I(a ^ c ^ g ^ h), I(b ^ c ^ g ^ h), I(a ^ b ^ c ^ g ^ h), I(d ^ g ^ h), I(a ^ d ^ g ^ h), I(b ^ d ^ g ^ h), I(a ^ b ^ d ^ g ^ h), I(c ^ d ^ g ^ h), I(a ^ c ^ d ^ g ^ h), I(b ^ c ^ d ^ g ^ h), I(a ^ b ^ c ^ d ^ g ^ h), I(e ^ g ^ h), I(a ^ e ^ g ^ h), I(b ^ e ^ g ^ h), I(a ^ b ^ e ^ g ^ h), I(c ^ e ^ g ^ h), I(a ^ c ^ e ^ g ^ h), I(b ^ c ^ e ^ g ^ h), I(a ^ b ^ c ^ e ^ g ^ h), I(d ^ e ^ g ^ h), I(a ^ d ^ e ^ g ^ h), I(b ^ d ^ e ^ g ^ h), I(a ^ b ^ d ^ e ^ g ^ h), I(c ^ d ^ e ^ g ^ h), I(a ^ c ^ d ^ e ^ g ^ h), I(b ^ c ^ d ^ e ^ g ^ h), I(a ^ b ^ c ^ d ^ e ^ g ^ h), I(f ^ g ^ h), I(a ^ f ^ g ^ h), I(b^ f ^ g ^ h), I(a ^ b ^ f ^ g ^ h), I(c^ f ^ g ^ h), I(a ^ c ^ f ^ g ^ h), I(b ^ c ^ f ^ g ^ h), I(a ^ b ^ c ^ f ^ g ^ h), I(d ^ f ^ g ^ h), I(a ^ d ^ f ^ g ^ h), I(b ^ d ^ f ^ g ^ h), I(a ^ b ^ d ^ f ^ g ^ h), I(c ^ d ^ f ^ g ^ h), I(a ^ c ^ d ^ f ^ g ^ h), I(b ^ c ^ d ^ f ^ g ^ h), I(a ^ b ^ c ^ d ^ f ^ g ^ h), I(e ^ f ^ g ^ h), I(a ^ e ^ f ^ g ^ h), I(b ^ e ^ f ^ g ^ h), I(a ^ b ^ e ^ f ^ g ^ h), I(c ^ e ^ f ^ g ^ h), I(a ^ c ^ e ^ f ^ g ^ h), I(b ^ c ^ e ^ f ^ g ^ h), I(a ^ b ^ c ^ e ^ f ^ g ^ h), I(d ^ e ^ f ^ g ^ h), I(a ^ d ^ e ^ f ^ g ^ h), I(b ^ d ^ e ^ f ^ g ^ h), I(a ^ b ^ d ^ e ^ f ^ g ^ h), I(c ^ d ^ e ^ f ^ g ^ h), I(a ^ c ^ d ^ e ^ f ^ g ^ h), I(b ^ c ^ d ^ e ^ f ^ g ^ h), I(a ^ b ^ c ^ d ^ e ^ f ^ g ^ h)} {} /* Construct a transformation over 3 to 8 bits, using a pointer to the bit's images. */ constexpr LinTrans(const I* p, Num<2>) : LinTrans(I(p[0]), I(p[1])) {} constexpr LinTrans(const I* p, Num<3>) : LinTrans(I(p[0]), I(p[1]), I(p[2])) {} constexpr LinTrans(const I* p, Num<4>) : LinTrans(I(p[0]), I(p[1]), I(p[2]), I(p[3])) {} constexpr LinTrans(const I* p, Num<5>) : LinTrans(I(p[0]), I(p[1]), I(p[2]), I(p[3]), I(p[4])) {} constexpr LinTrans(const I* p, Num<6>) : LinTrans(I(p[0]), I(p[1]), I(p[2]), I(p[3]), I(p[4]), I(p[5])) {} constexpr LinTrans(const I* p, Num<7>) : LinTrans(I(p[0]), I(p[1]), I(p[2]), I(p[3]), I(p[4]), I(p[5]), I(p[6])) {} constexpr LinTrans(const I* p, Num<8>) : LinTrans(I(p[0]), I(p[1]), I(p[2]), I(p[3]), I(p[4]), I(p[5]), I(p[6]), I(p[7])) {} template<I (*F)(const I&)> inline I Build(Num<1>, I a) { table[0] = I(); table[1] = a; return a; } template<I (*F)(const I&)> inline I Build(Num<2>, I a) { I b = F(a); table[0] = I(); table[1] = a; table[2] = b; table[3] = a ^ b; return b; } template<I (*F)(const I&)> inline I Build(Num<3>, I a) { I b = F(a), c = F(b); table[0] = I(); table[1] = a; table[2] = b; table[3] = a ^ b; table[4] = c; table[5] = a ^ c; table[6] = b ^ c; table[7] = a ^ b ^ c; return c; } template<I (*F)(const I&)> inline I Build(Num<4>, I a) { I b = F(a), c = F(b), d = F(c); table[0] = I(); table[1] = a; table[2] = b; table[3] = a ^ b; table[4] = c; table[5] = a ^ c; table[6] = b ^ c; table[7] = a ^ b ^ c; table[8] = d; table[9] = a ^ d; table[10] = b ^ d; table[11] = a ^ b ^ d; table[12] = c ^ d; table[13] = a ^ c ^ d; table[14] = b ^ c ^ d; table[15] = a ^ b ^ c ^ d; return d; } template<I (*F)(const I&)> inline I Build(Num<5>, I a) { I b = F(a), c = F(b), d = F(c), e = F(d); table[0] = I(); table[1] = a; table[2] = b; table[3] = a ^ b; table[4] = c; table[5] = a ^ c; table[6] = b ^ c; table[7] = a ^ b ^ c; table[8] = d; table[9] = a ^ d; table[10] = b ^ d; table[11] = a ^ b ^ d; table[12] = c ^ d; table[13] = a ^ c ^ d; table[14] = b ^ c ^ d; table[15] = a ^ b ^ c ^ d; table[16] = e; table[17] = a ^ e; table[18] = b ^ e; table[19] = a ^ b ^ e; table[20] = c ^ e; table[21] = a ^ c ^ e; table[22] = b ^ c ^ e; table[23] = a ^ b ^ c ^ e; table[24] = d ^ e; table[25] = a ^ d ^ e; table[26] = b ^ d ^ e; table[27] = a ^ b ^ d ^ e; table[28] = c ^ d ^ e; table[29] = a ^ c ^ d ^ e; table[30] = b ^ c ^ d ^ e; table[31] = a ^ b ^ c ^ d ^ e; return e; } template<I (*F)(const I&)> inline I Build(Num<6>, I a) { I b = F(a), c = F(b), d = F(c), e = F(d), f = F(e); table[0] = I(); table[1] = a; table[2] = b; table[3] = a ^ b; table[4] = c; table[5] = a ^ c; table[6] = b ^ c; table[7] = a ^ b ^ c; table[8] = d; table[9] = a ^ d; table[10] = b ^ d; table[11] = a ^ b ^ d; table[12] = c ^ d; table[13] = a ^ c ^ d; table[14] = b ^ c ^ d; table[15] = a ^ b ^ c ^ d; table[16] = e; table[17] = a ^ e; table[18] = b ^ e; table[19] = a ^ b ^ e; table[20] = c ^ e; table[21] = a ^ c ^ e; table[22] = b ^ c ^ e; table[23] = a ^ b ^ c ^ e; table[24] = d ^ e; table[25] = a ^ d ^ e; table[26] = b ^ d ^ e; table[27] = a ^ b ^ d ^ e; table[28] = c ^ d ^ e; table[29] = a ^ c ^ d ^ e; table[30] = b ^ c ^ d ^ e; table[31] = a ^ b ^ c ^ d ^ e; table[32] = f; table[33] = a ^ f; table[34] = b ^ f; table[35] = a ^ b ^ f; table[36] = c ^ f; table[37] = a ^ c ^ f; table[38] = b ^ c ^ f; table[39] = a ^ b ^ c ^ f; table[40] = d ^ f; table[41] = a ^ d ^ f; table[42] = b ^ d ^ f; table[43] = a ^ b ^ d ^ f; table[44] = c ^ d ^ f; table[45] = a ^ c ^ d ^ f; table[46] = b ^ c ^ d ^ f; table[47] = a ^ b ^ c ^ d ^ f; table[48] = e ^ f; table[49] = a ^ e ^ f; table[50] = b ^ e ^ f; table[51] = a ^ b ^ e ^ f; table[52] = c ^ e ^ f; table[53] = a ^ c ^ e ^ f; table[54] = b ^ c ^ e ^ f; table[55] = a ^ b ^ c ^ e ^ f; table[56] = d ^ e ^ f; table[57] = a ^ d ^ e ^ f; table[58] = b ^ d ^ e ^ f; table[59] = a ^ b ^ d ^ e ^ f; table[60] = c ^ d ^ e ^ f; table[61] = a ^ c ^ d ^ e ^ f; table[62] = b ^ c ^ d ^ e ^ f; table[63] = a ^ b ^ c ^ d ^ e ^ f; return f; } template<typename O, int P> inline I constexpr Map(I a) const { return table[O::template MidBits<P, N>(a)]; } template<typename O, int P> inline I constexpr TopMap(I a) const { static_assert(P + N == O::SIZE, "TopMap inconsistency"); return table[O::template TopBits<N>(a)]; } }; /** A linear transformation constructed using LinTrans tables for sections of bits. */ template<typename I, int... N> class RecLinTrans; template<typename I, int N> class RecLinTrans<I, N> { LinTrans<I, N> trans; public: static constexpr int BITS = N; constexpr RecLinTrans(const I* p, Num<BITS>) : trans(p, Num<N>()) {} constexpr RecLinTrans() = default; constexpr RecLinTrans(const I (&init)[BITS]) : RecLinTrans(init, Num<BITS>()) {} template<typename O, int P = 0> inline I constexpr Map(I a) const { return trans.template TopMap<O, P>(a); } template<I (*F)(const I&)> inline void Build(I a) { trans.template Build<F>(Num<N>(), a); } }; template<typename I, int N, int... X> class RecLinTrans<I, N, X...> { LinTrans<I, N> trans; RecLinTrans<I, X...> rec; public: static constexpr int BITS = RecLinTrans<I, X...>::BITS + N; constexpr RecLinTrans(const I* p, Num<BITS>) : trans(p, Num<N>()), rec(p + N, Num<BITS - N>()) {} constexpr RecLinTrans() = default; constexpr RecLinTrans(const I (&init)[BITS]) : RecLinTrans(init, Num<BITS>()) {} template<typename O, int P = 0> inline I constexpr Map(I a) const { return trans.template Map<O, P>(a) ^ rec.template Map<O, P + N>(a); } template<I (*F)(const I&)> inline void Build(I a) { I n = trans.template Build<F>(Num<N>(), a); rec.template Build<F>(F(n)); } }; /** The identity transformation. */ class IdTrans { public: template<typename O, typename I> inline I constexpr Map(I a) const { return a; } }; /** A singleton for the identity transformation. */ constexpr IdTrans ID_TRANS{}; #endif
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/test.cpp
/********************************************************************** * Copyright (c) 2018,2021 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #include <algorithm> #include <cstdio> #include <limits> #include <random> #include <stdexcept> #include <string> #include <vector> #include "../include/minisketch.h" #include "util.h" namespace { uint64_t Combination(uint64_t n, uint64_t k) { if (n - k < k) k = n - k; uint64_t ret = 1; for (uint64_t i = 1; i <= k; ++i) { ret = (ret * n) / i; --n; } return ret; } /** Create a vector with Minisketch objects, one for each implementation. */ std::vector<Minisketch> CreateSketches(uint32_t bits, size_t capacity) { if (!Minisketch::BitsSupported(bits)) return {}; std::vector<Minisketch> ret; for (uint32_t impl = 0; impl <= Minisketch::MaxImplementation(); ++impl) { if (Minisketch::ImplementationSupported(bits, impl)) { CHECK(Minisketch::BitsSupported(bits)); ret.push_back(Minisketch(bits, impl, capacity)); CHECK((bool)ret.back()); } else { // implementation 0 must always work unless field size is disabled CHECK(impl != 0 || !Minisketch::BitsSupported(bits)); } } return ret; } /** Test properties by exhaustively decoding all 2**(bits*capacity) sketches * with specified capacity and bits. */ void TestExhaustive(uint32_t bits, size_t capacity) { auto sketches = CreateSketches(bits, capacity); if (sketches.empty()) return; auto sketches_rebuild = CreateSketches(bits, capacity); std::vector<unsigned char> serialized; std::vector<unsigned char> serialized_empty; std::vector<uint64_t> counts; //!< counts[i] = number of results with i elements std::vector<uint64_t> elements_0; //!< Result vector for elements for impl=0 std::vector<uint64_t> elements_other; //!< Result vector for elements for other impls std::vector<uint64_t> elements_too_small; //!< Result vector that's too small counts.resize(capacity + 1); serialized.resize(sketches[0].GetSerializedSize()); serialized_empty.resize(sketches[0].GetSerializedSize()); // Iterate over all (bits)-bit sketches with (capacity) syndromes. for (uint64_t x = 0; (x >> (bits * capacity)) == 0; ++x) { // Construct the serialization. for (size_t i = 0; i < serialized.size(); ++i) { serialized[i] = (x >> (i * 8)) & 0xFF; } // Compute all the solutions sketches[0].Deserialize(serialized); elements_0.resize(64); bool decodable_0 = sketches[0].Decode(elements_0); std::sort(elements_0.begin(), elements_0.end()); // Verify that decoding with other implementations agrees. for (size_t impl = 1; impl < sketches.size(); ++impl) { sketches[impl].Deserialize(serialized); elements_other.resize(64); bool decodable_other = sketches[impl].Decode(elements_other); CHECK(decodable_other == decodable_0); std::sort(elements_other.begin(), elements_other.end()); CHECK(elements_other == elements_0); } // If there are solutions: if (decodable_0) { if (!elements_0.empty()) { // Decoding with limit one less than the number of elements should fail. elements_too_small.resize(elements_0.size() - 1); for (size_t impl = 0; impl < sketches.size(); ++impl) { CHECK(!sketches[impl].Decode(elements_too_small)); } } // Reconstruct the sketch from the solutions. for (size_t impl = 0; impl < sketches.size(); ++impl) { // Clear the sketch. sketches_rebuild[impl].Deserialize(serialized_empty); // Load all decoded elements into it. for (uint64_t elem : elements_0) { CHECK(elem != 0); CHECK(elem >> bits == 0); sketches_rebuild[impl].Add(elem); } // Reserialize the result auto serialized_rebuild = sketches_rebuild[impl].Serialize(); // Compare CHECK(serialized == serialized_rebuild); // Count it if (impl == 0 && elements_0.size() <= capacity) ++counts[elements_0.size()]; } } } // Verify that the number of decodable sketches with given elements is expected. uint64_t mask = bits == 64 ? UINT64_MAX : (uint64_t{1} << bits) - 1; for (uint64_t i = 0; i <= capacity && (i & mask) == i; ++i) { CHECK(counts[i] == Combination(mask, i)); } } /** Test properties of sketches with random elements put in. */ void TestRandomized(uint32_t bits, size_t max_capacity, size_t iter) { std::random_device rnd; std::uniform_int_distribution<uint64_t> capacity_dist(0, std::min<uint64_t>(std::numeric_limits<uint64_t>::max() >> (64 - bits), max_capacity)); std::uniform_int_distribution<uint64_t> element_dist(1, std::numeric_limits<uint64_t>::max() >> (64 - bits)); std::uniform_int_distribution<uint64_t> rand64(0, std::numeric_limits<uint64_t>::max()); std::uniform_int_distribution<int64_t> size_offset_dist(-3, 3); std::vector<uint64_t> decode_0; std::vector<uint64_t> decode_other; std::vector<uint64_t> decode_temp; std::vector<uint64_t> elements; for (size_t i = 0; i < iter; ++i) { // Determine capacity, and construct Minisketch objects for all implementations. uint64_t capacity = capacity_dist(rnd); auto sketches = CreateSketches(bits, capacity); // Sanity checks if (sketches.empty()) return; for (size_t impl = 0; impl < sketches.size(); ++impl) { CHECK(sketches[impl].GetBits() == bits); CHECK(sketches[impl].GetCapacity() == capacity); CHECK(sketches[impl].GetSerializedSize() == sketches[0].GetSerializedSize()); } // Determine the number of elements, and create a vector to store them in. size_t element_count = std::max<int64_t>(0, std::max<int64_t>(0, capacity + size_offset_dist(rnd))); elements.resize(element_count); // Add the elements to all sketches for (size_t j = 0; j < element_count; ++j) { uint64_t elem = element_dist(rnd); CHECK(elem != 0); elements[j] = elem; for (auto& sketch : sketches) sketch.Add(elem); } // Remove pairs of duplicates in elements, as they cancel out. std::sort(elements.begin(), elements.end()); size_t real_element_count = element_count; for (size_t pos = 0; pos + 1 < elements.size(); ++pos) { if (elements[pos] == elements[pos + 1]) { real_element_count -= 2; // Set both elements to 0; afterwards we will move these to the end. elements[pos] = 0; elements[pos + 1] = 0; ++pos; } } if (real_element_count < element_count) { // Move all introduced zeroes (masking duplicates) to the end. std::sort(elements.begin(), elements.end(), [](uint64_t a, uint64_t b) { return a != b && (b == 0 || (a != 0 && a < b)); }); CHECK(elements[real_element_count] == 0); elements.resize(real_element_count); } // Create and compare serializations auto serialized_0 = sketches[0].Serialize(); for (size_t impl = 1; impl < sketches.size(); ++impl) { auto serialized_other = sketches[impl].Serialize(); CHECK(serialized_other == serialized_0); } // Deserialize and reserialize them for (size_t impl = 0; impl < sketches.size(); ++impl) { sketches[impl].Deserialize(serialized_0); auto reserialized = sketches[impl].Serialize(); CHECK(reserialized == serialized_0); } // Decode with limit set to the capacity, and compare results decode_0.resize(capacity); bool decodable_0 = sketches[0].Decode(decode_0); std::sort(decode_0.begin(), decode_0.end()); for (size_t impl = 1; impl < sketches.size(); ++impl) { decode_other.resize(capacity); bool decodable_other = sketches[impl].Decode(decode_other); CHECK(decodable_other == decodable_0); std::sort(decode_other.begin(), decode_other.end()); CHECK(decode_other == decode_0); } // If the result is decodable, it should also be decodable with limit // set to the actual number of elements, and not with one less. if (decodable_0) { for (auto& sketch : sketches) { decode_temp.resize(decode_0.size()); bool decodable = sketch.Decode(decode_temp); CHECK(decodable); std::sort(decode_temp.begin(), decode_temp.end()); CHECK(decode_temp == decode_0); if (!decode_0.empty()) { decode_temp.resize(decode_0.size() - 1); decodable = sketch.Decode(decode_temp); CHECK(!decodable); } } } // If the actual number of elements is not higher than the capacity, the // result should be decodable, and the result should match what we put in. if (real_element_count <= capacity) { CHECK(decodable_0); CHECK(decode_0 == elements); } } } void TestComputeFunctions() { for (uint32_t bits = 0; bits <= 256; ++bits) { for (uint32_t fpbits = 0; fpbits <= 512; ++fpbits) { std::vector<size_t> table_max_elements(1025); for (size_t capacity = 0; capacity <= 1024; ++capacity) { table_max_elements[capacity] = minisketch_compute_max_elements(bits, capacity, fpbits); // Exception for bits==0 if (bits == 0) CHECK(table_max_elements[capacity] == 0); // A sketch with capacity N cannot guarantee decoding more than N elements. CHECK(table_max_elements[capacity] <= capacity); // When asking for N bits of false positive protection, either no solution exists, or no more than ceil(N / bits) excess capacity should be needed. if (bits > 0) CHECK(table_max_elements[capacity] == 0 || capacity - table_max_elements[capacity] <= (fpbits + bits - 1) / bits); // Increasing capacity by one, if there is a solution, should always increment the max_elements by at least one as well. if (capacity > 0) CHECK(table_max_elements[capacity] == 0 || table_max_elements[capacity] > table_max_elements[capacity - 1]); } std::vector<size_t> table_capacity(513); for (size_t max_elements = 0; max_elements <= 512; ++max_elements) { table_capacity[max_elements] = minisketch_compute_capacity(bits, max_elements, fpbits); // Exception for bits==0 if (bits == 0) CHECK(table_capacity[max_elements] == 0); // To be able to decode N elements, capacity needs to be at least N. if (bits > 0) CHECK(table_capacity[max_elements] >= max_elements); // A sketch of N bits in total cannot have more than N bits of false positive protection; if (bits > 0) CHECK(bits * table_capacity[max_elements] >= fpbits); // When asking for N bits of false positive protection, no more than ceil(N / bits) excess capacity should be needed. if (bits > 0) CHECK(table_capacity[max_elements] - max_elements <= (fpbits + bits - 1) / bits); // Increasing max_elements by one can only increment the capacity by 0 or 1. if (max_elements > 0 && fpbits < 256) CHECK(table_capacity[max_elements] == table_capacity[max_elements - 1] || table_capacity[max_elements] == table_capacity[max_elements - 1] + 1); // Check round-tripping max_elements->capacity->max_elements (only a lower bound) CHECK(table_capacity[max_elements] <= 1024); CHECK(table_max_elements[table_capacity[max_elements]] == 0 || table_max_elements[table_capacity[max_elements]] >= max_elements); } for (size_t capacity = 0; capacity <= 512; ++capacity) { // Check round-tripping capacity->max_elements->capacity (exact, if it exists) CHECK(table_max_elements[capacity] <= 512); CHECK(table_max_elements[capacity] == 0 || table_capacity[table_max_elements[capacity]] == capacity); } } } } } // namespace int main(int argc, char** argv) { uint64_t test_complexity = 4; if (argc > 1) { size_t len = 0; std::string arg{argv[1]}; try { test_complexity = 0; long long complexity = std::stoll(arg, &len); if (complexity >= 1 && len == arg.size() && ((uint64_t)complexity <= std::numeric_limits<uint64_t>::max() >> 10)) { test_complexity = complexity; } } catch (const std::logic_error&) {} if (test_complexity == 0) { fprintf(stderr, "Invalid complexity specified: '%s'\n", arg.c_str()); return 1; } } #ifdef MINISKETCH_VERIFY const char* mode = " in verify mode"; #else const char* mode = ""; #endif printf("Running libminisketch tests%s with complexity=%llu\n", mode, (unsigned long long)test_complexity); TestComputeFunctions(); for (unsigned j = 2; j <= 64; ++j) { TestRandomized(j, 8, (test_complexity << 10) / j); TestRandomized(j, 128, (test_complexity << 7) / j); TestRandomized(j, 4096, test_complexity / j); } // Test capacity==0 together with all field sizes, and then // all combinations of bits and capacity up to a certain bits*capacity, // depending on test_complexity. for (int weight = 0; weight <= 40; ++weight) { for (int bits = 2; weight == 0 ? bits <= 64 : (bits <= 32 && bits <= weight); ++bits) { int capacity = weight / bits; if (capacity * bits != weight) continue; TestExhaustive(bits, capacity); } if (weight >= 16 && test_complexity >> (weight - 16) == 0) break; } printf("All tests successful.\n"); return 0; }
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/false_positives.h
/********************************************************************** * Copyright (c) 2020 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_FALSE_POSITIVES_H_ #define _MINISKETCH_FALSE_POSITIVES_H_ #include "util.h" #include "int_utils.h" #include <stdint.h> namespace { /** Compute floor(log2(x!)), exactly up to x=57; an underestimate up to x=2^32-1. */ uint64_t Log2Factorial(uint32_t x) { //! Values of floor(106*log2(1 + i/32)) for i=0..31 static constexpr uint8_t T[32] = { 0, 4, 9, 13, 18, 22, 26, 30, 34, 37, 41, 45, 48, 52, 55, 58, 62, 65, 68, 71, 74, 77, 80, 82, 85, 88, 90, 93, 96, 98, 101, 103 }; int bits = CountBits(x, 32); // Compute an (under)estimate of floor(106*log2(x)). // This works by relying on floor(log2(x)) = countbits(x)-1, and adding // precision using the top 6 bits of x (the highest one of which is always // one). unsigned l2_106 = 106 * (bits - 1) + T[((x << (32 - bits)) >> 26) & 31]; // Based on Stirling approximation for log2(x!): // log2(x!) = log(x!) / log(2) // = ((x + 1/2) * log(x) - x + log(2*pi)/2 + ...) / log(2) // = (x + 1/2) * log2(x) - x/log(2) + log2(2*pi)/2 + ... // = 1/2*(2*x+1)*log2(x) - (1/log(2))*x + log2(2*pi)/2 + ... // = 1/212*(2*x+1)*(106*log2(x)) + (-1/log(2))*x + log2(2*pi)/2 + ... // where 418079/88632748 is exactly 1/212 // -127870026/88632748 is slightly less than -1/log(2) // 117504694/88632748 is less than log2(2*pi)/2 // A correction term is only needed for x < 3. // // See doc/log2_factorial.sage for how these constants were obtained. return (418079 * (2 * uint64_t{x} + 1) * l2_106 - 127870026 * uint64_t{x} + 117504694 + 88632748 * (x < 3)) / 88632748; } /** Compute floor(log2(2^(bits * capacity) / sum((2^bits - 1) choose k, k=0..capacity))), for bits>1 * * See doc/gen_basefpbits.sage for how the tables were obtained. */ uint64_t BaseFPBits(uint32_t bits, uint32_t capacity) { // Correction table for low bits/capacities static constexpr uint8_t ADD5[] = {1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12}; static constexpr uint8_t ADD6[] = {1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 8, 8, 10, 10, 11, 12, 12, 13, 14, 15, 15, 16, 17, 18, 18, 19, 20, 20, 21, 21, 22, 22, 23, 23, 23, 24, 24, 24, 24}; static constexpr uint8_t ADD7[] = {1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 7, 8, 9, 9, 9, 10, 11, 11, 12, 12, 13, 13, 15, 15, 15, 16, 17, 17, 18, 19, 20, 20}; static constexpr uint8_t ADD8[] = {1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 9, 9}; static constexpr uint8_t ADD9[] = {1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 3, 2, 3, 3, 3, 3, 4, 3, 3, 4, 4, 4, 4}; if (capacity == 0) return 0; uint64_t ret = 0; if (bits < 32 && capacity >= (1U << bits)) { ret = uint64_t{bits} * (capacity - (1U << bits) + 1); capacity = (1U << bits) - 1; } ret += Log2Factorial(capacity); switch (bits) { case 2: return ret + (capacity <= 2 ? 0 : 1); case 3: return ret + (capacity <= 2 ? 0 : (0x2a5 >> 2 * (capacity - 3)) & 3); case 4: return ret + (capacity <= 3 ? 0 : (0xb6d91a449 >> 3 * (capacity - 4)) & 7); case 5: return ret + (capacity <= 4 ? 0 : ADD5[capacity - 5]); case 6: return ret + (capacity <= 4 ? 0 : capacity > 54 ? 25 : ADD6[capacity - 5]); case 7: return ret + (capacity <= 4 ? 0 : capacity > 57 ? 21 : ADD7[capacity - 5]); case 8: return ret + (capacity <= 9 ? 0 : capacity > 56 ? 10 : ADD8[capacity - 10]); case 9: return ret + (capacity <= 11 ? 0 : capacity > 54 ? 5 : ADD9[capacity - 12]); case 10: return ret + (capacity <= 21 ? 0 : capacity > 50 ? 2 : (0x1a6665545555041 >> 2 * (capacity - 22)) & 3); case 11: return ret + (capacity <= 21 ? 0 : capacity > 45 ? 1 : (0x5b3dc1 >> (capacity - 22)) & 1); case 12: return ret + (capacity <= 21 ? 0 : capacity > 57 ? 0 : (0xe65522041 >> (capacity - 22)) & 1); case 13: return ret + (capacity <= 27 ? 0 : capacity > 55 ? 0 : (0x8904081 >> (capacity - 28)) & 1); case 14: return ret + (capacity <= 47 ? 0 : capacity > 48 ? 0 : 1); default: return ret; } } size_t ComputeCapacity(uint32_t bits, size_t max_elements, uint32_t fpbits) { if (bits == 0) return 0; uint64_t base_fpbits = BaseFPBits(bits, max_elements); // The fpbits provided by the base max_elements==capacity case are sufficient. if (base_fpbits >= fpbits) return max_elements; // Otherwise, increment capacity by ceil(fpbits / bits) beyond that. return max_elements + (fpbits - base_fpbits + bits - 1) / bits; } size_t ComputeMaxElements(uint32_t bits, size_t capacity, uint32_t fpbits) { if (bits == 0) return 0; // Start with max_elements=capacity, and decrease max_elements until the corresponding capacity is capacity. size_t max_elements = capacity; while (true) { size_t capacity_for_max_elements = ComputeCapacity(bits, max_elements, fpbits); CHECK_SAFE(capacity_for_max_elements >= capacity); if (capacity_for_max_elements <= capacity) return max_elements; size_t adjust = capacity_for_max_elements - capacity; // Decrementing max_elements by N will at most decrement the corresponding capacity by N. // As the observed capacity is adjust too high, we can safely decrease max_elements by adjust. // If that brings us into negative max_elements territory, no solution exists and we return 0. if (max_elements < adjust) return 0; max_elements -= adjust; } } } // namespace #endif
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/sketch_impl.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_SKETCH_IMPL_H_ #define _MINISKETCH_SKETCH_IMPL_H_ #include <random> #include "util.h" #include "sketch.h" #include "int_utils.h" /** Compute the remainder of a polynomial division of val by mod, putting the result in mod. */ template<typename F> void PolyMod(const std::vector<typename F::Elem>& mod, std::vector<typename F::Elem>& val, const F& field) { size_t modsize = mod.size(); CHECK_SAFE(modsize > 0 && mod.back() == 1); if (val.size() < modsize) return; CHECK_SAFE(val.back() != 0); while (val.size() >= modsize) { auto term = val.back(); val.pop_back(); if (term != 0) { typename F::Multiplier mul(field, term); for (size_t x = 0; x < mod.size() - 1; ++x) { val[val.size() - modsize + 1 + x] ^= mul(mod[x]); } } } while (val.size() > 0 && val.back() == 0) val.pop_back(); } /** Compute the quotient of a polynomial division of val by mod, putting the quotient in div and the remainder in val. */ template<typename F> void DivMod(const std::vector<typename F::Elem>& mod, std::vector<typename F::Elem>& val, std::vector<typename F::Elem>& div, const F& field) { size_t modsize = mod.size(); CHECK_SAFE(mod.size() > 0 && mod.back() == 1); if (val.size() < mod.size()) { div.clear(); return; } CHECK_SAFE(val.back() != 0); div.resize(val.size() - mod.size() + 1); while (val.size() >= modsize) { auto term = val.back(); div[val.size() - modsize] = term; val.pop_back(); if (term != 0) { typename F::Multiplier mul(field, term); for (size_t x = 0; x < mod.size() - 1; ++x) { val[val.size() - modsize + 1 + x] ^= mul(mod[x]); } } } } /** Make a polynomial monic. */ template<typename F> typename F::Elem MakeMonic(std::vector<typename F::Elem>& a, const F& field) { CHECK_SAFE(a.back() != 0); if (a.back() == 1) return 0; auto inv = field.Inv(a.back()); typename F::Multiplier mul(field, inv); a.back() = 1; for (size_t i = 0; i < a.size() - 1; ++i) { a[i] = mul(a[i]); } return inv; } /** Compute the GCD of two polynomials, putting the result in a. b will be cleared. */ template<typename F> void GCD(std::vector<typename F::Elem>& a, std::vector<typename F::Elem>& b, const F& field) { if (a.size() < b.size()) std::swap(a, b); while (b.size() > 0) { if (b.size() == 1) { a.resize(1); a[0] = 1; return; } MakeMonic(b, field); PolyMod(b, a, field); std::swap(a, b); } } /** Square a polynomial. */ template<typename F> void Sqr(std::vector<typename F::Elem>& poly, const F& field) { if (poly.size() == 0) return; poly.resize(poly.size() * 2 - 1); for (int x = poly.size() - 1; x >= 0; --x) { poly[x] = (x & 1) ? 0 : field.Sqr(poly[x / 2]); } } /** Compute the trace map of (param*x) modulo mod, putting the result in out. */ template<typename F> void TraceMod(const std::vector<typename F::Elem>& mod, std::vector<typename F::Elem>& out, const typename F::Elem& param, const F& field) { out.reserve(mod.size() * 2); out.resize(2); out[0] = 0; out[1] = param; for (int i = 0; i < field.Bits() - 1; ++i) { Sqr(out, field); if (out.size() < 2) out.resize(2); out[1] = param; PolyMod(mod, out, field); } } /** One step of the root finding algorithm; finds roots of stack[pos] and adds them to roots. Stack elements >= pos are destroyed. * * It operates on a stack of polynomials. The polynomial operated on is `stack[pos]`, where elements of `stack` with index higher * than `pos` are used as scratch space. * * `stack[pos]` is assumed to be square-free polynomial. If `fully_factorizable` is true, it is also assumed to have no irreducible * factors of degree higher than 1. * This implements the Berlekamp trace algorithm, plus an efficient test to fail fast in * case the polynomial cannot be fully factored. */ template<typename F> bool RecFindRoots(std::vector<std::vector<typename F::Elem>>& stack, size_t pos, std::vector<typename F::Elem>& roots, bool fully_factorizable, int depth, typename F::Elem randv, const F& field) { auto& ppoly = stack[pos]; // We assert ppoly.size() > 1 (instead of just ppoly.size() > 0) to additionally exclude // constants polynomials because // - ppoly is not constant initially (this is ensured by FindRoots()), and // - we never recurse on a constant polynomial. CHECK_SAFE(ppoly.size() > 1 && ppoly.back() == 1); /* 1st degree input: constant term is the root. */ if (ppoly.size() == 2) { roots.push_back(ppoly[0]); return true; } /* 2nd degree input: use direct quadratic solver. */ if (ppoly.size() == 3) { CHECK_RETURN(ppoly[1] != 0, false); // Equations of the form (x^2 + a) have two identical solutions; contradicts square-free assumption. */ auto input = field.Mul(ppoly[0], field.Sqr(field.Inv(ppoly[1]))); auto root = field.Qrt(input); if ((field.Sqr(root) ^ root) != input) { CHECK_SAFE(!fully_factorizable); return false; // No root found. } auto sol = field.Mul(root, ppoly[1]); roots.push_back(sol); roots.push_back(sol ^ ppoly[1]); return true; } /* 3rd degree input and more: recurse further. */ if (pos + 3 > stack.size()) { // Allocate memory if necessary. stack.resize((pos + 3) * 2); } auto& poly = stack[pos]; auto& tmp = stack[pos + 1]; auto& trace = stack[pos + 2]; trace.clear(); tmp.clear(); for (int iter = 0;; ++iter) { // Compute the polynomial (trace(x*randv) mod poly(x)) symbolically, // and put the result in `trace`. TraceMod(poly, trace, randv, field); if (iter >= 1 && !fully_factorizable) { // If the polynomial cannot be factorized completely (it has an // irreducible factor of degree higher than 1), we want to avoid // the case where this is only detected after trying all BITS // independent split attempts fail (see the assert below). // // Observe that if we call y = randv*x, it is true that: // // trace = y + y^2 + y^4 + y^8 + ... y^(FIELDSIZE/2) mod poly // // Due to the Frobenius endomorphism, this means: // // trace^2 = y^2 + y^4 + y^8 + ... + y^FIELDSIZE mod poly // // Or, adding them up: // // trace + trace^2 = y + y^FIELDSIZE mod poly. // = randv*x + randv^FIELDSIZE*x^FIELDSIZE // = randv*x + randv*x^FIELDSIZE // = randv*(x + x^FIELDSIZE). // (all mod poly) // // x + x^FIELDSIZE is the polynomial which has every field element // as root once. Whenever x + x^FIELDSIZE is multiple of poly, // this means it only has unique first degree factors. The same // holds for its constant multiple randv*(x + x^FIELDSIZE) = // trace + trace^2. // // We use this test to quickly verify whether the polynomial is // fully factorizable after already having computed a trace. // We don't invoke it immediately; only when splitting has failed // at least once, which avoids it for most polynomials that are // fully factorizable (or at least pushes the test down the // recursion to factors which are smaller and thus faster). tmp = trace; Sqr(tmp, field); for (size_t i = 0; i < trace.size(); ++i) { tmp[i] ^= trace[i]; } while (tmp.size() && tmp.back() == 0) tmp.pop_back(); PolyMod(poly, tmp, field); // Whenever the test fails, we can immediately abort the root // finding. Whenever it succeeds, we can remember and pass down // the information that it is in fact fully factorizable, avoiding // the need to run the test again. if (tmp.size() != 0) return false; fully_factorizable = true; } if (fully_factorizable) { // Every succesful iteration of this algorithm splits the input // polynomial further into buckets, each corresponding to a subset // of 2^(BITS-depth) roots. If after depth splits the degree of // the polynomial is >= 2^(BITS-depth), something is wrong. CHECK_RETURN(field.Bits() - depth >= std::numeric_limits<decltype(poly.size())>::digits || (poly.size() - 2) >> (field.Bits() - depth) == 0, false); } depth++; // In every iteration we multiply randv by 2. As a result, the set // of randv values forms a GF(2)-linearly independent basis of splits. randv = field.Mul2(randv); tmp = poly; GCD(trace, tmp, field); if (trace.size() != poly.size() && trace.size() > 1) break; } MakeMonic(trace, field); DivMod(trace, poly, tmp, field); // At this point, the stack looks like [... (poly) tmp trace], and we want to recursively // find roots of trace and tmp (= poly/trace). As we don't care about poly anymore, move // trace into its position first. std::swap(poly, trace); // Now the stack is [... (trace) tmp ...]. First we factor tmp (at pos = pos+1), and then // we factor trace (at pos = pos). if (!RecFindRoots(stack, pos + 1, roots, fully_factorizable, depth, randv, field)) return false; // The stack position pos contains trace, the polynomial with all of poly's roots which (after // multiplication with randv) have trace 0. This is never the case for irreducible factors // (which always end up in tmp), so we can set fully_factorizable to true when recursing. bool ret = RecFindRoots(stack, pos, roots, true, depth, randv, field); // Because of the above, recursion can never fail here. CHECK_SAFE(ret); return ret; } /** Returns the roots of a fully factorizable polynomial * * This function assumes that the input polynomial is square-free * and not the zero polynomial (represented by an empty vector). * * In case the square-free polynomial is not fully factorizable, i.e., it * has fewer roots than its degree, the empty vector is returned. */ template<typename F> std::vector<typename F::Elem> FindRoots(const std::vector<typename F::Elem>& poly, typename F::Elem basis, const F& field) { std::vector<typename F::Elem> roots; CHECK_RETURN(poly.size() != 0, {}); CHECK_RETURN(basis != 0, {}); if (poly.size() == 1) return roots; // No roots when the polynomial is a constant. roots.reserve(poly.size() - 1); std::vector<std::vector<typename F::Elem>> stack = {poly}; // Invoke the recursive factorization algorithm. if (!RecFindRoots(stack, 0, roots, false, 0, basis, field)) { // Not fully factorizable. return {}; } CHECK_RETURN(poly.size() - 1 == roots.size(), {}); return roots; } template<typename F> std::vector<typename F::Elem> BerlekampMassey(const std::vector<typename F::Elem>& syndromes, size_t max_degree, const F& field) { std::vector<typename F::Multiplier> table; std::vector<typename F::Elem> current, prev, tmp; current.reserve(syndromes.size() / 2 + 1); prev.reserve(syndromes.size() / 2 + 1); tmp.reserve(syndromes.size() / 2 + 1); current.resize(1); current[0] = 1; prev.resize(1); prev[0] = 1; typename F::Elem b = 1, b_inv = 1; bool b_have_inv = true; table.reserve(syndromes.size()); for (size_t n = 0; n != syndromes.size(); ++n) { table.emplace_back(field, syndromes[n]); auto discrepancy = syndromes[n]; for (size_t i = 1; i < current.size(); ++i) discrepancy ^= table[n - i](current[i]); if (discrepancy != 0) { int x = n + 1 - (current.size() - 1) - (prev.size() - 1); if (!b_have_inv) { b_inv = field.Inv(b); b_have_inv = true; } bool swap = 2 * (current.size() - 1) <= n; if (swap) { if (prev.size() + x - 1 > max_degree) return {}; // We'd exceed maximum degree tmp = current; current.resize(prev.size() + x); } typename F::Multiplier mul(field, field.Mul(discrepancy, b_inv)); for (size_t i = 0; i < prev.size(); ++i) current[i + x] ^= mul(prev[i]); if (swap) { std::swap(prev, tmp); b = discrepancy; b_have_inv = false; } } } CHECK_RETURN(current.size() && current.back() != 0, {}); return current; } template<typename F> std::vector<typename F::Elem> ReconstructAllSyndromes(const std::vector<typename F::Elem>& odd_syndromes, const F& field) { std::vector<typename F::Elem> all_syndromes; all_syndromes.resize(odd_syndromes.size() * 2); for (size_t i = 0; i < odd_syndromes.size(); ++i) { all_syndromes[i * 2] = odd_syndromes[i]; all_syndromes[i * 2 + 1] = field.Sqr(all_syndromes[i]); } return all_syndromes; } template<typename F> void AddToOddSyndromes(std::vector<typename F::Elem>& osyndromes, typename F::Elem data, const F& field) { auto sqr = field.Sqr(data); typename F::Multiplier mul(field, sqr); for (auto& osyndrome : osyndromes) { osyndrome ^= data; data = mul(data); } } template<typename F> std::vector<typename F::Elem> FullDecode(const std::vector<typename F::Elem>& osyndromes, const F& field) { auto asyndromes = ReconstructAllSyndromes<typename F::Elem>(osyndromes, field); auto poly = BerlekampMassey(asyndromes, field); std::reverse(poly.begin(), poly.end()); return FindRoots(poly, field); } template<typename F> class SketchImpl final : public Sketch { const F m_field; std::vector<typename F::Elem> m_syndromes; typename F::Elem m_basis; public: template<typename... Args> SketchImpl(int implementation, int bits, const Args&... args) : Sketch(implementation, bits), m_field(args...) { std::random_device rng; std::uniform_int_distribution<uint64_t> dist; m_basis = m_field.FromSeed(dist(rng)); } size_t Syndromes() const override { return m_syndromes.size(); } void Init(int count) override { m_syndromes.assign(count, 0); } void Add(uint64_t val) override { auto elem = m_field.FromUint64(val); AddToOddSyndromes(m_syndromes, elem, m_field); } void Serialize(unsigned char* ptr) const override { BitWriter writer(ptr); for (const auto& val : m_syndromes) { m_field.Serialize(writer, val); } writer.Flush(); } void Deserialize(const unsigned char* ptr) override { BitReader reader(ptr); for (auto& val : m_syndromes) { val = m_field.Deserialize(reader); } } int Decode(int max_count, uint64_t* out) const override { auto all_syndromes = ReconstructAllSyndromes(m_syndromes, m_field); auto poly = BerlekampMassey(all_syndromes, max_count, m_field); if (poly.size() == 0) return -1; if (poly.size() == 1) return 0; if ((int)poly.size() > 1 + max_count) return -1; std::reverse(poly.begin(), poly.end()); auto roots = FindRoots(poly, m_basis, m_field); if (roots.size() == 0) return -1; for (const auto& root : roots) { *(out++) = m_field.ToUint64(root); } return roots.size(); } size_t Merge(const Sketch* other_sketch) override { // Sad cast. This is safe only because the caller code in minisketch.cpp checks // that implementation and field size match. const SketchImpl* other = static_cast<const SketchImpl*>(other_sketch); m_syndromes.resize(std::min(m_syndromes.size(), other->m_syndromes.size())); for (size_t i = 0; i < m_syndromes.size(); ++i) { m_syndromes[i] ^= other->m_syndromes[i]; } return m_syndromes.size(); } void SetSeed(uint64_t seed) override { if (seed == (uint64_t)-1) { m_basis = 1; } else { m_basis = m_field.FromSeed(seed); } } }; #endif
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/util.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_UTIL_H_ #define _MINISKETCH_UTIL_H_ #ifdef MINISKETCH_VERIFY #include <stdio.h> #endif #if !defined(__GNUC_PREREQ) # if defined(__GNUC__)&&defined(__GNUC_MINOR__) # define __GNUC_PREREQ(_maj,_min) \ ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min)) # else # define __GNUC_PREREQ(_maj,_min) 0 # endif #endif #if __GNUC_PREREQ(3, 0) #define EXPECT(x,c) __builtin_expect((x),(c)) #else #define EXPECT(x,c) (x) #endif /* Assertion macros */ /** * Unconditional failure on condition failure. * Primarily used in testing harnesses. */ #define CHECK(cond) do { \ if (EXPECT(!(cond), 0)) { \ fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, "Check condition failed: " #cond); \ abort(); \ } \ } while(0) /** * Check macro that does nothing in normal non-verify builds but crashes in verify builds. * This is used to test conditions at runtime that should always be true, but are either * expensive to test or in locations where returning on failure would be messy. */ #ifdef MINISKETCH_VERIFY #define CHECK_SAFE(cond) CHECK(cond) #else #define CHECK_SAFE(cond) #endif /** * Check a condition and return on failure in non-verify builds, crash in verify builds. * Used for inexpensive conditions which believed to be always true in locations where * a graceful exit is possible. */ #ifdef MINISKETCH_VERIFY #define CHECK_RETURN(cond, rvar) do { \ if (EXPECT(!(cond), 0)) { \ fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, "Check condition failed: " #cond); \ abort(); \ return rvar; /* Does nothing, but causes compile to warn on incorrect return types. */ \ } \ } while(0) #else #define CHECK_RETURN(cond, rvar) do { \ if (EXPECT(!(cond), 0)) { \ return rvar; \ } \ } while(0) #endif #endif
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/sketch.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_STATE_H_ #define _MINISKETCH_STATE_H_ #include <stdint.h> #include <stdlib.h> /** Abstract class for internal representation of a minisketch object. */ class Sketch { uint64_t m_canary; const int m_implementation; const int m_bits; public: Sketch(int implementation, int bits) : m_implementation(implementation), m_bits(bits) {} void Ready() { m_canary = 0x6d496e536b65LU; } void Check() const { if (m_canary != 0x6d496e536b65LU) abort(); } void UnReady() { m_canary = 1; } int Implementation() const { return m_implementation; } int Bits() const { return m_bits; } virtual ~Sketch() {} virtual size_t Syndromes() const = 0; virtual void Init(int syndromes) = 0; virtual void Add(uint64_t element) = 0; virtual void Serialize(unsigned char*) const = 0; virtual void Deserialize(const unsigned char*) = 0; virtual size_t Merge(const Sketch* other_sketch) = 0; virtual void SetSeed(uint64_t seed) = 0; virtual int Decode(int max_count, uint64_t* roots) const = 0; }; #endif
0
bitcoin/src/minisketch
bitcoin/src/minisketch/src/bench.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #include "../include/minisketch.h" #include <string.h> #include <memory> #include <vector> #include <chrono> #include <random> #include <set> #include <algorithm> int main(int argc, char** argv) { if (argc < 1 || argc > 4) { printf("Usage: %s [syndromes=150] [errors=syndromes] [iters=10]\n", argv[0]); return 1; } int syndromes = argc > 1 ? strtoul(argv[1], NULL, 10) : 150; int errors = argc > 2 ? strtoul(argv[2], NULL, 10) : syndromes; int iters = argc > 3 ? strtoul(argv[3], NULL, 10) : 10; if (syndromes < 0 || syndromes > 1000000) { printf("Number of syndromes (%i) out of range 0..1000000\n", syndromes); return 1; } if (errors < 0) { printf("Number of errors (%i) is negative(%i)\n", errors, syndromes); return 1; } if (iters < 0 || iters > 1000000000) { printf("Number of iterations (%i) out of range 0..1000000000\n", iters); return 1; } uint32_t max_impl = minisketch_implementation_max(); for (int bits = 2; bits <= 64; ++bits) { if (errors > pow(2.0, bits - 1)) continue; if (!minisketch_bits_supported(bits)) continue; printf("recover[ms]\t% 3i\t", bits); for (uint32_t impl = 0; impl <= max_impl; ++impl) { std::vector<minisketch*> states; std::vector<uint64_t> roots(2 * syndromes); std::random_device rng; std::uniform_int_distribution<uint64_t> dist(1, (uint64_t(1) << bits) - 1); states.resize(iters); std::vector<double> benches; benches.reserve(iters); for (int i = 0; i < iters; ++i) { states[i] = minisketch_create(bits, impl, syndromes); if (!states[i]) break; std::set<uint64_t> done; for (int j = 0; j < errors; ++j) { uint64_t r; do { r = dist(rng); } while (done.count(r)); done.insert(r); minisketch_add_uint64(states[i], r); } } if (!states[0]) { printf(" -\t"); } else { for (auto& state : states) { auto start = std::chrono::steady_clock::now(); minisketch_decode(state, 2 * syndromes, roots.data()); auto stop = std::chrono::steady_clock::now(); std::chrono::duration<double> dur(stop - start); benches.push_back(dur.count()); } std::sort(benches.begin(), benches.end()); printf("% 10.5f\t", benches[0] * 1000.0); } for (auto& state : states) { minisketch_destroy(state); } } printf("\n"); printf("create[ns]\t% 3i\t", bits); for (uint32_t impl = 0; impl <= max_impl; ++impl) { std::vector<minisketch*> states; std::random_device rng; std::uniform_int_distribution<uint64_t> dist; std::vector<uint64_t> data; data.resize(errors * 10); states.resize(iters); std::vector<double> benches; benches.reserve(iters); for (int i = 0; i < iters; ++i) { states[i] = minisketch_create(bits, impl, syndromes); } for (size_t i = 0; i < data.size(); ++i) { data[i] = dist(rng); } if (!states[0]) { printf(" -\t"); } else { for (auto& state : states) { auto start = std::chrono::steady_clock::now(); for (auto val : data) { minisketch_add_uint64(state, val); } auto stop = std::chrono::steady_clock::now(); std::chrono::duration<double> dur(stop - start); benches.push_back(dur.count()); } std::sort(benches.begin(), benches.end()); printf("% 10.5f\t", benches[0] * 1000000000.0 / data.size() / syndromes); } for (auto& state : states) { minisketch_destroy(state); } } printf("\n"); } return 0; }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_5bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_5) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_33 // 33 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5> StatTable33; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable33; constexpr StatTable33 SQR_TABLE_33({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x802, 0x2008, 0x8020, 0x20080, 0x80200, 0x200800, 0x802000, 0x2008000, 0x8020000, 0x20080000, 0x80200000, 0x800401, 0x2001004, 0x8004010, 0x20010040, 0x80040100}); constexpr StatTable33 QRT_TABLE_33({0xba504dd4, 0x1e2798ef2, 0x1e2798ef0, 0x6698a4ec, 0x1e2798ef4, 0x1c7f1bef0, 0x6698a4e4, 0x16da1b384, 0x1e2798ee4, 0x661ca6ec, 0x1c7f1bed0, 0x1483b87a6, 0x6698a4a4, 0x800000, 0x16da1b304, 0x1a185101c, 0x1e2798fe4, 0xaa400954, 0x661ca4ec, 0x667caeec, 0x1c7f1bad0, 0x400800, 0x1483b8fa6, 0, 0x6698b4a4, 0x1c61da4b8, 0x802000, 0x16e5dadec, 0x16da1f304, 0x62fc8eec, 0x1a185901c, 0x1661da5ec, 0x1e2788fe4}); typedef Field<uint64_t, 33, 1025, StatTable33, DynTable33, &SQR_TABLE_33, &QRT_TABLE_33> Field33; #endif #ifdef ENABLE_FIELD_INT_34 // 34 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5> StatTable34; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable34; constexpr StatTable34 SQR_TABLE_34({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x81, 0x204, 0x810, 0x2040, 0x8100, 0x20400, 0x81000, 0x204000, 0x810000, 0x2040000, 0x8100000, 0x20400000, 0x81000000, 0x204000000, 0x10000102, 0x40000408, 0x100001020}); constexpr StatTable34 QRT_TABLE_34({0x2f973a1f6, 0x40202, 0x40200, 0x348102060, 0x40204, 0x8000420, 0x348102068, 0x1092195c8, 0x40214, 0x3f6881b6e, 0x8000400, 0x3f810383e, 0x348102028, 0x340002068, 0x109219548, 0x24015a774, 0x40314, 0x3f050343e, 0x3f688196e, 0x3f81c3a3a, 0x8000000, 0x24031a560, 0x3f810303e, 0xb08c1a12, 0x348103028, 0xb2881906, 0x340000068, 0, 0x10921d548, 0x2e131e576, 0x240152774, 0x18921d55e, 0x50314, 0x14015271c}); typedef Field<uint64_t, 34, 129, StatTable34, DynTable34, &SQR_TABLE_34, &QRT_TABLE_34> Field34; #endif #ifdef ENABLE_FIELD_INT_35 // 35 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5> StatTable35; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable35; constexpr StatTable35 SQR_TABLE_35({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0xa, 0x28, 0xa0, 0x280, 0xa00, 0x2800, 0xa000, 0x28000, 0xa0000, 0x280000, 0xa00000, 0x2800000, 0xa000000, 0x28000000, 0xa0000000, 0x280000000, 0x200000005}); constexpr StatTable35 QRT_TABLE_35({0x5c2038114, 0x2bf547ee8, 0x2bf547eea, 0x2bf1074e8, 0x2bf547eee, 0x1883d0736, 0x2bf1074e0, 0x100420, 0x2bf547efe, 0x400800, 0x1883d0716, 0x5e90e4a0, 0x2bf1074a0, 0x4e70ac20, 0x1004a0, 0x2f060c880, 0x2bf547ffe, 0x37d55fffe, 0x400a00, 0x3372573de, 0x1883d0316, 0x700c20, 0x5e90eca0, 0x10604880, 0x2bf1064a0, 0x18f35377e, 0x4e708c20, 0x33f557ffe, 0x1044a0, 0x1bf557ffe, 0x2f0604880, 0x200000000, 0x2bf557ffe, 0, 0x37d57fffe}); typedef Field<uint64_t, 35, 5, StatTable35, DynTable35, &SQR_TABLE_35, &QRT_TABLE_35> Field35; #endif #ifdef ENABLE_FIELD_INT_36 // 36 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6> StatTable36; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable36; constexpr StatTable36 SQR_TABLE_36({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x201, 0x804, 0x2010, 0x8040, 0x20100, 0x80400, 0x201000, 0x804000, 0x2010000, 0x8040000, 0x20100000, 0x80400000, 0x201000000, 0x804000000, 0x10000402, 0x40001008, 0x100004020, 0x400010080}); constexpr StatTable36 QRT_TABLE_36({0x40200, 0x8b0526186, 0x8b0526184, 0x240001000, 0x8b0526180, 0xcb6894d94, 0x240001008, 0xdb6880c22, 0x8b0526190, 0x8000200, 0xcb6894db4, 0x500424836, 0x240001048, 0x406cb2834, 0xdb6880ca2, 0x241200008, 0x8b0526090, 0xdb05021a6, 0x8000000, 0xdb01829b2, 0xcb68949b4, 0x1001000, 0x500424036, 0x106116406, 0x240000048, 0xcb29968a4, 0x406cb0834, 0, 0xdb6884ca2, 0x110010516, 0x241208008, 0x430434520, 0x8b0536090, 0x41208040, 0xdb05221a6, 0xb6884d14}); typedef Field<uint64_t, 36, 513, StatTable36, DynTable36, &SQR_TABLE_36, &QRT_TABLE_36> Field36; #endif #ifdef ENABLE_FIELD_INT_37 // 37 bit field typedef RecLinTrans<uint64_t, 6, 6, 5, 5, 5, 5, 5> StatTable37; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable37; constexpr StatTable37 SQR_TABLE_37({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0xa6, 0x298, 0xa60, 0x2980, 0xa600, 0x29800, 0xa6000, 0x298000, 0xa60000, 0x2980000, 0xa600000, 0x29800000, 0xa6000000, 0x298000000, 0xa60000000, 0x980000053, 0x60000011f, 0x180000047c}); constexpr StatTable37 QRT_TABLE_37({0xa3c62e7ba, 0xdc7a0c16a, 0xdc7a0c168, 0x12f7484546, 0xdc7a0c16c, 0xa9803a20, 0x12f748454e, 0xda07064a4, 0xdc7a0c17c, 0x123908de8e, 0xa9803a00, 0x122a888a8e, 0x12f748450e, 0x6790add8, 0xda0706424, 0x12e0a0384c, 0xdc7a0c07c, 0xcb28a2c2, 0x123908dc8e, 0xd09f85e86, 0xa9803e00, 0x124d682b6e, 0x122a88828e, 0x1738711a, 0x12f748550e, 0x73035b8, 0x67908dd8, 0xa0702438, 0xda0702424, 0xe0a0b860, 0x12e0a0b84c, 0x1c7a1c060, 0xdc7a1c07c, 0, 0xcb2aa2c2, 0x100000002c, 0x12390cdc8e}); typedef Field<uint64_t, 37, 83, StatTable37, DynTable37, &SQR_TABLE_37, &QRT_TABLE_37> Field37; #endif #ifdef ENABLE_FIELD_INT_38 // 38 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5, 5> StatTable38; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable38; constexpr StatTable38 SQR_TABLE_38({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x63, 0x18c, 0x630, 0x18c0, 0x6300, 0x18c00, 0x63000, 0x18c000, 0x630000, 0x18c0000, 0x6300000, 0x18c00000, 0x63000000, 0x18c000000, 0x630000000, 0x18c0000000, 0x2300000063, 0xc0000014a, 0x3000000528}); constexpr StatTable38 QRT_TABLE_38({0x34b0ac6430, 0x2223262fa, 0x2223262f8, 0x35554405fe, 0x2223262fc, 0x355514098a, 0x35554405f6, 0x400840, 0x2223262ec, 0x1777726532, 0x35551409aa, 0x15c06fc0, 0x35554405b6, 0x1f5303fec, 0x4008c0, 0x236a21030, 0x2223263ec, 0x1a9008c00, 0x1777726732, 0x3692c60ab6, 0x3555140daa, 0x15556007ee, 0x15c067c0, 0x14a0b030f2, 0x35554415b6, 0x227c06d168, 0x1f5301fec, 0x16c3928fc2, 0x4048c0, 0x3a942c4c0, 0x236a29030, 0x1636a2902e, 0x2223363ec, 0x3a6e898276, 0x1a9028c00, 0x6de74eb2c, 0x1777766732, 0}); typedef Field<uint64_t, 38, 99, StatTable38, DynTable38, &SQR_TABLE_38, &QRT_TABLE_38> Field38; #endif #ifdef ENABLE_FIELD_INT_39 // 39 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5> StatTable39; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable39; constexpr StatTable39 SQR_TABLE_39({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x22, 0x88, 0x220, 0x880, 0x2200, 0x8800, 0x22000, 0x88000, 0x220000, 0x880000, 0x2200000, 0x8800000, 0x22000000, 0x88000000, 0x220000000, 0x880000000, 0x2200000000, 0x800000011, 0x2000000044}); constexpr StatTable39 QRT_TABLE_39({0x66b02a408c, 0x100420, 0x100422, 0x14206080, 0x100426, 0x5dccefab1c, 0x14206088, 0x9fc11e5b6, 0x100436, 0x5466bea62a, 0x5dccefab3c, 0x9aa110536, 0x142060c8, 0x54739ed6e2, 0x9fc11e536, 0xe7a82c080, 0x100536, 0x4002000, 0x5466bea42a, 0x6a4022000, 0x5dccefaf3c, 0x9e8118536, 0x9aa110d36, 0x5680e080, 0x142070c8, 0x7d293c5b6, 0x54739ef6e2, 0x8d680e080, 0x9fc11a536, 0x6d282c080, 0xe7a824080, 0x800000000, 0x110536, 0x2d680e080, 0x4022000, 0, 0x5466baa42a, 0x46b03a44aa, 0x6a40a2000}); typedef Field<uint64_t, 39, 17, StatTable39, DynTable39, &SQR_TABLE_39, &QRT_TABLE_39> Field39; #endif #ifdef ENABLE_FIELD_INT_40 // 40 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5> StatTable40; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable40; constexpr StatTable40 SQR_TABLE_40({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x39, 0xe4, 0x390, 0xe40, 0x3900, 0xe400, 0x39000, 0xe4000, 0x390000, 0xe40000, 0x3900000, 0xe400000, 0x39000000, 0xe4000000, 0x390000000, 0xe40000000, 0x3900000000, 0xe400000000, 0x900000004b, 0x400000015e}); constexpr StatTable40 QRT_TABLE_40({0x624b3cecc, 0xbc5c3f4c6, 0xbc5c3f4c4, 0xde1603e2c, 0xbc5c3f4c0, 0xaabec06cea, 0xde1603e24, 0x6cd9f724c2, 0xbc5c3f4d0, 0xcde1743818, 0xaabec06cca, 0xa138c314ca, 0xde1603e64, 0xaafc00f01a, 0x6cd9f72442, 0xcdca11bb4, 0xbc5c3f5d0, 0xa00002001a, 0xcde1743a18, 0xdf1407b90, 0xaabec068ca, 0xc043b482c8, 0xa138c31cca, 0xcb86977e3c, 0xde1602e64, 0x604596a326, 0xaafc00d01a, 0xcc1c165d0, 0x6cd9f76442, 0x673c94da26, 0xcdca19bb4, 0x67c0940a26, 0xbc5c2f5d0, 0xa4dca19bae, 0xa00000001a, 0x1bc5c2f5d0, 0xcde1703a18, 0, 0xdf1487b90, 0x8df1487b8a}); typedef Field<uint64_t, 40, 57, StatTable40, DynTable40, &SQR_TABLE_40, &QRT_TABLE_40> Field40; #endif } Sketch* ConstructGeneric5Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_33 case 33: return new SketchImpl<Field33>(implementation, 33); #endif #ifdef ENABLE_FIELD_INT_34 case 34: return new SketchImpl<Field34>(implementation, 34); #endif #ifdef ENABLE_FIELD_INT_35 case 35: return new SketchImpl<Field35>(implementation, 35); #endif #ifdef ENABLE_FIELD_INT_36 case 36: return new SketchImpl<Field36>(implementation, 36); #endif #ifdef ENABLE_FIELD_INT_37 case 37: return new SketchImpl<Field37>(implementation, 37); #endif #ifdef ENABLE_FIELD_INT_38 case 38: return new SketchImpl<Field38>(implementation, 38); #endif #ifdef ENABLE_FIELD_INT_39 case 39: return new SketchImpl<Field39>(implementation, 39); #endif #ifdef ENABLE_FIELD_INT_40 case 40: return new SketchImpl<Field40>(implementation, 40); #endif default: return nullptr; } }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_4bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_4) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_25 // 25 bit field typedef RecLinTrans<uint32_t, 5, 5, 5, 5, 5> StatTable25; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 3, 3, 3> DynTable25; constexpr StatTable25 SQR_TABLE_25({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x48000, 0x120000, 0x480000, 0x1200000, 0x800012}); constexpr StatTable25 QRT_TABLE_25({0, 0x482110, 0x482112, 0x1b3c3e6, 0x482116, 0x4960ae, 0x1b3c3ee, 0x4088, 0x482106, 0x58a726, 0x49608e, 0x5ce52e, 0x1b3c3ae, 0x2006, 0x4008, 0x1c1a8, 0x482006, 0x1e96488, 0x58a526, 0x400000, 0x49648e, 0x1800006, 0x5ced2e, 0xb3d3a8, 0x1b3d3ae}); typedef Field<uint32_t, 25, 9, StatTable25, DynTable25, &SQR_TABLE_25, &QRT_TABLE_25> Field25; #endif #ifdef ENABLE_FIELD_INT_26 // 26 bit field typedef RecLinTrans<uint32_t, 6, 5, 5, 5, 5> StatTable26; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 3, 3> DynTable26; constexpr StatTable26 SQR_TABLE_26({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x1b, 0x6c, 0x1b0, 0x6c0, 0x1b00, 0x6c00, 0x1b000, 0x6c000, 0x1b0000, 0x6c0000, 0x1b00000, 0x2c0001b, 0x300005a}); constexpr StatTable26 QRT_TABLE_26({0x217b530, 0x2ae82a8, 0x2ae82aa, 0x2001046, 0x2ae82ae, 0x2de032e, 0x200104e, 0x70c10c, 0x2ae82be, 0x20151f2, 0x2de030e, 0xbc1400, 0x200100e, 0x178570, 0x70c18c, 0x2ae4232, 0x2ae83be, 0x211d742, 0x20153f2, 0x21f54f2, 0x2de070e, 0x5e0700, 0xbc1c00, 0x3abb97e, 0x200000e, 0}); typedef Field<uint32_t, 26, 27, StatTable26, DynTable26, &SQR_TABLE_26, &QRT_TABLE_26> Field26; #endif #ifdef ENABLE_FIELD_INT_27 // 27 bit field typedef RecLinTrans<uint32_t, 6, 6, 5, 5, 5> StatTable27; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 4, 3> DynTable27; constexpr StatTable27 SQR_TABLE_27({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x4e, 0x138, 0x4e0, 0x1380, 0x4e00, 0x13800, 0x4e000, 0x138000, 0x4e0000, 0x1380000, 0x4e00000, 0x380004e, 0x600011f}); constexpr StatTable27 QRT_TABLE_27({0x6bf0530, 0x2be4496, 0x2be4494, 0x2bf0522, 0x2be4490, 0x1896cca, 0x2bf052a, 0x408a, 0x2be4480, 0x368ae72, 0x1896cea, 0x18d2ee0, 0x2bf056a, 0x1c76d6a, 0x400a, 0x336e9f8, 0x2be4580, 0x36baf12, 0x368ac72, 0x430360, 0x18968ea, 0x34a6b80, 0x18d26e0, 0xbf1560, 0x2bf156a, 0, 0x1c74d6a}); typedef Field<uint32_t, 27, 39, StatTable27, DynTable27, &SQR_TABLE_27, &QRT_TABLE_27> Field27; #endif #ifdef ENABLE_FIELD_INT_28 // 28 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 5, 5> StatTable28; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 4, 4> DynTable28; constexpr StatTable28 SQR_TABLE_28({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000}); constexpr StatTable28 QRT_TABLE_28({0x121d57a, 0x40216, 0x40214, 0x8112578, 0x40210, 0x10110, 0x8112570, 0x12597ec, 0x40200, 0x6983e00, 0x10130, 0x972b99c, 0x8112530, 0x8002000, 0x125976c, 0x815a76c, 0x40300, 0x936b29c, 0x6983c00, 0x97bb8ac, 0x10530, 0x9103000, 0x972b19c, 0xf6384ac, 0x8113530, 0x4113530, 0x8000000, 0}); typedef Field<uint32_t, 28, 3, StatTable28, DynTable28, &SQR_TABLE_28, &QRT_TABLE_28> Field28; #endif #ifdef ENABLE_FIELD_INT_29 // 29 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 6, 5> StatTable29; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 3, 3, 3> DynTable29; constexpr StatTable29 SQR_TABLE_29({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0xa, 0x28, 0xa0, 0x280, 0xa00, 0x2800, 0xa000, 0x28000, 0xa0000, 0x280000, 0xa00000, 0x2800000, 0xa000000, 0x8000005}); constexpr StatTable29 QRT_TABLE_29({0x1b8351dc, 0xb87135e, 0xb87135c, 0xda7b35e, 0xb871358, 0x621a116, 0xda7b356, 0x40200, 0xb871348, 0xc9e2620, 0x621a136, 0x478b16, 0xda7b316, 0x6762e20, 0x40280, 0x6202000, 0xb871248, 0x627a316, 0xc9e2420, 0xcd1ad36, 0x621a536, 0x760e20, 0x478316, 0xa760e20, 0xda7a316, 0x8000000, 0x6760e20, 0, 0x44280}); typedef Field<uint32_t, 29, 5, StatTable29, DynTable29, &SQR_TABLE_29, &QRT_TABLE_29> Field29; #endif #ifdef ENABLE_FIELD_INT_30 // 30 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 6, 6> StatTable30; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 4, 3, 3> DynTable30; constexpr StatTable30 SQR_TABLE_30({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000, 0x30000000}); constexpr StatTable30 QRT_TABLE_30({0x2159df4a, 0x109134a, 0x1091348, 0x10114, 0x109134c, 0x3a203420, 0x1011c, 0x20004080, 0x109135c, 0x2005439c, 0x3a203400, 0x100400, 0x1015c, 0x3eb21930, 0x20004000, 0x20504c00, 0x109125c, 0x3b2b276c, 0x2005419c, 0x210450c0, 0x3a203000, 0x3e93186c, 0x100c00, 0x3aa23530, 0x1115c, 0x6b3286c, 0x3eb23930, 0xeb23930, 0x20000000, 0}); typedef Field<uint32_t, 30, 3, StatTable30, DynTable30, &SQR_TABLE_30, &QRT_TABLE_30> Field30; #endif #ifdef ENABLE_FIELD_INT_31 // 31 bit field typedef RecLinTrans<uint32_t, 6, 5, 5, 5, 5, 5> StatTable31; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 4, 4, 3> DynTable31; constexpr StatTable31 SQR_TABLE_31({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x48000, 0x120000, 0x480000, 0x1200000, 0x4800000, 0x12000000, 0x48000000, 0x20000012}); constexpr StatTable31 QRT_TABLE_31({0, 0x10110, 0x10112, 0x15076e, 0x10116, 0x117130e, 0x150766, 0x4743fa0, 0x10106, 0x1121008, 0x117132e, 0x176b248e, 0x150726, 0x172a2c88, 0x4743f20, 0x7eb81e86, 0x10006, 0x20008, 0x1121208, 0x56b2c8e, 0x117172e, 0x133f1bae, 0x176b2c8e, 0x7f2a0c8e, 0x151726, 0x10000000, 0x172a0c88, 0x60000006, 0x4747f20, 0x3eb89e80, 0x7eb89e86}); typedef Field<uint32_t, 31, 9, StatTable31, DynTable31, &SQR_TABLE_31, &QRT_TABLE_31> Field31; #endif #ifdef ENABLE_FIELD_INT_32 // 32 bit field typedef RecLinTrans<uint32_t, 6, 6, 5, 5, 5, 5> StatTable32; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 4, 4, 4> DynTable32; constexpr StatTable32 SQR_TABLE_32({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x8d, 0x234, 0x8d0, 0x2340, 0x8d00, 0x23400, 0x8d000, 0x234000, 0x8d0000, 0x2340000, 0x8d00000, 0x23400000, 0x8d000000, 0x3400011a, 0xd0000468, 0x40001037}); constexpr StatTable32 QRT_TABLE_32({0x54fd1264, 0xc26fcd64, 0xc26fcd66, 0x238a7462, 0xc26fcd62, 0x973bccaa, 0x238a746a, 0x77766712, 0xc26fcd72, 0xc1bdd556, 0x973bcc8a, 0x572a094c, 0x238a742a, 0xb693be84, 0x77766792, 0x9555c03e, 0xc26fcc72, 0x568419f8, 0xc1bdd756, 0x96c3d2ca, 0x973bc88a, 0x54861fdc, 0x572a014c, 0xb79badc4, 0x238a642a, 0xb9b99fe0, 0xb6939e84, 0xc519fa86, 0x77762792, 0, 0x9555403e, 0x377627ba}); typedef Field<uint32_t, 32, 141, StatTable32, DynTable32, &SQR_TABLE_32, &QRT_TABLE_32> Field32; #endif } Sketch* ConstructGeneric4Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_25 case 25: return new SketchImpl<Field25>(implementation, 25); #endif #ifdef ENABLE_FIELD_INT_26 case 26: return new SketchImpl<Field26>(implementation, 26); #endif #ifdef ENABLE_FIELD_INT_27 case 27: return new SketchImpl<Field27>(implementation, 27); #endif #ifdef ENABLE_FIELD_INT_28 case 28: return new SketchImpl<Field28>(implementation, 28); #endif #ifdef ENABLE_FIELD_INT_29 case 29: return new SketchImpl<Field29>(implementation, 29); #endif #ifdef ENABLE_FIELD_INT_30 case 30: return new SketchImpl<Field30>(implementation, 30); #endif #ifdef ENABLE_FIELD_INT_31 case 31: return new SketchImpl<Field31>(implementation, 31); #endif #ifdef ENABLE_FIELD_INT_32 case 32: return new SketchImpl<Field32>(implementation, 32); #endif default: return nullptr; } }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/clmul_7bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_7) #include "clmul_common_impl.h" #include "../int_utils.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_49 // 49 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5, 5, 5> StatTable49; constexpr StatTable49 SQR_TABLE_49({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x402, 0x1008, 0x4020, 0x10080, 0x40200, 0x100800, 0x402000, 0x1008000, 0x4020000, 0x10080000, 0x40200000, 0x100800000, 0x402000000, 0x1008000000, 0x4020000000, 0x10080000000, 0x40200000000, 0x100800000000, 0x402000000000, 0x1008000000000, 0x20000000402, 0x80000001008, 0x200000004020, 0x800000010080}); constexpr StatTable49 SQR2_TABLE_49({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x1008, 0x10080, 0x100800, 0x1008000, 0x10080000, 0x100800000, 0x1008000000, 0x10080000000, 0x100800000000, 0x1008000000000, 0x80000001008, 0x800000010080, 0x100004, 0x1000040, 0x10000400, 0x100004000, 0x1000040000, 0x10000400000, 0x100004000000, 0x1000040000000, 0x400001008, 0x4000010080, 0x40000100800, 0x400001008000, 0x10080402, 0x100804020, 0x1008040200, 0x10080402000, 0x100804020000, 0x1008040200000, 0x80402001008, 0x804020010080, 0x40200100004, 0x402001000040, 0x20010000002, 0x200100000020}); constexpr StatTable49 SQR4_TABLE_49({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x1008000, 0x10080000000, 0x800000010080, 0x100004000, 0x1000040000000, 0x400001008000, 0x10080402000, 0x804020010080, 0x200100000020, 0x1000000001000, 0x11008000, 0x110080000000, 0x800000110880, 0x1108004000, 0x1080040001008, 0x400011008400, 0x110084402000, 0x844020110880, 0x201108040220, 0x1080402000008, 0x20001008002, 0x10080000100, 0x800001010080, 0x10100004000, 0x1000040010080, 0x400101808000, 0x1018080402000, 0x8040210100c0, 0x210100400020, 0x1004000011080, 0x11180c020, 0x11180c0200000, 0xc020011108c0, 0x11108004010, 0x1080040111088, 0x401111808400, 0x1118084403008, 0x8440311908c0, 0x311908440220, 0x108440211008c, 0x2110184c022, 0x10184c0201108, 0xc020100904c2, 0x100904024010, 0x1040240000004}); constexpr StatTable49 SQR8_TABLE_49({0x1, 0x800000110880, 0x210100400020, 0x1040240000004, 0x130081008002, 0x191c0a54130c8, 0x900804130890, 0x210111408020, 0x582c0402004, 0xd320910984c0, 0xb1d1ad4522e8, 0x1d80945829818, 0x1218540601128, 0x1240340000024, 0x11300c1018082, 0x193d1a4c5f0ea, 0x148a0522810, 0xe0201051c8e0, 0x2dc7c25120a8, 0x1d2205148a440, 0x33c0adc0e24a, 0x17850e987bab8, 0xa8a40071c9e0, 0x10d47d391c1a8, 0x9740b01888c2, 0x91c0e54130c8, 0x920805138892, 0x130819500b028, 0x8583c0516884, 0x1fa25934984e8, 0x1f5c2fcc5a6ec, 0x15a094483189a, 0x1014cc242300, 0xac020000582c, 0x3b05524100aa, 0x1520255145c6e, 0x4279b95aec40, 0x1f1a0951178e8, 0xbcc646004828, 0x3b055219aca8, 0x57d2fc40666e, 0xba50b987beba, 0x8aa44d913bea, 0x944717d1b9a0, 0x776562491022, 0x1701305105c4c, 0x19039cd5be842, 0x1b281d8e58082, 0x134dac80532a4}); constexpr StatTable49 SQR16_TABLE_49({0x1, 0x790181b552e0, 0xeb19044e00a, 0xc6bf7911f7ae, 0x447f77c1a0c4, 0x19d2a0d21c480, 0x13d4e22aadedc, 0x18fa344c8f0a6, 0x1481c1bbfde92, 0x41547e22f6e0, 0xf5ad96335088, 0xd7e4db3adaa0, 0x197fc8d7b53d0, 0x37781564b82a, 0xa52ef2139cbc, 0x153c6a0949498, 0x18d7401fc152e, 0xc4b5d8597752, 0xd15cd891aa2, 0x217903427da8, 0x13ec9e269a0e0, 0xc01720774514, 0x389aeb1d788a, 0x64a914a860a4, 0xa09aebec6188, 0x15c3239e150c8, 0x38f8fe110ce, 0xc1ea415c5006, 0x3209972f2ff0, 0x41bfc6b2ad88, 0x1ccc2fd5f73c8, 0x7bed1f863c00, 0x1a46d9b9844f4, 0x12e3ca6573ff6, 0x290c26cca98c, 0x514cb03b3b2e, 0x11168909cbc2c, 0x8e6dc910afda, 0x11311def1c440, 0x3e42d62664d8, 0x1c2bb2d75fe80, 0x2db5d58b45ca, 0x3d14059fd338, 0x109e8f457ebf8, 0x43b071b62a64, 0x185242247c010, 0x5e0c7721c092, 0x1c94950e46b82, 0x1761170f76a40}); constexpr StatTable49 QRT_TABLE_49({0, 0x10004196, 0x10004194, 0x5099461f080, 0x10004190, 0x40840600c20, 0x5099461f088, 0x58a56349cfde, 0x10004180, 0x48641a0c03fe, 0x40840600c00, 0x10084002848, 0x5099461f0c8, 0x4002048, 0x58a56349cf5e, 0x5088460a048, 0x10004080, 0x4c2852624dde, 0x48641a0c01fe, 0x14893129c280, 0x40840600800, 0x1eb23c323ace8, 0x10084002048, 0x48740a09417e, 0x5099461e0c8, 0x40852604d96, 0x4000048, 0x5cad2b29c37e, 0x58a563498f5e, 0x20000200, 0x50884602048, 0x10000000000, 0x10014080, 0x4c2a56624d96, 0x4c2852604dde, 0x1ee2347438ca0, 0x48641a0801fe, 0x480000000048, 0x14893121c280, 0x14091121c080, 0x40840700800, 0x1a5099561e17e, 0x1eb23c303ace8, 0x8740a894136, 0x10084402048, 0x18101c501ace8, 0x48740a89417e, 0x15dace6286f96, 0x5099561e0c8}); typedef Field<uint64_t, 49, 513, StatTable49, &SQR_TABLE_49, &SQR2_TABLE_49, &SQR4_TABLE_49, &SQR8_TABLE_49, &SQR16_TABLE_49, &QRT_TABLE_49, IdTrans, &ID_TRANS, &ID_TRANS> Field49; typedef FieldTri<uint64_t, 49, 9, RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5, 5, 5>, &SQR_TABLE_49, &SQR2_TABLE_49, &SQR4_TABLE_49, &SQR8_TABLE_49, &SQR16_TABLE_49, &QRT_TABLE_49, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri49; #endif #ifdef ENABLE_FIELD_INT_50 // 50 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5, 5> StatTable50; constexpr StatTable50 SQR_TABLE_50({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x1d, 0x74, 0x1d0, 0x740, 0x1d00, 0x7400, 0x1d000, 0x74000, 0x1d0000, 0x740000, 0x1d00000, 0x7400000, 0x1d000000, 0x74000000, 0x1d0000000, 0x740000000, 0x1d00000000, 0x7400000000, 0x1d000000000, 0x74000000000, 0x1d0000000000, 0x740000000000, 0x1d00000000000, 0x340000000001d, 0x1000000000053}); constexpr StatTable50 SQR2_TABLE_50({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x74, 0x740, 0x7400, 0x74000, 0x740000, 0x7400000, 0x74000000, 0x740000000, 0x7400000000, 0x74000000000, 0x740000000000, 0x340000000001d, 0x151, 0x1510, 0x15100, 0x151000, 0x1510000, 0x15100000, 0x151000000, 0x1510000000, 0x15100000000, 0x151000000000, 0x1510000000000, 0x1100000000069, 0x10000000006e4, 0x6e34, 0x6e340, 0x6e3400, 0x6e34000, 0x6e340000, 0x6e3400000, 0x6e34000000, 0x6e340000000, 0x6e3400000000, 0x2e3400000001d, 0x234000000011f, 0x3400000001118}); constexpr StatTable50 SQR4_TABLE_50({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x74000, 0x740000000, 0x340000000001d, 0x151000, 0x1510000000, 0x1100000000069, 0x6e3400, 0x6e34000000, 0x234000000011f, 0x1110100, 0x11101000000, 0x1010000000734, 0x7334740, 0x73347400000, 0x347400000145c, 0x14540510, 0x145405100000, 0x510000068b9, 0x68b91a34, 0x68b91a340000, 0x11a3400010106, 0x101010001, 0x1010100010000, 0x1000100074740, 0x1000747474000, 0x347474007401d, 0x340074015050d, 0x340150505101d, 0x1050510151069, 0x11015106e5a5d, 0x1106e5a5a3469, 0x25a5a346e351f, 0x2346e3510111e, 0x235101110001f, 0x111000110634, 0x1106347334, 0x1063473340074, 0x733400735301, 0x7353004541, 0x353004541014c, 0x454101446dc0, 0x101446dc1cb90, 0x6dc1cb97468d, 0x1cb97468c1a30, 0x3468c1a350009, 0x1a3500010007}); constexpr StatTable50 SQR8_TABLE_50({0x1, 0x7334740, 0x1050510151069, 0x3468c1a350009, 0x341624173531c, 0x245791a347b50, 0x23179d1a40682, 0x1671402235203, 0x321023818751e, 0x143ca5b716dd5, 0x171633ad257de, 0x33860681a5d1d, 0x5e572f82a317, 0x10e7512224646, 0x32d6b56300005, 0x350ab39687414, 0x25c47550c1a8a, 0x23a2e2d91533f, 0x2211af19c2381, 0x352073a863a68, 0x37f43380f0ac4, 0x233516127052a, 0x25ad4785169cf, 0x237b6a609b0b6, 0x132fd372b5dac, 0x1f311727562e, 0x345bd7e275754, 0x352fe5b3d7708, 0x259a328ca3376, 0x25101aab53ece, 0x32701d9da5ace, 0x17809a9c86099, 0x72b4752a7323, 0x202d22dc33a7c, 0x5a8c0dbc19a2, 0x14a86b37416ad, 0x5c574289fe12, 0x3627f3bf0f37b, 0x27349052a4f83, 0x2436d71033de5, 0x22fab345e0bce, 0x27ea796d5a27a, 0x1e4f33562d17, 0x31a1f9c3f2154, 0x1638db7753f96, 0x2256163f33b5f, 0x11a6ecf28882e, 0x1bd4cf35f47cc, 0x25e19aeb21e64, 0x371612d0b4dcd}); constexpr StatTable50 SQR16_TABLE_50({0x1, 0x14db3a1b1531f, 0x270a39b5e8c48, 0x26536a58442bd, 0x7f158d4b869e, 0x12663760f7d, 0x29634a2c8876, 0x15271f7ec5d31, 0x17fbb0726d0f0, 0x7f0f7bf826bb, 0x115135d3c7c4c, 0x348ffaaa125e5, 0x1887695a20d9, 0x25e41181c0de, 0x2670d7f17fb35, 0x356079737f513, 0x22bebda8a1574, 0x315f9649d2b50, 0x13abe45aa6ac8, 0x723d536b5242, 0x24263520a22a9, 0x15860c0156a69, 0x271d0bbeed892, 0x146920f281d19, 0x117d5d46e7991, 0x278d8273551fc, 0x15d73a9745614, 0x7e5e966bbfe0, 0x687b14e62abb, 0x178acea79fa5c, 0x3363c557e9662, 0x3153c79bf06ef, 0x15c8ff9daf7ce, 0x243b030f4617a, 0x20663fbd2383a, 0x25c5dbd448872, 0x21fc8dfbd2429, 0x229f9fb8f01b0, 0x17a180ae72359, 0x1c8e2f554ad9, 0x174596d1e774f, 0x3264c5da47f53, 0x333817d45b05c, 0x321907ec10dfd, 0x3a12b2018ada, 0x23ab0599cd08, 0x23028d60c00e5, 0x8ca05e2a1eab, 0x3537bf673a228, 0x32f8cf8611080}); constexpr StatTable50 QRT_TABLE_50({0xfbdfa3ae9d4c, 0x38143245a4878, 0x38143245a487a, 0x38527487e7492, 0x38143245a487e, 0x3124c61f56d2a, 0x38527487e749a, 0xfa8c91b087c0, 0x38143245a486e, 0x3eca48c6196be, 0x3124c61f56d0a, 0x380000040080a, 0x38527487e74da, 0x976b2d8b39b4, 0xfa8c91b08740, 0xfa8cd5b02724, 0x38143245a496e, 0x316291dd013fe, 0x3eca48c6194be, 0x10344122064, 0x3124c61f5690a, 0x68c5f006ee40, 0x380000040000a, 0x852749fe64d0, 0x38527487e64da, 0x37ef8e9d0e9da, 0x976b2d8b19b4, 0x37fabd1cef34a, 0xfa8c91b0c740, 0x96282d9159b4, 0xfa8cd5b0a724, 0x464a8249dd0, 0x38143245b496e, 0x37eaa8ddc94be, 0x316291dd213fe, 0x392446035690a, 0x3eca48c6594be, 0x974b258b4964, 0x103441a2064, 0x385a7c87fb4da, 0x3124c61e5690a, 0xeb8ad5d9a724, 0x68c5f026ee40, 0x3724c61e5690a, 0x380000000000a, 0x3a8c5f026ee4a, 0x8527497e64d0, 0, 0x38527497e64da, 0x2fbdfa2ae8d0a}); typedef Field<uint64_t, 50, 29, StatTable50, &SQR_TABLE_50, &SQR2_TABLE_50, &SQR4_TABLE_50, &SQR8_TABLE_50, &SQR16_TABLE_50, &QRT_TABLE_50, IdTrans, &ID_TRANS, &ID_TRANS> Field50; #endif #ifdef ENABLE_FIELD_INT_51 // 51 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5, 5> StatTable51; constexpr StatTable51 SQR_TABLE_51({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x96, 0x258, 0x960, 0x2580, 0x9600, 0x25800, 0x96000, 0x258000, 0x960000, 0x2580000, 0x9600000, 0x25800000, 0x96000000, 0x258000000, 0x960000000, 0x2580000000, 0x9600000000, 0x25800000000, 0x96000000000, 0x258000000000, 0x960000000000, 0x2580000000000, 0x160000000004b, 0x580000000012c, 0x6000000000426}); constexpr StatTable51 SQR2_TABLE_51({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x96, 0x960, 0x9600, 0x96000, 0x960000, 0x9600000, 0x96000000, 0x960000000, 0x9600000000, 0x96000000000, 0x960000000000, 0x160000000004b, 0x6000000000426, 0x4114, 0x41140, 0x411400, 0x4114000, 0x41140000, 0x411400000, 0x4114000000, 0x41140000000, 0x411400000000, 0x4114000000000, 0x1140000000258, 0x1400000002516, 0x40000000251f6, 0x251d38, 0x251d380, 0x251d3800, 0x251d38000, 0x251d380000, 0x251d3800000, 0x251d38000000, 0x251d380000000, 0x51d380000012c, 0x1d3800000100e, 0x538000001003d, 0x380000010011e}); constexpr StatTable51 SQR4_TABLE_51({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x96000, 0x960000000, 0x160000000004b, 0x411400, 0x4114000000, 0x1140000000258, 0x251d380, 0x251d3800000, 0x1d3800000100e, 0x10010110, 0x100101100000, 0x1011000009600, 0x960969f6, 0x960969f60000, 0x169f60004110b, 0x6000411015132, 0x4110151054000, 0x1510540251f60, 0x540251f6ba760, 0x51f6ba74eb92c, 0x3a74eb900001f, 0x6b90000010033, 0x100010860, 0x1000108600000, 0x1086000096000, 0x960092874, 0x160092874004b, 0x128740041144b, 0x40041144304e2, 0x1144304c78258, 0x304c78251d1d8, 0x78251d1c38368, 0x1d1c38352800e, 0x3835280011188, 0x280011197096e, 0x1119709787000, 0x709787009fb46, 0x7009fb7861c9, 0x1fb7861cae24b, 0x61cae2456109, 0x2e245610a7bc3, 0x5610a7bd61498, 0x27bd614b79d2b, 0x614b79d3a74de, 0x79d3a74e9f68a, 0x274e9f6b06011, 0x1f6b06000000f}); constexpr StatTable51 SQR8_TABLE_51({0x1, 0x960969f6, 0x40041144304e2, 0x79d3a74e9f68a, 0x61005961939d4, 0x2e2108dfdafb5, 0xe7e61b897f73, 0x493a58b330d18, 0x7882105dc65ec, 0x5f00774200d11, 0x63ef4cd371ef3, 0x660b24b8d214b, 0x7ab791e669e3d, 0x10821820969f6, 0x1544b9d4c3f3e, 0x831185e3da14, 0x1eb0831983187, 0x1d8699ae87312, 0x586e000eb5f1a, 0x3ea794ef9c821, 0x2ab1c63209cc1, 0x7f434bcc29855, 0x673d370c40117, 0x6a668249ddd8b, 0x48be019e56bbe, 0x57d1a751be823, 0x5621931ca6d5f, 0x68c5a37844a68, 0xefa69123b6b1, 0x5804da97df62a, 0x30c29b82f3986, 0x5b808f6ddc779, 0x2c8b4e7596cbe, 0x2c5a432ec7a14, 0x7f178a4d63277, 0x77112a07b99b7, 0x56cf47ad50529, 0x73a2180190a41, 0x25cbc68f1f1a8, 0x1c27dc22e6950, 0x2fbf4aafee2ad, 0x554b728a595ca, 0x52726d34627e, 0x6dcc716c9e860, 0x36ade274d5eff, 0x1fa23a55b359a, 0x1bc6260896059, 0x53a74c5798bc1, 0x50e671fc54a4a, 0x251a72b3c4c3c, 0x6d9623f5d3a1e}); constexpr StatTable51 SQR16_TABLE_51({0x1, 0x27b32044e9663, 0x528c08dd195bf, 0x5d461228d5764, 0x616db8f131bf6, 0x9d910988ca4, 0x1e7a7a29c55fd, 0x512a2e6297818, 0x688d44453ead0, 0x70e0b6e1b3be2, 0x4313e5612d70, 0x132241d43589d, 0x7ca688c29c89a, 0x1d6b8caeb8958, 0x36d06e8e76e3b, 0x18ebafc89388e, 0x1cb5f93b2c29c, 0x5137bd7b7b6ec, 0x6e3ae8731000b, 0x359203e5e12fe, 0x1822ded1f1e16, 0x3ee9c50cbcb89, 0x5cc0b4564ab4, 0x695b235bd9236, 0x283c619a1ecb, 0x6f37f1f6ef70d, 0x7f394b6fbdd53, 0x3f482b36793f, 0x4055274e56dfa, 0x1a85d9d434f33, 0x37aa8f3df2031, 0x5f4e77b2bb063, 0x6e9702d84f07b, 0x25f16f8ffd4c2, 0x22c591d8277cb, 0x59435d9bae242, 0x46eaf9f69ddd9, 0x3098c1e26bd6e, 0x6c6544847a1d, 0x254946c0c33ce, 0x23970a6118811, 0x67f6c55082b49, 0x6592c83ebde46, 0x716418f089ed8, 0x8cb8de463166, 0x37cb1794fac42, 0x94ac55c1ac68, 0x3ab0d33bb4fdf, 0x1669c2f7ae3c5, 0x4d4e4f61d1f04, 0x476980d17eef5}); constexpr StatTable51 QRT_TABLE_51({0x778bf2703d152, 0x2aaaafbff2092, 0x2aaaafbff2090, 0x4d2119c7e7780, 0x2aaaafbff2094, 0x65de1df8ae194, 0x4d2119c7e7788, 0x67d63d7ba262c, 0x2aaaafbff2084, 0x28ff003f4167c, 0x65de1df8ae1b4, 0x658397fb1d034, 0x4d2119c7e77c8, 0x4d7c9284526ba, 0x67d63d7ba26ac, 0x6666333fc0cbe, 0x2aaaafbff2184, 0x295b807ab55ee, 0x28ff003f4147c, 0x2aaabfffe0016, 0x65de1df8ae5b4, 0x209210349d60, 0x658397fb1d834, 0x4d215dc7cf1c8, 0x4d2119c7e67c8, 0x662b2b3d7b4be, 0x4d7c9284506ba, 0x255af00b36e0, 0x67d63d7ba66ac, 0x65de1fb8ac1a6, 0x6666333fc8cbe, 0x662f3b3ded4be, 0x2aaaafbfe2184, 0x663a9dbc3a426, 0x295b807a955ee, 0x4cdc9ec128928, 0x28ff003f0147c, 0x28a0c93cd511c, 0x2aaabfff60016, 0x65d73cf8e78d4, 0x65de1df9ae5b4, 0x4d5eddc44f1c8, 0x209210149d60, 0x357fcc506c8a, 0x658397ff1d834, 0, 0x4d215dcfcf1c8, 0x63f536f5d4554, 0x4d2119d7e67c8, 0x4000000000022, 0x662b2b1d7b4be}); typedef Field<uint64_t, 51, 75, StatTable51, &SQR_TABLE_51, &SQR2_TABLE_51, &SQR4_TABLE_51, &SQR8_TABLE_51, &SQR16_TABLE_51, &QRT_TABLE_51, IdTrans, &ID_TRANS, &ID_TRANS> Field51; #endif #ifdef ENABLE_FIELD_INT_52 // 52 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5, 5> StatTable52; constexpr StatTable52 SQR_TABLE_52({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x9, 0x24, 0x90, 0x240, 0x900, 0x2400, 0x9000, 0x24000, 0x90000, 0x240000, 0x900000, 0x2400000, 0x9000000, 0x24000000, 0x90000000, 0x240000000, 0x900000000, 0x2400000000, 0x9000000000, 0x24000000000, 0x90000000000, 0x240000000000, 0x900000000000, 0x2400000000000, 0x9000000000000, 0x4000000000012}); constexpr StatTable52 SQR2_TABLE_52({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x9, 0x90, 0x900, 0x9000, 0x90000, 0x900000, 0x9000000, 0x90000000, 0x900000000, 0x9000000000, 0x90000000000, 0x900000000000, 0x9000000000000, 0x41, 0x410, 0x4100, 0x41000, 0x410000, 0x4100000, 0x41000000, 0x410000000, 0x4100000000, 0x41000000000, 0x410000000000, 0x4100000000000, 0x1000000000024, 0x249, 0x2490, 0x24900, 0x249000, 0x2490000, 0x24900000, 0x249000000, 0x2490000000, 0x24900000000, 0x249000000000, 0x2490000000000, 0x4900000000012, 0x9000000000104}); constexpr StatTable52 SQR4_TABLE_52({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x9000, 0x90000000, 0x900000000000, 0x4100, 0x41000000, 0x410000000000, 0x2490, 0x24900000, 0x249000000000, 0x1001, 0x10010000, 0x100100000000, 0x1000000000900, 0x9009000, 0x90090000000, 0x900000000410, 0x4104100, 0x41041000000, 0x410000000249, 0x2492490, 0x24924900000, 0x9249000000104, 0x1000001, 0x10000010000, 0x100000090, 0x1000000900000, 0x9000009000, 0x90000041, 0x900000410000, 0x4100004100, 0x1000041000024, 0x410000249000, 0x2490002490, 0x4900024900012, 0x249000100100, 0x1001001001, 0x10010010009, 0x100100090090, 0x1000900900900, 0x9009009009000, 0x90090041041, 0x900410410410, 0x4104104104100, 0x1041041024924, 0x410249249249, 0x2492492492490, 0x4924924910002, 0x9249100000004}); constexpr StatTable52 SQR8_TABLE_52({0x1, 0x1000000000900, 0x900000410000, 0x410249249249, 0x349100000000, 0x1900000d1, 0x10d10d1065965, 0x51010000, 0x2d924909000, 0x4114114114109, 0xe591, 0x1000007c96591, 0x1903981d13981, 0x249000000001, 0x1000100000990, 0x990090451041, 0x41022cb49249, 0x37d824910000, 0x90191890190d8, 0x10d10d106edf5, 0x54114101, 0x102f4b400bd90, 0x5c04114114108, 0x8f5900000ebcc, 0x1e59107b5f401, 0x8f5ab89f5abcc, 0x24924900001, 0x1010010010909, 0x90000041d100, 0x41024f7df7d9, 0x34a591003491, 0x9001900000d0, 0x4c10d106522c, 0xb49051500100, 0x43dafdb40249, 0x428c0c5114109, 0x59001f590e576, 0x49f59f25facf6, 0x19039c4c17881, 0x26fdb4902491, 0x10110010998, 0x109009045cc51, 0x90022a8867d9, 0x9527ffcb5a6dc, 0x9bc01190190d9, 0x14c119006e608, 0x42fd9e0d55042, 0x143f711b5bfd9, 0x5fa58e1809008, 0x23d647ac81eb2, 0x57ac8f223a466, 0x865abc8b4abcc}); constexpr StatTable52 SQR16_TABLE_52({0x1, 0x4f881c2d96599, 0xd7eb53011fc41, 0x81d7387961fef, 0xd9afe338982c3, 0x17590c140da98, 0x141a99a87a04e, 0x10036ba4083d9, 0x8f4f72ffb12c7, 0xc8b70df241e1b, 0x18bd9e5d46c40, 0x18331d76266bd, 0x4d915f264a4e0, 0x46aeffb8e4037, 0x4800042de37b5, 0xdb172953272e8, 0x17a9c2edf826a, 0x191cf7053e3f2, 0x82036da842cea, 0x5891da126c1e, 0x1e536e9e4af49, 0x451b5638f5449, 0x5a006c6c4f8c8, 0x5ac71a535fb44, 0xd39a4d489ebd0, 0x4704e31bc006d, 0xc4b327f6ffae1, 0x46980b709bd00, 0xd755405154c11, 0x5741be2d0b797, 0xcb3d48ed630cb, 0x98a66c9f4f599, 0x4caa324b91629, 0x816b5015eeeaf, 0xa595e92a8ed4, 0xc93c6d9f5a073, 0x4250068b39e2, 0x105add98997b5, 0x408b030c0bce0, 0xced5e4a4a2028, 0x1eb59d68e7f25, 0x189756a5b6db0, 0xc49c5a7c98b01, 0x18c9a496767cb, 0xde650554b3d49, 0x11077035fd81c, 0x8b37c5e95a659, 0x45b9226c2c25e, 0xdd2b5e20c7c8b, 0x6de972f0e7025, 0x84e80092f5681, 0x8dfcf97183cbc}); constexpr StatTable52 QRT_TABLE_52({0xc108165459b0e, 0x10004086, 0x10004084, 0xc00000100104e, 0x10004080, 0x2041810a545b0, 0xc000001001046, 0x1181e055efc0, 0x10004090, 0x40810214390, 0x2041810a54590, 0xc000141019106, 0xc000001001006, 0x10816045ab40, 0x1181e055ef40, 0xc000111015196, 0x10004190, 0xe045c19af44a2, 0x40810214190, 0xe045809ad0532, 0x2041810a54190, 0xdb387a03fe646, 0xc000141019906, 0x2000000800000, 0xc000001000006, 0x2486548199c34, 0x108160458b40, 0x2041808a50534, 0x1181e055af40, 0xc0408312153d6, 0xc00011101d196, 0x21499f0e0eed0, 0x10014190, 0xe15dff9faabe2, 0xe045c19ad44a2, 0xdb787b01ea7d6, 0x40810254190, 0xe484409180532, 0xe045809a50532, 0xc14095164d896, 0x2041810b54190, 0x217dee8fb7a74, 0xdb387a01fe646, 0x441810b54190, 0xc000141419906, 0xc3386e15e7f46, 0x2000000000000, 0x1000141419900, 0xc000000000006, 0, 0x248654a199c34, 0xa48654a199c32}); typedef Field<uint64_t, 52, 9, StatTable52, &SQR_TABLE_52, &SQR2_TABLE_52, &SQR4_TABLE_52, &SQR8_TABLE_52, &SQR16_TABLE_52, &QRT_TABLE_52, IdTrans, &ID_TRANS, &ID_TRANS> Field52; typedef FieldTri<uint64_t, 52, 3, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5, 5>, &SQR_TABLE_52, &SQR2_TABLE_52, &SQR4_TABLE_52, &SQR8_TABLE_52, &SQR16_TABLE_52, &QRT_TABLE_52, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri52; #endif #ifdef ENABLE_FIELD_INT_53 // 53 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 5> StatTable53; constexpr StatTable53 SQR_TABLE_53({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x8e, 0x238, 0x8e0, 0x2380, 0x8e00, 0x23800, 0x8e000, 0x238000, 0x8e0000, 0x2380000, 0x8e00000, 0x23800000, 0x8e000000, 0x238000000, 0x8e0000000, 0x2380000000, 0x8e00000000, 0x23800000000, 0x8e000000000, 0x238000000000, 0x8e0000000000, 0x2380000000000, 0x8e00000000000, 0x3800000000047, 0xe00000000011c, 0x18000000000437}); constexpr StatTable53 SQR2_TABLE_53({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x10000000000000, 0x238, 0x2380, 0x23800, 0x238000, 0x2380000, 0x23800000, 0x238000000, 0x2380000000, 0x23800000000, 0x238000000000, 0x2380000000000, 0x3800000000047, 0x18000000000437, 0x4054, 0x40540, 0x405400, 0x4054000, 0x40540000, 0x405400000, 0x4054000000, 0x40540000000, 0x405400000000, 0x4054000000000, 0x54000000008e, 0x54000000008e0, 0x14000000008e8e, 0x8ea56, 0x8ea560, 0x8ea5600, 0x8ea56000, 0x8ea560000, 0x8ea5600000, 0x8ea56000000, 0x8ea560000000, 0x8ea5600000000, 0xea5600000011c, 0xa560000001015, 0x560000001000b, 0x1600000010003e}); constexpr StatTable53 SQR4_TABLE_53({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x23800, 0x238000000, 0x2380000000000, 0x40540, 0x405400000, 0x4054000000000, 0x8ea56, 0x8ea560000, 0x8ea5600000000, 0x1600000010003e, 0x1000111000, 0x10001110000000, 0x11100000238000, 0x2380219b80, 0x380219b800047, 0x19b8000405447, 0x4054441114, 0x54441114008e, 0x41114008ea5ee, 0x14008ea5e6c1b8, 0xea5e6c193611c, 0x6c1936100000d, 0x13610000000124, 0x1010338, 0x10103380000, 0x1033800000238, 0x180000023a3e0f, 0x23a3e3d4000, 0x1a3e3d40000437, 0x1d400004014997, 0x40149af1600, 0x149af160008e0, 0xf160008e2a4a3, 0x8e2a4bc4710, 0x2a4bc47101015, 0x1c4710101022bb, 0x101010228120a8, 0x102281208ba380, 0x1208ba3a3c26c, 0xba3a3c26e7e1c, 0x3c26e7e0ad413, 0xe7e0ad414deb9, 0xad414dea4a7d0, 0x14dea4a7c40960, 0x4a7c4094acd8b, 0x4094acd82b43a, 0xacd82b432f376, 0x2b432f3623804, 0x12f36238010027}); constexpr StatTable53 SQR8_TABLE_53({0x1, 0x11100000238000, 0x1a3e3d40000437, 0x4a7c4094acd8b, 0x1eea7d6a679bbe, 0x1c423906384897, 0x2168da5f2c08c, 0x1b8259ec8ea11, 0x19d1f388b2d3d6, 0x1959a5720001a7, 0x1a6c8fa147c79, 0x191868056d58df, 0x19b717beaf7eb0, 0x1d37e92df66e7f, 0x16ec165c8535b7, 0x7da5e73dba0b3, 0x14d2bece5702b1, 0xadfaa30a5cf7e, 0x101934bec0d066, 0xaae7f006690ce, 0x6bfdbd85eb297, 0x6b2cb00d8c2b5, 0x52ee73aae547e, 0x67461baa976c2, 0xf8a44f459c7d, 0x2579abd0b5fc6, 0x6e7e5e9b82057, 0x1ab0a0fcf2d91c, 0x385dc87020053, 0xfc75a891c9df0, 0xca67b851d0c1a, 0x4c8d3234fd4f7, 0xf3ea564798c7f, 0x16881f479c0d6b, 0x60b0e8e33fe90, 0x18259a2869066d, 0xc52b463fb1475, 0x8229075c3475d, 0x6725108ff0948, 0xd5edf67d5a509, 0xbf52bb2383664, 0xd5b84ac7ed2ab, 0xbb5901d009d56, 0xcb380bfcebc5, 0x5f411d4594745, 0x18bdcb9f9d25da, 0xf0d3abe76ec15, 0x8b1a6404ca3b5, 0x15b7c7c793b65f, 0x11ff16f08569ff, 0x19c1d4c5eb3442, 0x5deb92ff5fc40, 0xa8009f9410cbc}); constexpr StatTable53 SQR16_TABLE_53({0x1, 0x5a65e677a526f, 0x142b8f50195f72, 0x12b0ca8e8b1225, 0x1b892547f268cc, 0x1239ca3a4824b6, 0x4249dac026ea8, 0x38080cba150e5, 0x903882481cefb, 0x1ad11e5cf99bf0, 0x14fa149116ab75, 0x6cbd888de21e5, 0x1388c718c37a69, 0x89d1eb38e9978, 0xf12019f00f91f, 0xb377986c7da1f, 0x1c780b06da5cb9, 0x1e10c7eee3249d, 0xe1afb7bd8111d, 0xc821f2a6fa090, 0x1a26caa65e1d59, 0x4280741c8cc4c, 0xb9c507337dad8, 0x65bffa0a097b6, 0x12068bb8ed4ac0, 0x6d751e7056355, 0xbccc3fbdcf084, 0x17ed82d58ea927, 0x125a30b543b4b8, 0xaf1ce3f5f84ce, 0x1082e42090b649, 0xf8d6a6212c41a, 0x1f89211d4982d, 0x1910bdfe092d07, 0x9363da9b9b9d3, 0x8a7196ef7b84e, 0x33fe46ddf1dc, 0x1f3f3291cf719d, 0x91a5da69f1035, 0x5a8dc6eb62cfb, 0xaf99fcc57728a, 0x15e73f1aa49f47, 0x2d82e50796b97, 0x1072fcbb074200, 0x15180f0fc7904, 0xa3a194b750f79, 0xb053c3eea9bb3, 0x1e58da5ae123de, 0x10b47afec00861, 0x17cd9ea910639d, 0x1ecf806dbf8c36, 0xf93d00fe6145b, 0x1247d788a3eda}); constexpr StatTable53 QRT_TABLE_53({0xf940b90844076, 0x1f940b90844052, 0x1f940b90844050, 0x9d2a063b43e64, 0x1f940b90844054, 0x936f69323ec14, 0x9d2a063b43e6c, 0xe12270a88898, 0x1f940b90844044, 0x1f917f00bb5a3c, 0x936f69323ec34, 0x1f622df85b46ee, 0x9d2a063b43e2c, 0x9bc65ab040b66, 0xe12270a88818, 0x958330b931986, 0x1f940b90844144, 0x98e2a06e32e0, 0x1f917f00bb583c, 0x1f877970dc1024, 0x936f69323e834, 0x16cc3c9b1558c2, 0x1f622df85b4eee, 0x16de1c3351dae8, 0x9d2a063b42e2c, 0x1fecdc7855f8ee, 0x9bc65ab042b66, 0x933821b1cb6fe, 0xe12270a8c818, 0x1f675958641c0e, 0x958330b939986, 0x9d97e050e960, 0x1f940b90854144, 0x1f820fa0e38adc, 0x98e2a06c32e0, 0x1650f0e358a010, 0x1f917f00bf583c, 0x1643af4b037a3a, 0x1f877970d41024, 0x1ffe2c281d8c16, 0x936f69333e834, 0xf00d50ffccf8, 0x16cc3c9b3558c2, 0x16bc31cbca943a, 0x1f622df81b4eee, 0xa6cbd8007232, 0x16de1c33d1dae8, 0x15d2a062b42e10, 0x9d2a062b42e2c, 0x1aa77896586ca, 0x1fecdc7a55f8ee, 0, 0x9bc65af042b66}); typedef Field<uint64_t, 53, 71, StatTable53, &SQR_TABLE_53, &SQR2_TABLE_53, &SQR4_TABLE_53, &SQR8_TABLE_53, &SQR16_TABLE_53, &QRT_TABLE_53, IdTrans, &ID_TRANS, &ID_TRANS> Field53; #endif #ifdef ENABLE_FIELD_INT_54 // 54 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 6> StatTable54; constexpr StatTable54 SQR_TABLE_54({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x201, 0x804, 0x2010, 0x8040, 0x20100, 0x80400, 0x201000, 0x804000, 0x2010000, 0x8040000, 0x20100000, 0x80400000, 0x201000000, 0x804000000, 0x2010000000, 0x8040000000, 0x20100000000, 0x80400000000, 0x201000000000, 0x804000000000, 0x2010000000000, 0x8040000000000, 0x20100000000000, 0x400000000402, 0x1000000001008, 0x4000000004020, 0x10000000010080}); constexpr StatTable54 SQR2_TABLE_54({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x10000000000000, 0x804, 0x8040, 0x80400, 0x804000, 0x8040000, 0x80400000, 0x804000000, 0x8040000000, 0x80400000000, 0x804000000000, 0x8040000000000, 0x400000000402, 0x4000000004020, 0x40001, 0x400010, 0x4000100, 0x40001000, 0x400010000, 0x4000100000, 0x40001000000, 0x400010000000, 0x4000100000000, 0x1000000201, 0x10000002010, 0x100000020100, 0x1000000201000, 0x10000002010000, 0x20100804, 0x201008040, 0x2010080400, 0x20100804000, 0x201008040000, 0x2010080400000, 0x20100804000000, 0x1008040001008, 0x10080400010080, 0x804000100004, 0x8040001000040, 0x400010000002, 0x4000100000020}); constexpr StatTable54 SQR4_TABLE_54({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x80400, 0x804000000, 0x8040000000000, 0x400010, 0x4000100000, 0x1000000201, 0x10000002010000, 0x20100804000, 0x1008040001008, 0x400010000002, 0x100000000100, 0x1008040, 0x10080400000, 0x804000000804, 0x8000001, 0x80000010000, 0x100004020, 0x1000040200000, 0x402000080400, 0x20000804020100, 0x8040200008000, 0x2000080400010, 0x804000000800, 0x8040001, 0x80400010000, 0x4000100004020, 0x1000040001000, 0x400010080400, 0x100804020100, 0x8040201008040, 0x2010080000010, 0x800000000004, 0x200, 0x2000000, 0x20000000000, 0x1008, 0x10080000, 0x100800000000, 0x8000000008040, 0x80002000, 0x800020000000, 0x200000040200, 0x402010080, 0x4020100800000, 0x1008000200008, 0x2000000002, 0x20000000020000, 0x201008000, 0x2010080000000, 0x800000100004}); constexpr StatTable54 SQR8_TABLE_54({0x1, 0x10080400000, 0x100804020100, 0x1008000200008, 0x10080002000000, 0x4000000804, 0x8000201000040, 0x402000000000, 0x20100004020, 0x1000000000, 0x80000010, 0x20100800000100, 0x201008, 0x80002010080, 0x804020100000, 0x201000040, 0x2000080000, 0x4020100004000, 0x8040000, 0x10000402000, 0x20000, 0x1008000001008, 0x10080402010080, 0x4000000004, 0x40001000040, 0x10080402, 0x4020000004000, 0x40001, 0x2000080402010, 0x20000000000000, 0x1000000200000, 0x10000000000080, 0x4020100000, 0x40201008040, 0x402000080002, 0x4020000800000, 0x1000000201, 0x2000080400010, 0x100800000000, 0x8040001008, 0x400000000, 0x20000004, 0x8040200000040, 0x80402, 0x20000804020, 0x201008040000, 0x80400010, 0x800020000, 0x1008040001000, 0x2010000, 0x4000100800, 0x8000, 0x402000000402, 0x4020100804020}); constexpr StatTable54 SQR16_TABLE_54({0x1, 0x80002010000, 0x4020000000000, 0x1000000201008, 0x402010000402, 0x20100804020000, 0x8000001000040, 0x2000000000000, 0x804020000800, 0x1000000201, 0x80002000080, 0x804020, 0x8, 0x400010080000, 0x20100000000000, 0x8000001008040, 0x2010080002010, 0x804020100804, 0x8000001, 0x10000000000000, 0x4020100004000, 0x8000001008, 0x400010000400, 0x4020100, 0x40, 0x2000080400000, 0x800000000804, 0x8040001, 0x10080400010080, 0x4020100804020, 0x40000008, 0x402, 0x20100800020000, 0x40000008040, 0x2000080002000, 0x20100800, 0x200, 0x10000402000000, 0x4000000004020, 0x40200008, 0x402000080002, 0x20100804020100, 0x200000040, 0x2010, 0x804000100804, 0x200000040200, 0x10000400010000, 0x100804000, 0x1000, 0x2010000402, 0x20000000020100, 0x201000040, 0x2010000400010, 0x804020100004}); constexpr StatTable54 QRT_TABLE_54({0x201008000200, 0x26c10916494994, 0x26c10916494996, 0x40008008, 0x26c10916494992, 0x141a2434c12d12, 0x40008000, 0x36c00110594c22, 0x26c10916494982, 0x200000040200, 0x141a2434c12d32, 0x10010816104534, 0x40008040, 0x36da60b01308b2, 0x36c00110594ca2, 0x48200209000, 0x26c10916494882, 0x41b6da2d86106, 0x200000040000, 0x32db2c228965b0, 0x141a2434c12932, 0x9000000200048, 0x10010816104d34, 0x32db68b2832da4, 0x40009040, 0x40045928b4902, 0x36da60b01328b2, 0x1000040000, 0x36c00110590ca2, 0x101b69865a4120, 0x48200201000, 0x22da6434912884, 0x26c10916484882, 0x9000240208008, 0x41b6da2da6106, 0x22c14484c20180, 0x200000000000, 0x4016db29b6812, 0x32db2c228165b0, 0x9008200201048, 0x141a2434d12932, 0x32c36ca2c264b0, 0x9000000000048, 0x140a65b48a2c32, 0x10010816504d34, 0, 0x32db68b2032da4, 0x404490824814, 0x41009040, 0x14da60a4536126, 0x40045908b4902, 0x8000041009008, 0x36da60b41328b2, 0x6db68b2032c12}); typedef Field<uint64_t, 54, 513, StatTable54, &SQR_TABLE_54, &SQR2_TABLE_54, &SQR4_TABLE_54, &SQR8_TABLE_54, &SQR16_TABLE_54, &QRT_TABLE_54, IdTrans, &ID_TRANS, &ID_TRANS> Field54; typedef FieldTri<uint64_t, 54, 9, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 6>, &SQR_TABLE_54, &SQR2_TABLE_54, &SQR4_TABLE_54, &SQR8_TABLE_54, &SQR16_TABLE_54, &QRT_TABLE_54, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri54; #endif #ifdef ENABLE_FIELD_INT_55 // 55 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5> StatTable55; constexpr StatTable55 SQR_TABLE_55({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x102, 0x408, 0x1020, 0x4080, 0x10200, 0x40800, 0x102000, 0x408000, 0x1020000, 0x4080000, 0x10200000, 0x40800000, 0x102000000, 0x408000000, 0x1020000000, 0x4080000000, 0x10200000000, 0x40800000000, 0x102000000000, 0x408000000000, 0x1020000000000, 0x4080000000000, 0x10200000000000, 0x40800000000000, 0x2000000000102, 0x8000000000408, 0x20000000001020}); constexpr StatTable55 SQR2_TABLE_55({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x10000000000000, 0x102, 0x1020, 0x10200, 0x102000, 0x1020000, 0x10200000, 0x102000000, 0x1020000000, 0x10200000000, 0x102000000000, 0x1020000000000, 0x10200000000000, 0x2000000000102, 0x20000000001020, 0x10004, 0x100040, 0x1000400, 0x10004000, 0x100040000, 0x1000400000, 0x10004000000, 0x100040000000, 0x1000400000000, 0x10004000000000, 0x40000000102, 0x400000001020, 0x4000000010200, 0x40000000102000, 0x1020408, 0x10204080, 0x102040800, 0x1020408000, 0x10204080000, 0x102040800000, 0x1020408000000, 0x10204080000000, 0x2040800000102, 0x20408000001020, 0x4080000010004, 0x40800000100040, 0x8000001000008}); constexpr StatTable55 SQR4_TABLE_55({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x10200, 0x102000000, 0x1020000000000, 0x10004, 0x100040000, 0x1000400000000, 0x4000000010200, 0x102040800, 0x1020408000000, 0x4080000010004, 0x100000010, 0x1000000100000, 0x1000010200, 0x10000102000000, 0x1020000102000, 0x1020010004, 0x10200100040000, 0x1000400100040, 0x4001000410200, 0x10004102040800, 0x41020408102000, 0x4081020418004, 0x10204180000010, 0x41800000000040, 0x10300, 0x103000000, 0x1030000000000, 0x10106, 0x101060000, 0x1010600000000, 0x6000000010302, 0x103040c00, 0x103040c000000, 0x40c0000010106, 0x101020418, 0x1010204180000, 0x2041800010302, 0x18000103000008, 0x1030000103000, 0x1030010106, 0x10300101060000, 0x1010600101060, 0x6001010610302, 0x10106103040c00, 0x6103040c103020, 0x40c103041c106, 0x103041c1020418, 0x41c10204081060, 0x2040810214282, 0x8102142800008, 0x21428000000020}); constexpr StatTable55 SQR8_TABLE_55({0x1, 0x1000010200, 0x101060000, 0x6103040c103020, 0x1001400010200, 0x4081121478004, 0x7903050f103028, 0x1100010200, 0x1020101162000, 0x6703040c113322, 0x113055c1030618, 0x50a102353a804, 0x3e83050f11336a, 0x103040f102071e, 0x101070200, 0x7123050c143020, 0x3100c010200, 0x60c193166c286, 0x6d2b040f15302c, 0x103140f010200, 0x2070f112772e2, 0x7621050c153322, 0x143341cd420418, 0x70e193270ee9e, 0xbe9840f14334e, 0x143355fe53051e, 0x3050e103555fc, 0x5153e50f143c00, 0x1001500050200, 0x450a152957a004, 0x7b071d0f11332a, 0x1000040200, 0x5000040b060000, 0x64061a0c103020, 0x153c44f147c71e, 0x4008142b428a04, 0x2ca75c8f103078, 0x113341f117371e, 0x5402040b162000, 0x62064aac143336, 0x50c003f51ff06, 0x7cf1f3d7ef2e6, 0x6e2d180714332e, 0x103150f050100, 0x43350b1a3152e2, 0x74261e06143020, 0x113f54fd17c65e, 0x56301c3b66cd98, 0x10dff9c7953054, 0x153055fe47360e, 0x46340a1b2277fc, 0x4574bfb5753c14, 0x50f003345fc52, 0x41f653264c9962, 0x7612375be93322}); constexpr StatTable55 SQR16_TABLE_55({0x1, 0x4ba7488f00015a, 0x30ce9d3a61c1e4, 0x4a2e76980aff84, 0x4e44f5b9d2f610, 0x7b479e4450115c, 0x248c18e86b39b2, 0x1ba74c8406015a, 0x35e93420af76aa, 0x7f282c7c68ad54, 0x7f8b356ad7bc5a, 0x527272878d3b24, 0x587495a40395a4, 0x43c4d0fd51f96c, 0x57ce893a71f0c6, 0x62c68a94803da, 0x1b32bc920e6546, 0x5073c39b469c78, 0x2fba08c009b110, 0x10bd0559ba45c, 0x3bbbd0ca4b3246, 0x243ad4b7c193b8, 0x335d7f186b5db2, 0x5590f3a0fd73f0, 0x72953f208233ba, 0x5210b9a31e6c62, 0x744bb124e351da, 0x4929f00a730244, 0x736ff5bdc1c63c, 0x4c1da1fb246e2e, 0x553c18b46d95cc, 0x268f5c8c143376, 0x438f5a59cbf094, 0x6a718b25fd3946, 0x67053b1bf54fe0, 0x441c5323cb0288, 0x5def8fcd41d5a8, 0x40446cdfcdb062, 0x1043009fb20072, 0xef08d6ed9e9c6, 0xbdf8adea645be, 0x76b092b499c072, 0xd754f98b724c2, 0x5a21d55c8f8752, 0x4f0f36a62eeb0c, 0x262f651fb93b18, 0x3336d340aa0aaa, 0x69375d0e9970fa, 0x2e0997225afe66, 0x6692008b83364e, 0x230856519bc3ae, 0x2c0a54962f8378, 0x2a6460de8a4266, 0x2f14d8fa237452, 0x25934cd7ae0030}); constexpr StatTable55 QRT_TABLE_55({0, 0x121d57b6623fde, 0x121d57b6623fdc, 0x68908340d10e00, 0x121d57b6623fd8, 0x100300510e20, 0x68908340d10e08, 0x10004096, 0x121d57b6623fc8, 0x100010000, 0x100300510e00, 0x7ea8c890a088e8, 0x68908340d10e48, 0x68809540871648, 0x10004016, 0x68808000808068, 0x121d57b6623ec8, 0x68909240d41c48, 0x100010200, 0x6884c170ad0216, 0x100300510a00, 0x68848160a50200, 0x7ea8c890a080e8, 0x7eecbca04ab4b6, 0x68908340d11e48, 0x120c54b62234c8, 0x68809540873648, 0x69929240d61c48, 0x10000016, 0x68808060800000, 0x68808000800068, 0x80000080, 0x121d57b6633ec8, 0x7ea8cb90a18ae8, 0x68909240d61c48, 0x16284090200080, 0x100050200, 0x474302a345e, 0x6884c170a50216, 0x166cbca0cab4de, 0x100300410a00, 0x1000000000000, 0x68848160850200, 0x688cc1f0a50296, 0x7ea8c890e080e8, 0x7e8cc1f0a50280, 0x7eecbca0cab4b6, 0x68000000000068, 0x68908341d11e48, 0x7880954487365e, 0x120c54b42234c8, 0x9929248d61c20, 0x68809544873648, 0x41121208561c20, 0x69929248d61c48}); typedef Field<uint64_t, 55, 129, StatTable55, &SQR_TABLE_55, &SQR2_TABLE_55, &SQR4_TABLE_55, &SQR8_TABLE_55, &SQR16_TABLE_55, &QRT_TABLE_55, IdTrans, &ID_TRANS, &ID_TRANS> Field55; typedef FieldTri<uint64_t, 55, 7, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5>, &SQR_TABLE_55, &SQR2_TABLE_55, &SQR4_TABLE_55, &SQR8_TABLE_55, &SQR16_TABLE_55, &QRT_TABLE_55, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri55; #endif #ifdef ENABLE_FIELD_INT_56 // 56 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5> StatTable56; constexpr StatTable56 SQR_TABLE_56({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x95, 0x254, 0x950, 0x2540, 0x9500, 0x25400, 0x95000, 0x254000, 0x950000, 0x2540000, 0x9500000, 0x25400000, 0x95000000, 0x254000000, 0x950000000, 0x2540000000, 0x9500000000, 0x25400000000, 0x95000000000, 0x254000000000, 0x950000000000, 0x2540000000000, 0x9500000000000, 0x25400000000000, 0x95000000000000, 0x5400000000012a, 0x5000000000043d, 0x40000000001061}); constexpr StatTable56 SQR2_TABLE_56({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x1000000000000, 0x10000000000000, 0x95, 0x950, 0x9500, 0x95000, 0x950000, 0x9500000, 0x95000000, 0x950000000, 0x9500000000, 0x95000000000, 0x950000000000, 0x9500000000000, 0x95000000000000, 0x5000000000043d, 0x4111, 0x41110, 0x411100, 0x4111000, 0x41110000, 0x411100000, 0x4111000000, 0x41110000000, 0x411100000000, 0x4111000000000, 0x41110000000000, 0x11100000000254, 0x110000000025d5, 0x10000000025dc5, 0x25dcc5, 0x25dcc50, 0x25dcc500, 0x25dcc5000, 0x25dcc50000, 0x25dcc500000, 0x25dcc5000000, 0x25dcc50000000, 0x25dcc500000000, 0x5dcc500000012a, 0xdcc50000001061, 0xcc500000010079, 0xc500000010016c, 0x5000000100103c}); constexpr StatTable56 SQR4_TABLE_56({0x1, 0x10000, 0x100000000, 0x1000000000000, 0x9500, 0x95000000, 0x950000000000, 0x4111, 0x41110000, 0x411100000000, 0x110000000025d5, 0x25dcc500, 0x25dcc5000000, 0xdcc50000001061, 0x10010101, 0x100101010000, 0x1010100000950, 0x1000009509595, 0x95095959500, 0x5095959500043d, 0x95950004115111, 0x41151505011, 0x11515050110254, 0x505011025de985, 0x11025de9a93c10, 0x5de9a93c19c42a, 0xa93c19c400005d, 0x19c4000001000c, 0x100010094, 0x1000100940000, 0x1009400009500, 0x94000095009500, 0x950095418400, 0x954184004111, 0x41840041114111, 0x411141349dd4, 0x1141349dd425d5, 0x349dd425dce0d5, 0xd425dce0cce1b9, 0xdce0cce1ddd461, 0xcce1ddd4011160, 0xddd401110941f5, 0x1110941959dc4, 0x941959dc49cc5, 0x959dc49cc118d5, 0xc49cc1189454b9, 0xc1189454d4d12c, 0x9454d4d14358f8, 0xd4d14358b9aa44, 0x4358b9aa20a205, 0xb9aa20a221d7b8, 0x20a221d7ed10a2, 0x21d7ed10b0f90a, 0xed10b0f918507b, 0xb0f91850000050, 0x1850000001000d}); constexpr StatTable56 SQR8_TABLE_56({0x1, 0x1010100000950, 0x950095418400, 0xd4d14358b9aa44, 0x1135dd851025d5, 0x2c3e45b8a8a9d9, 0xcc39c4d816cc89, 0x51109400, 0x8496c8edb8f151, 0x1c2d7d88406199, 0x3856af0918b2ea, 0x2c26c02be43364, 0x7c13f0a9492898, 0x887abc757e3b3c, 0x10100411009c5, 0x850b98e029a995, 0x18309e7d346f24, 0x49e692600134d8, 0xf902789abce101, 0xed998d1d57187b, 0xa5488e663e846e, 0x84267921a952d0, 0x3d464f2d15176e, 0x801aac9d710b04, 0xfc00d6eb916343, 0x5c7fb78f391c1, 0x745ee236e80ea0, 0x81f8c65be65eac, 0x1940095415941, 0x1188025e2103d0, 0x49c166e0b13f34, 0xbd26558f28a2b3, 0xe147d131ae4b81, 0x25b501ad8ba86d, 0x75fb4e24c70a79, 0x88172901f1684d, 0xb090520bb570a2, 0x963c9b97aad59, 0x39b1e5f12c85a6, 0xd90de4c2bf3055, 0x9c921257e4a1b, 0x45f1f318fef834, 0x48161e1eb09635, 0x10685b397538ce, 0xbc8d4a0c6bc62a, 0xdce738247bfad9, 0x1115b3337d25a4, 0x195bf5a6f0999b, 0xb85101388b2f37, 0x8ee1b2833544cf, 0x49bc1efef7da90, 0x346e404662e355, 0x8c0dab6a1217d6, 0x3cb782ec54c968, 0x5efe07d4f59f4, 0x55f19c0f482900}); constexpr StatTable56 SQR16_TABLE_56({0x1, 0x2563e0b70105c4, 0x48ce07ef5576bb, 0xb94064d844f117, 0x207d2f511ffe3c, 0xf8f6dd1e2a3e6b, 0xe4cc405e0c6cdb, 0xd053f9b827b2bf, 0x550ae8d22edcbf, 0x29f7570f88728b, 0xa06a9e2dfd84a6, 0x55567b9483b3ff, 0x197c6c0d004df6, 0xe106c03f218a16, 0xc50dd2aaf0a388, 0x39473f6702a06c, 0xc8c1736b312ded, 0x992dc692bb707d, 0x24bb9a8dcad06f, 0x9cc45f9e3c2075, 0x455e7271eb130b, 0x847157a5326f59, 0xdc8ccb4ab3f5bd, 0x9463c02c46910d, 0xe1debd0b794514, 0x4c5128db660cde, 0x11910a685416a3, 0x11dfa5b9552a3d, 0x5d902ced822708, 0x794ff735e94601, 0xf1dc5fd7efcf7e, 0x19fb7ff8d06993, 0x7069119ac28a09, 0x98ba5a77d83e7f, 0xf4923dbc1b24e5, 0x7c2dcc84668312, 0xc27e2f5f2243f, 0x78c6d8ebe4bede, 0xad39495debf1a5, 0xa1564b894b50f0, 0x5898ae4e965be9, 0x28aa991e046567, 0x585e95889bb734, 0xc59e73661cf916, 0xed70696926d95d, 0xcca6630954309a, 0x8c4b12ac111264, 0xe8413ad0493e05, 0x1acea73bc9166, 0x9a7f11cd38d12d, 0x390dd1972139ec, 0x9146bc1a4fbff0, 0xd5a1c594335b01, 0x2566272e74ef1a, 0xd4a8baf259e7d0, 0x71e7efd8f20703}); constexpr StatTable56 QRT_TABLE_56({0x10004084, 0xd058f12fd5925e, 0xd058f12fd5925c, 0x41a60b5566d9f0, 0xd058f12fd59258, 0xbda60a142740ba, 0x41a60b5566d9f8, 0xd059f1afc5e688, 0xd058f12fd59248, 0xfc040841615a22, 0xbda60a1427409a, 0xbda60b5426c1ca, 0x41a60b5566d9b8, 0x1a60b4166b950, 0xd059f1afc5e608, 0xfc000041409822, 0xd058f12fd59348, 0xd1ee7a4ef4185c, 0xfc040841615822, 0x9049759b80b4a4, 0xbda60a1427449a, 0xd258e06f301e18, 0xbda60b5426c9ca, 0x6dfeeb3bf6d7d2, 0x41a60b5566c9b8, 0xbdef3ed4ae398a, 0x1a60b41669950, 0xd1ef3f8eeff04c, 0xd059f1afc5a608, 0xbda203340783de, 0xfc000041401822, 0x2dfefbaff2b27a, 0xd058f12fd49348, 0xfdb788a0706776, 0xd1ee7a4ef6185c, 0x2e5de0ae41337a, 0xfc040841655822, 0x41eb17d5ceecf8, 0x9049759b88b4a4, 0x40048874211afc, 0xbda60a1437449a, 0xd04a720f93400c, 0xd258e06f101e18, 0xbc559cf5ac7fce, 0xbda60b5466c9ca, 0x6dc9759b88b4d6, 0x6dfeeb3b76d7d2, 0x92feea7b275af0, 0x41a60b5466c9b8, 0, 0xbdef3ed6ae398a, 0x2811d5edd8ee2a, 0x1a60b45669950, 0xb1a60b5466c9ca, 0xd1ef3f86eff04c, 0xec493582c8f032}); typedef Field<uint64_t, 56, 149, StatTable56, &SQR_TABLE_56, &SQR2_TABLE_56, &SQR4_TABLE_56, &SQR8_TABLE_56, &SQR16_TABLE_56, &QRT_TABLE_56, IdTrans, &ID_TRANS, &ID_TRANS> Field56; #endif } Sketch* ConstructClMul7Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_49 case 49: return new SketchImpl<Field49>(implementation, 49); #endif #ifdef ENABLE_FIELD_INT_50 case 50: return new SketchImpl<Field50>(implementation, 50); #endif #ifdef ENABLE_FIELD_INT_51 case 51: return new SketchImpl<Field51>(implementation, 51); #endif #ifdef ENABLE_FIELD_INT_52 case 52: return new SketchImpl<Field52>(implementation, 52); #endif #ifdef ENABLE_FIELD_INT_53 case 53: return new SketchImpl<Field53>(implementation, 53); #endif #ifdef ENABLE_FIELD_INT_54 case 54: return new SketchImpl<Field54>(implementation, 54); #endif #ifdef ENABLE_FIELD_INT_55 case 55: return new SketchImpl<Field55>(implementation, 55); #endif #ifdef ENABLE_FIELD_INT_56 case 56: return new SketchImpl<Field56>(implementation, 56); #endif } return nullptr; } Sketch* ConstructClMulTri7Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_49 case 49: return new SketchImpl<FieldTri49>(implementation, 49); #endif #ifdef ENABLE_FIELD_INT_52 case 52: return new SketchImpl<FieldTri52>(implementation, 52); #endif #ifdef ENABLE_FIELD_INT_54 case 54: return new SketchImpl<FieldTri54>(implementation, 54); #endif #ifdef ENABLE_FIELD_INT_55 case 55: return new SketchImpl<FieldTri55>(implementation, 55); #endif } return nullptr; }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/clmul_6bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_6) #include "clmul_common_impl.h" #include "../int_utils.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_41 // 41 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5> StatTable41; constexpr StatTable41 SQR_TABLE_41({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x48000, 0x120000, 0x480000, 0x1200000, 0x4800000, 0x12000000, 0x48000000, 0x120000000, 0x480000000, 0x1200000000, 0x4800000000, 0x12000000000, 0x8000000012}); constexpr StatTable41 SQR2_TABLE_41({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x48, 0x480, 0x4800, 0x48000, 0x480000, 0x4800000, 0x48000000, 0x480000000, 0x4800000000, 0x8000000012, 0x104, 0x1040, 0x10400, 0x104000, 0x1040000, 0x10400000, 0x104000000, 0x1040000000, 0x10400000000, 0x4000000048, 0x492, 0x4920, 0x49200, 0x492000, 0x4920000, 0x49200000, 0x492000000, 0x4920000000, 0x9200000012, 0x12000000104}); constexpr StatTable41 SQR4_TABLE_41({0x1, 0x10000, 0x100000000, 0x480, 0x4800000, 0x8000000012, 0x104000, 0x1040000000, 0x4920, 0x49200000, 0x12000000104, 0x1001000, 0x10010000000, 0x48048, 0x480480000, 0x4800001040, 0x10410400, 0x4104000048, 0x492492, 0x4924920000, 0x9200010002, 0x100000100, 0x1000480, 0x10004800000, 0x8000048012, 0x480104000, 0x1040001040, 0x10404920, 0x4049200048, 0x12000492104, 0x4921001000, 0x10010010010, 0x100148048, 0x1480480480, 0x4804805840, 0x8058410412, 0x410410414c, 0x10414d2492, 0x14d24924920, 0x9249259202, 0x12592000004}); constexpr StatTable41 SQR8_TABLE_41({0x1, 0x10410400, 0x100148048, 0x13040000104, 0x11044801040, 0x924da49202, 0x9680490002, 0x82510514c, 0x8481485932, 0xc83144d832, 0x134d34d6db6, 0x18010048012, 0x165db20004c, 0x4800597052, 0x10131135cd0, 0xcd6cc30d32, 0x160586101cc, 0x15c64969da8, 0x179715681cc, 0x12f3c0ffc74, 0xc7dd3dd3ce, 0x10014c968, 0x1b040048116, 0x35d6801044, 0xda4deda6d0, 0x1de94c85852, 0x1083500114c, 0xc4c9685dfa, 0x18515c6d592, 0x17de69aed7e, 0x16c6c8a6c6c, 0x165cfe1044c, 0xdb004cf018, 0x7075031c98, 0x1d9a90b0d72, 0x1bb2485caee, 0x1cbe4dfd48a, 0x1f1540b7400, 0xc62bc7fd02, 0x147b5103f2e, 0x390ee8bcc6}); constexpr StatTable41 SQR16_TABLE_41({0x1, 0x61deee38fe, 0xe00adae2e, 0x1ea53eaa95a, 0x503e540566, 0xabc8e7f89a, 0x1bf760d86ac, 0x94cce9c722, 0x15c8006ee5c, 0x7aba20c1da, 0x12662a9603e, 0x5fe76acec4, 0x1e6beca9e42, 0x1efc8f7a000, 0x165997c6d7e, 0xee947a07ee, 0xd9bd741142, 0xaa304566c0, 0x5fe336e356, 0x11f1021b80c, 0xd34e5a1674, 0x99ed56b9dc, 0x9afae0eca, 0x1a5830b390e, 0x1be1a63eb7e, 0x141e77e141c, 0xee3be92168, 0xa93823d65c, 0x18a59f4b19c, 0xce69942af6, 0x3f7b319c0e, 0xba83a4a7b4, 0x7da4b6fcde, 0x17f79268f10, 0x1222602d048, 0x1b4b2f326b8, 0x159abff0786, 0xb35534a7a2, 0x84bbc48050, 0x173d5cbf330, 0x2897dd6f58}); constexpr StatTable41 QRT_TABLE_41({0, 0x1599a5e0b0, 0x1599a5e0b2, 0x105c119e0, 0x1599a5e0b6, 0x1a2030452a6, 0x105c119e8, 0x1a307c55b2e, 0x1599a5e0a6, 0x1ee3f47bc8e, 0x1a203045286, 0x400808, 0x105c119a8, 0x1a3038573a6, 0x1a307c55bae, 0x4d2882a520, 0x1599a5e1a6, 0x1ffbaa0b720, 0x1ee3f47be8e, 0x4d68c22528, 0x1a203045686, 0x200006, 0x400008, 0x1b79a21b200, 0x105c109a8, 0x1ef3886a526, 0x1a3038553a6, 0x1b692209200, 0x1a307c51bae, 0x5d99a4e1a6, 0x4d28822520, 0x185e109ae, 0x1599a4e1a6, 0x4e3f43be88, 0x1ffbaa2b720, 0x4000000000, 0x1ee3f43be8e, 0x18000000006, 0x4d68ca2528, 0xa203145680, 0x1a203145686}); typedef Field<uint64_t, 41, 9, StatTable41, &SQR_TABLE_41, &SQR2_TABLE_41, &SQR4_TABLE_41, &SQR8_TABLE_41, &SQR16_TABLE_41, &QRT_TABLE_41, IdTrans, &ID_TRANS, &ID_TRANS> Field41; typedef FieldTri<uint64_t, 41, 3, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5>, &SQR_TABLE_41, &SQR2_TABLE_41, &SQR4_TABLE_41, &SQR8_TABLE_41, &SQR16_TABLE_41, &QRT_TABLE_41, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri41; #endif #ifdef ENABLE_FIELD_INT_42 // 42 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6> StatTable42; constexpr StatTable42 SQR_TABLE_42({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x81, 0x204, 0x810, 0x2040, 0x8100, 0x20400, 0x81000, 0x204000, 0x810000, 0x2040000, 0x8100000, 0x20400000, 0x81000000, 0x204000000, 0x810000000, 0x2040000000, 0x8100000000, 0x20400000000, 0x1000000102, 0x4000000408, 0x10000001020}); constexpr StatTable42 SQR2_TABLE_42({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x204, 0x2040, 0x20400, 0x204000, 0x2040000, 0x20400000, 0x204000000, 0x2040000000, 0x20400000000, 0x4000000408, 0x4001, 0x40010, 0x400100, 0x4001000, 0x40010000, 0x400100000, 0x4001000000, 0x10000081, 0x100000810, 0x1000008100, 0x10000081000, 0x810204, 0x8102040, 0x81020400, 0x810204000, 0x8102040000, 0x1020400102, 0x10204001020, 0x2040010004, 0x20400100040, 0x4001000008}); constexpr StatTable42 SQR4_TABLE_42({0x1, 0x10000, 0x100000000, 0x2040, 0x20400000, 0x4000000408, 0x4001000, 0x10000081, 0x810204, 0x8102040000, 0x20400100040, 0x1000000100, 0x1020400, 0x10204000000, 0x200001, 0x2000010000, 0x100040800, 0x408002040, 0x20408002, 0x4080020408, 0x204000020, 0x204001, 0x2040010000, 0x100040010, 0x400102040, 0x1020408100, 0x4081020008, 0x10200000020, 0x80, 0x800000, 0x8000000000, 0x102000, 0x1020000000, 0x20008, 0x200080000, 0x800004080, 0x40810200, 0x8102000810, 0x20008000040, 0x8102, 0x81020000, 0x10200001020}); constexpr StatTable42 SQR8_TABLE_42({0x1, 0x100040800, 0x1020000000, 0x10200001000, 0x2040810000, 0x408102040, 0x4080000408, 0x10000000, 0x8002040810, 0x20008000, 0x10200080000, 0x40000004, 0x20408000040, 0x4000020000, 0x204000, 0x8002040010, 0x408102, 0x200081020, 0x40810000, 0x2000, 0x81000408, 0x4001, 0x2040010, 0x1020008002, 0x10204081020, 0x800004, 0x20000000000, 0x4081000400, 0x10000081, 0x100040010, 0x8102, 0x10000000020, 0x40010200, 0x408000000, 0x4080000400, 0x810204000, 0x102040810, 0x1020000102, 0x4000000, 0x2000810204, 0x8002000, 0x4080020000}); constexpr StatTable42 SQR16_TABLE_42({0x1, 0x40800204, 0x2000800, 0x20008002040, 0x408100, 0x20000, 0x10004081020, 0x10000081, 0x40010204, 0x8102000000, 0x400000000, 0x1020008102, 0x1020408, 0x204081020, 0x200001, 0x10200, 0x102000010, 0x20408100000, 0x1020408002, 0x4000020000, 0x204000000, 0x204001, 0x2000800004, 0x8100000010, 0x400102000, 0x8002, 0x4080020000, 0x10000001000, 0x80, 0x2040010200, 0x100040000, 0x400100040, 0x20408000, 0x1000000, 0x204080020, 0x800004080, 0x2000810200, 0x8100000810, 0x20000000000, 0x1000408002, 0x81020400, 0x10204081000}); constexpr StatTable42 QRT_TABLE_42({0x810200080, 0x120810806, 0x120810804, 0x1068c1a1000, 0x120810800, 0x34005023008, 0x1068c1a1008, 0x800004080, 0x120810810, 0x162818a10, 0x34005023028, 0x42408a14, 0x1068c1a1048, 0x1001040, 0x800004000, 0xb120808906, 0x120810910, 0x34000020068, 0x162818810, 0x68c021400, 0x34005023428, 0x10004000, 0x42408214, 0x162418214, 0x1068c1a0048, 0xb002018116, 0x1003040, 0x10008180448, 0x800000000, 0x62c08b04, 0xb120800906, 0x2408d1a3060, 0x120800910, 0x34401003028, 0x34000000068, 0, 0x162858810, 0xa042058116, 0x68c0a1400, 0x8162858806, 0x34005123428, 0x3068c0a1468}); typedef Field<uint64_t, 42, 129, StatTable42, &SQR_TABLE_42, &SQR2_TABLE_42, &SQR4_TABLE_42, &SQR8_TABLE_42, &SQR16_TABLE_42, &QRT_TABLE_42, IdTrans, &ID_TRANS, &ID_TRANS> Field42; typedef FieldTri<uint64_t, 42, 7, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6>, &SQR_TABLE_42, &SQR2_TABLE_42, &SQR4_TABLE_42, &SQR8_TABLE_42, &SQR16_TABLE_42, &QRT_TABLE_42, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri42; #endif #ifdef ENABLE_FIELD_INT_43 // 43 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5, 5, 5> StatTable43; constexpr StatTable43 SQR_TABLE_43({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0xb2, 0x2c8, 0xb20, 0x2c80, 0xb200, 0x2c800, 0xb2000, 0x2c8000, 0xb20000, 0x2c80000, 0xb200000, 0x2c800000, 0xb2000000, 0x2c8000000, 0xb20000000, 0x2c80000000, 0xb200000000, 0x2c800000000, 0x32000000059, 0x4800000013d, 0x20000000446}); constexpr StatTable43 SQR2_TABLE_43({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0xb2, 0xb20, 0xb200, 0xb2000, 0xb20000, 0xb200000, 0xb2000000, 0xb20000000, 0xb200000000, 0x32000000059, 0x20000000446, 0x4504, 0x45040, 0x450400, 0x4504000, 0x45040000, 0x450400000, 0x4504000000, 0x45040000000, 0x504000002c8, 0x4000002efa, 0x4000002efa0, 0x2ef8c8, 0x2ef8c80, 0x2ef8c800, 0x2ef8c8000, 0x2ef8c80000, 0x2ef8c800000, 0x6f8c800013d, 0x78c80001025, 0xc800010117, 0x48000101129}); constexpr StatTable43 SQR4_TABLE_43({0x1, 0x10000, 0x100000000, 0xb20, 0xb200000, 0x32000000059, 0x450400, 0x4504000000, 0x4000002efa0, 0x2ef8c8000, 0x78c80001025, 0x10110010, 0x11001000b2, 0x1000b2b920, 0xb2b920b200, 0x120b204545f, 0x20454554046, 0x45540506efa, 0x506ed4df68, 0x6d4df6a79f5, 0x76a79c80133, 0x1c801010007, 0x101000b2100, 0xb210b2b20, 0x10b2b204504, 0x320450f655d, 0x50f654106c8, 0x54106efcb4c, 0x6efcb696320, 0x369631c93e1, 0x31c93ff9d8c, 0x3ff9d91a2a2, 0x591a2b9839b, 0x2b983b98dd4, 0x3b98dc651b0, 0x5c651a971e9, 0x1a971c9c0ba, 0x1c9c0b5853e, 0xb585322d78, 0x5322d7c6430, 0x57c6416617d, 0x4166159c82c, 0x159c8000b6c}); constexpr StatTable43 SQR8_TABLE_43({0x1, 0x20454554046, 0x591a2b9839b, 0x722ff9f6fe9, 0x6a269c1eb12, 0xa3ce9f234e, 0x4d9ba8aae0b, 0x392cf0cf99b, 0x465f8594525, 0x4f9c1fb1524, 0x3b1a1dd441c, 0x381edd42255, 0x37a599424b, 0x554caee8670, 0x5335bb91d81, 0x69288c8a1a3, 0x3df2b6e68e5, 0x75330d31d56, 0x51a604b090c, 0x32e0d5a7ca3, 0x41eb9d4896e, 0x633e2855c9f, 0x4780d70e32f, 0x73b0cd728c3, 0x16627402bad, 0x4418f2a818a, 0x5cdd06cf7e5, 0x2a8da97a3ae, 0x446864a8976, 0x5a7bcbd45ea, 0x4034a4b8b04, 0x6bdaac9c5fa, 0x18769ce3a67, 0x560278257c, 0x41c06d6b64c, 0x69f6f61bd4b, 0x16cc45f84fd, 0x53f6b42f0f0, 0x6cac3d234f3, 0x1f94e8f24d5, 0x319342c7148, 0x8685bca86d, 0x6b694a6ea66}); constexpr StatTable43 SQR16_TABLE_43({0x1, 0x1ce77599049, 0x191715250a, 0xc1573d8dff, 0x118e73ab5e4, 0x4b6a83225fe, 0x72b4bc8e0f5, 0x4a4b2b6bb02, 0x66daf4741e9, 0x50baba19898, 0x5eb38771912, 0x6fb458aad3c, 0x5ce3b10bde9, 0x5575f3498f0, 0x5f075aa8a0a, 0x41d0aa8ee20, 0x609e3c78c28, 0xe2e45a8018, 0x523ac062837, 0x738388a569d, 0x6616ec46da9, 0x1a75cc16d96, 0x49b0b43bbc3, 0x400416b3c9a, 0x25813f41ffe, 0x309fdb9d0bc, 0x489f45b2cbf, 0xa141f4f88e, 0x739e0d11fb3, 0x44971f51cc0, 0x6490576e60e, 0x6c6674c5355, 0x6978126a4e1, 0x3d04eae5a5, 0x312eed633f2, 0x1de4b98d6b9, 0x118a106fb0a, 0x26dae025f4, 0x5c179312ebb, 0x75870ef1921, 0x60e9fed95c0, 0x209ab92427a, 0x1c5014a1937}); constexpr StatTable43 QRT_TABLE_43({0x2bccc2d6f6c, 0x4bccc2d6f54, 0x4bccc2d6f56, 0x7cc7bc61df0, 0x4bccc2d6f52, 0x7d13b404b10, 0x7cc7bc61df8, 0x37456e9ac5a, 0x4bccc2d6f42, 0x4e042c6a6, 0x7d13b404b30, 0x4a56de9ef4c, 0x7cc7bc61db8, 0x14bc18d8e, 0x37456e9acda, 0x7c89f84fb1e, 0x4bccc2d6e42, 0x7ffae40d210, 0x4e042c4a6, 0x366f45dd06, 0x7d13b404f30, 0x496fcaf8cca, 0x4a56de9e74c, 0x370b62b6af4, 0x7cc7bc60db8, 0x1498185a8, 0x14bc1ad8e, 0x7e602c46a98, 0x37456e9ecda, 0x36ccc2c6e74, 0x7c89f847b1e, 0x7e27d06d516, 0x4bccc2c6e42, 0x7f93302c396, 0x7ffae42d210, 0x3dd3440706, 0x4e046c4a6, 0x78bbc09da36, 0x366f4ddd06, 0, 0x7d13b504f30, 0x8bbc09da00, 0x496fc8f8cca}); typedef Field<uint64_t, 43, 89, StatTable43, &SQR_TABLE_43, &SQR2_TABLE_43, &SQR4_TABLE_43, &SQR8_TABLE_43, &SQR16_TABLE_43, &QRT_TABLE_43, IdTrans, &ID_TRANS, &ID_TRANS> Field43; #endif #ifdef ENABLE_FIELD_INT_44 // 44 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5, 5> StatTable44; constexpr StatTable44 SQR_TABLE_44({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x21, 0x84, 0x210, 0x840, 0x2100, 0x8400, 0x21000, 0x84000, 0x210000, 0x840000, 0x2100000, 0x8400000, 0x21000000, 0x84000000, 0x210000000, 0x840000000, 0x2100000000, 0x8400000000, 0x21000000000, 0x84000000000, 0x10000000042, 0x40000000108}); constexpr StatTable44 SQR2_TABLE_44({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x21, 0x210, 0x2100, 0x21000, 0x210000, 0x2100000, 0x21000000, 0x210000000, 0x2100000000, 0x21000000000, 0x10000000042, 0x401, 0x4010, 0x40100, 0x401000, 0x4010000, 0x40100000, 0x401000000, 0x4010000000, 0x40100000000, 0x1000000084, 0x10000000840, 0x8421, 0x84210, 0x842100, 0x8421000, 0x84210000, 0x842100000, 0x8421000000, 0x84210000000, 0x42100000108, 0x21000001004, 0x10000010002}); constexpr StatTable44 SQR4_TABLE_44({0x1, 0x10000, 0x100000000, 0x210, 0x2100000, 0x21000000000, 0x40100, 0x401000000, 0x10000000840, 0x8421000, 0x84210000000, 0x100001, 0x1000010000, 0x100002100, 0x21000210, 0x10002100042, 0x21000401000, 0x4010040100, 0x401008421, 0x10084210840, 0x42108421108, 0x84211000010, 0x10000000001, 0x31000, 0x310000000, 0x611, 0x6110000, 0x61100000000, 0xc4310, 0xc43100000, 0x31000001844, 0x18421100, 0x84211000021, 0x10000310001, 0x3100031000, 0x310006110, 0x61100611, 0x110061100c6, 0x61100c43100, 0xc4310c4310, 0x10c43118423, 0x31184210844, 0x42108421218, 0x84212100010}); constexpr StatTable44 SQR8_TABLE_44({0x1, 0x21000401000, 0x84211000021, 0xa521000, 0x42108421719, 0x311e5310e55, 0x10401008c61, 0x3210031000, 0x10c43058522, 0x74110050101, 0xf5312e97201, 0x42108421109, 0x21061501611, 0x94311002961, 0xf59421000, 0x52d4b56923a, 0x201e5300e54, 0x71501c8fe71, 0xb6002131043, 0xb5e4c168432, 0xb320f5619ae, 0xf5000f97201, 0x10c43118422, 0x24010451100, 0x942113d4330, 0x8421a521001, 0x6310e130719, 0xf72fc731c6c, 0x4ae739631, 0x70008417e4d, 0x20ca6358b77, 0x64110094a51, 0xd4002e97200, 0xf7f5a13853a, 0xb12664417f6, 0x843322d6860, 0xf7c4100194d, 0x7382d17842b, 0xf67fd71a10c, 0x6efcca4b731, 0xf4e5901ea2d, 0xcb8278a46, 0xa32050401ee, 0xb7218bb6518}); constexpr StatTable44 SQR16_TABLE_44({0x1, 0xc6cdb660138, 0x13de5a69a7b, 0x80bcafe7981, 0x60eb6f976d1, 0x677fbef6cce, 0x1549bb4cdec, 0x3b1ddf6859, 0xc01b8da28a6, 0xf3e11efbf8c, 0xd3e6faf8ee3, 0xa3dbc5712c8, 0x72361d7ca84, 0xe59e509337d, 0x15fca12a6f4, 0x33ce445498c, 0x44406de91fb, 0x9784b690571, 0xb0fb81753af, 0xb53a7c2c977, 0x34fbd3dba9b, 0xc758c22e647, 0xd5ff69aa469, 0x41e6d42b47d, 0xa4d1a3d02e7, 0x365db54ae9f, 0xd2293b8770b, 0xf1bf95c7746, 0x337fbe1d950, 0x726879e26a7, 0xa4be5ec2171, 0x7080da9df82, 0x7560017ce2, 0xd03997e34ae, 0x27ad4309a78, 0xb7b0ead892b, 0xf45bedb915d, 0xc4f0e25a52c, 0xe774a9d7fe8, 0xece6c1d7a26, 0xf20ea9ab655, 0x159bb624dc2, 0x12f2780b45f, 0x840cc52f19d}); constexpr StatTable44 QRT_TABLE_44({0xf05334f4f6e, 0x4002016, 0x4002014, 0xf04350e6246, 0x4002010, 0x4935b379a26, 0xf04350e624e, 0xf84250c228e, 0x4002000, 0xf04300e521e, 0x4935b379a06, 0xb966838dd48, 0xf04350e620e, 0xf7b8b80feda, 0xf84250c220e, 0xf972e097d5e, 0x4002100, 0x8000020000, 0xf04300e501e, 0x430025000, 0x4935b379e06, 0xf976a09dc5e, 0xb966838d548, 0xf84218c029a, 0xf04350e720e, 0x4925f36bf06, 0xf7b8b80deda, 0xb047d3ee758, 0xf84250c620e, 0xf80350e720e, 0xf972e09fd5e, 0x8091825284, 0x4012100, 0x9015063210, 0x8000000000, 0xff31a028c5e, 0xf04300a501e, 0x44340b7100, 0x4300a5000, 0, 0x4935b279e06, 0xa976b2dce18, 0xf976a29dc5e, 0x8935b279e18}); typedef Field<uint64_t, 44, 33, StatTable44, &SQR_TABLE_44, &SQR2_TABLE_44, &SQR4_TABLE_44, &SQR8_TABLE_44, &SQR16_TABLE_44, &QRT_TABLE_44, IdTrans, &ID_TRANS, &ID_TRANS> Field44; typedef FieldTri<uint64_t, 44, 5, RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5, 5>, &SQR_TABLE_44, &SQR2_TABLE_44, &SQR4_TABLE_44, &SQR8_TABLE_44, &SQR16_TABLE_44, &QRT_TABLE_44, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri44; #endif #ifdef ENABLE_FIELD_INT_45 // 45 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5> StatTable45; constexpr StatTable45 SQR_TABLE_45({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x36, 0xd8, 0x360, 0xd80, 0x3600, 0xd800, 0x36000, 0xd8000, 0x360000, 0xd80000, 0x3600000, 0xd800000, 0x36000000, 0xd8000000, 0x360000000, 0xd80000000, 0x3600000000, 0xd800000000, 0x36000000000, 0xd8000000000, 0x16000000001b, 0x18000000005a}); constexpr StatTable45 SQR2_TABLE_45({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0xd8, 0xd80, 0xd800, 0xd8000, 0xd80000, 0xd800000, 0xd8000000, 0xd80000000, 0xd800000000, 0xd8000000000, 0x18000000005a, 0x514, 0x5140, 0x51400, 0x514000, 0x5140000, 0x51400000, 0x514000000, 0x5140000000, 0x51400000000, 0x114000000036, 0x1400000003b8, 0x3b6e, 0x3b6e0, 0x3b6e00, 0x3b6e000, 0x3b6e0000, 0x3b6e00000, 0x3b6e000000, 0x3b6e0000000, 0x1b6e0000001b, 0x16e00000011f, 0xe0000001105}); constexpr StatTable45 SQR4_TABLE_45({0x1, 0x10000, 0x100000000, 0xd8, 0xd80000, 0xd800000000, 0x5140, 0x51400000, 0x114000000036, 0x3b6e00, 0x3b6e000000, 0xe0000001105, 0x11011000, 0x110110000000, 0x1000000d58d8, 0xd58d58000, 0x18d58000054e, 0x5451454, 0x54514540000, 0x145400038db8, 0x38db6d8e0, 0xdb6d8e00104, 0x18e00101000a, 0x10100010100, 0x10100d8d8, 0x100d8d800d8, 0x18d800d8d85a, 0xd8d8511140, 0x18511140511a, 0x114051117b58, 0x11117b556e36, 0x1b556e3b5575, 0xe3b557f1015, 0x157f1011011e, 0x101101101c48, 0x1101c458d58, 0x1c458d58d580, 0xd58d58815d4, 0x158815d1451a, 0x15d1451452c0, 0x51452ce6f6e, 0x12ce6f6db6d6, 0xf6db6da6e3d, 0x16da6e39e00f, 0xe39e00000dd}); constexpr StatTable45 SQR8_TABLE_45({0x1, 0x18d58000054e, 0xe3b557f1015, 0x51985198, 0xdb68cb55452, 0x1d0cc1d84f02, 0x140110c19ae, 0x11a16a14e7fe, 0x1e7ca7c62aa9, 0xe0eae26629b, 0x12182bee80ab, 0x1a38a68f28d3, 0x8581419c8c, 0x1d47f6f12ebc, 0x19fd34c3806e, 0x12ddba59f3cd, 0x10fa07f12a0e, 0x1d93eb544486, 0x1cf42cd119be, 0x1ff32d4b62c3, 0xf34ae031191, 0xada837715bf, 0xd368a753f92, 0x2ba87b17a03, 0x10374c3e4088, 0x1a6f539c11bd, 0x16548a5473c7, 0x1eb70011a8c9, 0x1ee5435ba1a3, 0x1173c0537680, 0xa1a3668dd6b, 0x119faad25e8, 0xd3909240e00, 0x1b560d018881, 0x127ecb9095ed, 0x306b507e701, 0x12b934c21ea3, 0x1a9d258c5b8b, 0x10452fbf0b1c, 0xae92fee120d, 0x183eb4b419fa, 0xc24d2391313, 0x4e6c4746f6, 0x2815fe7c395, 0xe4ab383747f}); constexpr StatTable45 SQR16_TABLE_45({0x1, 0x14af92df932, 0x484e0190bdc, 0xda69889e16e, 0xcf70dfdb150, 0x18c6743571a8, 0x1b2c3ad7fa79, 0x5f0cbe204f6, 0xee973392a75, 0x3e86ef79673, 0xb2a9bef7181, 0x19b5347ff116, 0x1cae0ec79856, 0x69093f18f81, 0x1964382be09a, 0x92c894b073e, 0x1d99d2922eb2, 0x647905ad0eb, 0x1695971acdd3, 0x8f3292bc8c4, 0x1ee4057ad94, 0x17f02dc60e01, 0x1bb8e05ab4d5, 0x14de5d2a05d6, 0x13a019a02983, 0xcd7097c3616, 0x1bd798639b8f, 0x1cf0ca5ac7b2, 0xa93b983cf05, 0x159a955a2aa8, 0x69e5ba33397, 0x3a6b3392237, 0x26aeab71e13, 0x26fe04d38b9, 0x1fa9df0e8c45, 0x104e85c234b0, 0x1792853f8767, 0x81573b15f20, 0x127d6bfb06d3, 0x8110e6957e8, 0x11f59cbcc110, 0xad68264cad8, 0x61438575b35, 0x56e4446dc, 0x1cc9cb28b150}); constexpr StatTable45 QRT_TABLE_45({0xede34e3e0fc, 0x1554148191aa, 0x1554148191a8, 0x1767be1dc4a6, 0x1554148191ac, 0x26bd4931492, 0x1767be1dc4ae, 0x233ab9c454a, 0x1554148191bc, 0x16939e8bb3dc, 0x26bd49314b2, 0x3c6ca8bac52, 0x1767be1dc4ee, 0x16caa5054c16, 0x233ab9c45ca, 0x14a1649628bc, 0x1554148190bc, 0x3c382881252, 0x16939e8bb1dc, 0x3c7ca0aa160, 0x26bd49310b2, 0x27f40158000, 0x3c6ca8ba452, 0x173fc092853c, 0x1767be1dd4ee, 0x16cbe284f25c, 0x16caa5056c16, 0x155559002f96, 0x233ab9c05ca, 0x26eb8908b32, 0x14a16496a8bc, 0x15440885333c, 0x1554148090bc, 0x17d60702e0, 0x3c3828a1252, 0x54548d10b2, 0x16939e8fb1dc, 0x3ac1e81b1d2, 0x3c7ca02a160, 0x166bd48310bc, 0x26bd48310b2, 0, 0x27f40358000, 0x10000000000e, 0x3c6cacba452}); typedef Field<uint64_t, 45, 27, StatTable45, &SQR_TABLE_45, &SQR2_TABLE_45, &SQR4_TABLE_45, &SQR8_TABLE_45, &SQR16_TABLE_45, &QRT_TABLE_45, IdTrans, &ID_TRANS, &ID_TRANS> Field45; #endif #ifdef ENABLE_FIELD_INT_46 // 46 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5> StatTableTRI46; constexpr StatTableTRI46 SQR_TABLE_TRI46({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000, 0x30000000, 0xc0000000, 0x300000000, 0xc00000000, 0x3000000000, 0xc000000000, 0x30000000000, 0xc0000000000, 0x300000000000}); constexpr StatTableTRI46 SQR2_TABLE_TRI46({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0xc, 0xc0, 0xc00, 0xc000, 0xc0000, 0xc00000, 0xc000000, 0xc0000000, 0xc00000000, 0xc000000000, 0xc0000000000, 0x5, 0x50, 0x500, 0x5000, 0x50000, 0x500000, 0x5000000, 0x50000000, 0x500000000, 0x5000000000, 0x50000000000, 0x100000000003, 0x3c, 0x3c0, 0x3c00, 0x3c000, 0x3c0000, 0x3c00000, 0x3c000000, 0x3c0000000, 0x3c00000000, 0x3c000000000, 0x3c0000000000}); constexpr StatTableTRI46 SQR4_TABLE_TRI46({0x1, 0x10000, 0x100000000, 0xc, 0xc0000, 0xc00000000, 0x50, 0x500000, 0x5000000000, 0x3c0, 0x3c00000, 0x3c000000000, 0x1100, 0x11000000, 0x110000000000, 0xcc00, 0xcc000000, 0xc0000000005, 0x55000, 0x550000000, 0x10000000003f, 0x3fc000, 0x3fc0000000, 0x101, 0x1010000, 0x10100000000, 0xc0c, 0xc0c0000, 0xc0c00000000, 0x5050, 0x50500000, 0x105000000003, 0x3c3c0, 0x3c3c00000, 0x3c000000011, 0x111100, 0x1111000000, 0x1100000000cc, 0xcccc00, 0xcccc000000, 0xc0000000555, 0x5555000, 0x55550000000, 0x100000003fff, 0x3fffc000, 0x3fffc0000000}); constexpr StatTableTRI46 SQR8_TABLE_TRI46({0x1, 0xcc000000, 0x3c3c0, 0x10000000c, 0x550055000, 0x3c000111111, 0xc0050, 0x103fc000003f, 0x1111cccc00, 0x5000500390, 0x13ec1010101, 0xcccc9999955, 0x5000001100, 0xc0c01010000, 0xc003fffc555, 0x12c003c0cc00, 0x10505c5c0c0f, 0x155450003ffe, 0x1100cc054100, 0xfcc5053c3d1, 0xd3ff2c00d, 0xd059c3a5c3a, 0x2828282d21e, 0x5000000001, 0xcd010000, 0xc000003c695, 0x3c103c0000c, 0x55c095c0c, 0x169550112eee, 0x1100000c1150, 0x1c339050003f, 0x112e320c01, 0x1d50cc50cf95, 0x116d5292c2c2, 0xcccc9959954, 0x1050cc00113f, 0xc1d1002c3c0, 0xc013fafc509, 0x12fa93c59d01, 0x135c9081d11e, 0x150453cc3fae, 0x13f0d044d33, 0x688119f0a84, 0x39d2d62d29d, 0x3751370167, 0x24e4e4e4b4b4}); constexpr StatTableTRI46 SQR16_TABLE_TRI46({0x1, 0x1fe6e1ab503e, 0xbbae1f3f55b, 0x1d51cc530c59, 0x163a6a22e14a, 0x5847feb7f81, 0x1ec9cc5fd281, 0xf6cc7b80c70, 0x8f46b31e374, 0xc13bf2ed37d, 0x148a1595bffe, 0x581ad245849, 0x1ea6920b83c1, 0x9d9a8355c7d, 0x6bcf393d5ff, 0x1d4e245085c0, 0x602a8c5e62c, 0x1922dd69197f, 0x7945d3a2aad, 0xf82a823f768, 0xdd24665599b, 0x13b43f6a29d, 0x4df114f238d, 0x1ee783c75ec0, 0xfb670f65c31, 0xf855dc973d2, 0x61ede5f2651, 0x6c1a1266403, 0x1f66ed2a96a, 0xbbbdf683148, 0x1ecc83e160c0, 0x1a2778c4bc0c, 0x10e154273753, 0x1704f8873c23, 0x1b4d3172da99, 0x2b3be805044, 0x5bb08848b9d, 0x1967d2b99be5, 0x7fa55262740, 0xe761a27cc28, 0x17dedd7181b5, 0x155b0344714a, 0x15187b38816e, 0xc5a679b5300, 0x1096cbf94c5d, 0x3f6b3cc122da}); constexpr StatTableTRI46 QRT_TABLE_TRI46({0x211c4fd486ba, 0x100104a, 0x1001048, 0x104d0492d4, 0x100104c, 0x20005040c820, 0x104d0492dc, 0x40008080, 0x100105c, 0x24835068ce00, 0x20005040c800, 0x200000400800, 0x104d04929c, 0x100904325c, 0x40008000, 0x25da9e77daf0, 0x100115c, 0x1184e1696f0, 0x24835068cc00, 0x24825169dd5c, 0x20005040cc00, 0x3ea3241c60c0, 0x200000400000, 0x211c4e5496f0, 0x104d04829c, 0x20005340d86c, 0x100904125c, 0x24835968de5c, 0x4000c000, 0x6400a0c0, 0x25da9e775af0, 0x118cf1687ac, 0x101115c, 0x1ea1745cacc0, 0x1184e1496f0, 0x20181e445af0, 0x2483506ccc00, 0x20240060c0, 0x24825161dd5c, 0x1e21755dbd9c, 0x20005050cc00, 0x26a3746cacc0, 0x3ea3243c60c0, 0xea3243c60c0, 0x200000000000, 0}); typedef FieldTri<uint64_t, 46, 1, StatTableTRI46, &SQR_TABLE_TRI46, &SQR2_TABLE_TRI46, &SQR4_TABLE_TRI46, &SQR8_TABLE_TRI46, &SQR16_TABLE_TRI46, &QRT_TABLE_TRI46, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri46; #endif #ifdef ENABLE_FIELD_INT_47 // 47 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5> StatTable47; constexpr StatTable47 SQR_TABLE_47({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x42, 0x108, 0x420, 0x1080, 0x4200, 0x10800, 0x42000, 0x108000, 0x420000, 0x1080000, 0x4200000, 0x10800000, 0x42000000, 0x108000000, 0x420000000, 0x1080000000, 0x4200000000, 0x10800000000, 0x42000000000, 0x108000000000, 0x420000000000, 0x80000000042, 0x200000000108}); constexpr StatTable47 SQR2_TABLE_47({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x42, 0x420, 0x4200, 0x42000, 0x420000, 0x4200000, 0x42000000, 0x420000000, 0x4200000000, 0x42000000000, 0x420000000000, 0x200000000108, 0x1004, 0x10040, 0x100400, 0x1004000, 0x10040000, 0x100400000, 0x1004000000, 0x10040000000, 0x100400000000, 0x4000000042, 0x40000000420, 0x400000004200, 0x42108, 0x421080, 0x4210800, 0x42108000, 0x421080000, 0x4210800000, 0x42108000000, 0x421080000000, 0x210800000108, 0x108000001004, 0x80000010002}); constexpr StatTable47 SQR4_TABLE_47({0x1, 0x10000, 0x100000000, 0x42, 0x420000, 0x4200000000, 0x1004, 0x10040000, 0x100400000000, 0x42108, 0x421080000, 0x210800000108, 0x1000010, 0x10000100000, 0x1000004200, 0x42000420, 0x420004200000, 0x42000100400, 0x1004010040, 0x40100400420, 0x4004210842, 0x42108421080, 0x84210810002, 0x108100000004, 0x142, 0x1420000, 0x14200000000, 0x5204, 0x52040000, 0x520400000000, 0x142508, 0x1425080000, 0x250800000528, 0x5210810, 0x52108100000, 0x81000014202, 0x142001420, 0x420014200042, 0x142000520400, 0x5204052040, 0x40520401424, 0x20401425094a, 0x142509425080, 0x9425085210a, 0x508521084204, 0x21084210804a, 0x421080420010}); constexpr StatTable47 SQR8_TABLE_47({0x1, 0x420004200000, 0x250800000528, 0x11004, 0xc6210910402, 0x142005730c10, 0x101000010, 0x1056050040, 0x55a429184204, 0x111404110002, 0x532408500562, 0x3d196251d62e, 0x420142, 0x44524611c66, 0x1142047728, 0x46205e2508, 0x67339c2519da, 0x5661384b5880, 0x434346200424, 0x392938cb55aa, 0x724b0c31058c, 0x7f4f1cf703fc, 0x4fe303d32d1e, 0x75de250d676c, 0x100400011004, 0xc6210910540, 0x102525331834, 0x1101046318, 0x1057532548, 0x37f4bd7f4b5e, 0x115021380840, 0x52674a501142, 0x297a4a1b86ae, 0x666b0c2010ca, 0x776839031b88, 0x4b5316a05622, 0x254e215e2030, 0x6733ce2009de, 0xa8609d21e86, 0x567347420874, 0x6e0d31db55ba, 0x4357182485c4, 0x2afb35ef02ba, 0x5af227961c30, 0x64faad1b0116, 0x2d5d2527ef40, 0x6e27e3bc1978}); constexpr StatTable47 SQR16_TABLE_47({0x1, 0x421ac25c8774, 0x30581389b510, 0x423b9c671db0, 0xa4537914208, 0x38f9be0dbf38, 0x351c5a8b92a8, 0xc38b9920da2, 0x508d34674f2a, 0x1f8c359a6b76, 0x5ac4bf86daaa, 0x51d6a6616df2, 0xe2717a0378a, 0x13353e783e6e, 0x55a55ac09ec6, 0x3f17cde43402, 0x760584b64b6c, 0x6acbecc99a02, 0x16be80e45b76, 0x2d5069e0005a, 0x3388f5759aa6, 0x2f98f891f4e2, 0x7657f368d924, 0x48f81e34f5b0, 0x51a9087f072e, 0x1de01ba9001c, 0x560b4b374bfc, 0x13f576988ff0, 0x3673cd322294, 0x595959f7c5fe, 0xbfa426eb4a4, 0x2b68fd7c02c2, 0x2a3c1437913a, 0x6e4b179fcf9e, 0x69ddf09bbdee, 0x7b91973d5e52, 0x1329cefd9514, 0x6a5f380b7ab0, 0x48e6620529c4, 0x60589a4b95b6, 0x5e4bd1d1aa34, 0x4b1ec7645cc2, 0x5cfb8785aec6, 0x34e47cf10c3a, 0x7b6c363eee10, 0x1dc52d768b32, 0x3585af9113a0}); constexpr StatTable47 QRT_TABLE_47({0, 0x1001040, 0x1001042, 0x1047043076, 0x1001046, 0x112471c241e, 0x104704307e, 0x4304e052168, 0x1001056, 0x10004000, 0x112471c243e, 0x172a09c949d6, 0x104704303e, 0x4002020, 0x4304e0521e8, 0x5400e220, 0x1001156, 0x172b08c85080, 0x10004200, 0x41200b0800, 0x112471c203e, 0x172f0cca50a0, 0x172a09c941d6, 0x7eb88a11c1d6, 0x104704203e, 0x1044042020, 0x4000020, 0x42001011156, 0x4304e0561e8, 0x172a28c95880, 0x54006220, 0x112931cc21e, 0x1011156, 0x53670f283e, 0x172b08ca5080, 0x7a80c414a03e, 0x10044200, 0x40000000000, 0x4120030800, 0x1928318801e, 0x112470c203e, 0x799283188000, 0x172f0cea50a0, 0x1eb88a91c1c8, 0x172a098941d6, 0x3ea8cc95e1f6, 0x7eb88a91c1d6}); typedef Field<uint64_t, 47, 33, StatTable47, &SQR_TABLE_47, &SQR2_TABLE_47, &SQR4_TABLE_47, &SQR8_TABLE_47, &SQR16_TABLE_47, &QRT_TABLE_47, IdTrans, &ID_TRANS, &ID_TRANS> Field47; typedef FieldTri<uint64_t, 47, 5, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5>, &SQR_TABLE_47, &SQR2_TABLE_47, &SQR4_TABLE_47, &SQR8_TABLE_47, &SQR16_TABLE_47, &QRT_TABLE_47, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri47; #endif #ifdef ENABLE_FIELD_INT_48 // 48 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6> StatTable48; constexpr StatTable48 SQR_TABLE_48({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x2d, 0xb4, 0x2d0, 0xb40, 0x2d00, 0xb400, 0x2d000, 0xb4000, 0x2d0000, 0xb40000, 0x2d00000, 0xb400000, 0x2d000000, 0xb4000000, 0x2d0000000, 0xb40000000, 0x2d00000000, 0xb400000000, 0x2d000000000, 0xb4000000000, 0x2d0000000000, 0xb40000000000, 0xd0000000005a, 0x40000000011f}); constexpr StatTable48 SQR2_TABLE_48({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x10000000000, 0x100000000000, 0x2d, 0x2d0, 0x2d00, 0x2d000, 0x2d0000, 0x2d00000, 0x2d000000, 0x2d0000000, 0x2d00000000, 0x2d000000000, 0x2d0000000000, 0xd0000000005a, 0x451, 0x4510, 0x45100, 0x451000, 0x4510000, 0x45100000, 0x451000000, 0x4510000000, 0x45100000000, 0x451000000000, 0x5100000000b4, 0x100000000bd9, 0xbdbd, 0xbdbd0, 0xbdbd00, 0xbdbd000, 0xbdbd0000, 0xbdbd00000, 0xbdbd000000, 0xbdbd0000000, 0xbdbd00000000, 0xdbd00000011f, 0xbd0000001001, 0xd0000001010f}); constexpr StatTable48 SQR4_TABLE_48({0x1, 0x10000, 0x100000000, 0x2d, 0x2d0000, 0x2d00000000, 0x451, 0x4510000, 0x45100000000, 0xbdbd, 0xbdbd0000, 0xbdbd00000000, 0x101101, 0x1011010000, 0x1101000002d0, 0x2d2fd2d, 0x2d2fd2d0000, 0xfd2d0000454a, 0x45514551, 0x455145510000, 0x4551000bd0bd, 0xbd0b6d0bd, 0xd0b6d0bd011f, 0xd0bd0100011e, 0x10001010001, 0x10100012d00, 0x12d002d2d, 0x2d002d2d002d, 0x2d2d00295100, 0x2951045551, 0x5104555104e5, 0x555104ecbdb4, 0x4ecbdbd00bd, 0xbdbd00bdadbc, 0xbdadac1101, 0xadac11011001, 0x11011013c3fc, 0x1013c3fefd2d, 0xc3fefd2fd2a7, 0xfd2fd2baac36, 0xd2baac2d450b, 0xac2d45145ac2, 0x45145ad0f851, 0x5ad0f85adb64, 0xf85adb6cbd10, 0xdb6cbd0bd0a2, 0xbd0bd0bc003c, 0xd0bc002c001f}); constexpr StatTable48 SQR8_TABLE_48({0x1, 0x2d2fd2d0000, 0x4ecbdbd00bd, 0x2c0000002c, 0x47882d9b95ec, 0xb9eec2eefc90, 0xbd900450, 0x9734009bfc8f, 0x93070a51e9b7, 0xb9d0aa02ec00, 0x8630787dd0ab, 0x6b3468ab98c9, 0x4100001bc1bd, 0x3ffeec1692fd, 0x2e0cce80414a, 0x11a77fc95626, 0x7c9856084ffe, 0x2f41c702f193, 0xd260e95bfeeb, 0x3b86220b54eb, 0x5735c802071a, 0x44626fc7ba84, 0x2b9cda923f5b, 0xc57d0a962e45, 0xd1685001450b, 0x6d78400145b6, 0x9114412978c1, 0x7d9ece1f5b0c, 0xfd2419988960, 0xd12ac3eaeaa5, 0x7d67e75f441d, 0xf86c2ba5457c, 0x40db7617aa6a, 0x80ee292186, 0xbd0f8525d34c, 0xa87ce27ca699, 0xacf3315d7a6d, 0x1a289bca977, 0x92975374e0f1, 0x3fcf113826ab, 0xff4d9be19a5e, 0x1412e5091900, 0x82c721f22d43, 0x1d773380ff32, 0xfed661cca7b1, 0x308072e06846, 0xd3eb44e91aa0, 0x819a669cbb14}); constexpr StatTable48 SQR16_TABLE_48({0x1, 0x50c24311dfa9, 0xfc08c1e39482, 0xa9ff91b620a3, 0x54954a59d16c, 0xec45c0a9fb02, 0xba7004022837, 0xc1ea19828166, 0xee9a3efecffe, 0x57ed421a20bb, 0x69d387b19141, 0x9105d02d728f, 0xd2f24d4006da, 0x39195005f508, 0xd0206ff5333c, 0x8592e734a441, 0x787b36a1c435, 0x1151e6f03f85, 0xfe0429bf95ab, 0xab2b20b47651, 0x2a65fc935212, 0x7f73ae670e2e, 0x697c17f0fc4a, 0x55dc5681f013, 0xadbd09a289bc, 0x418414f64940, 0x927c737efd40, 0x38535d08fc98, 0xe811b107691c, 0x856c3bbf4cf6, 0x47e629ad3757, 0xf9c82b4b2c09, 0x64312c99e2f, 0xd4936c978dfd, 0x782ff8716675, 0xaf853e867dd7, 0x457143c1fa6d, 0x84c4dda48e91, 0xbac9aacda41e, 0x6a6e0ffb2dc1, 0xfef377f00194, 0x3a129790acc1, 0x541e49c6f92a, 0x73e821aca96d, 0x3a6f15c03f57, 0x1bf377c66f3b, 0xbff5e192fe3b, 0x346360ee74a}); constexpr StatTable48 QRT_TABLE_48({0xc00442c284f0, 0xc16b7fda410a, 0xc16b7fda4108, 0xada3b5c79fbe, 0xc16b7fda410c, 0x16f3c18d5b0, 0xada3b5c79fb6, 0x7090a381f64, 0xc16b7fda411c, 0xcafc15d179f8, 0x16f3c18d590, 0x6630880e534e, 0xada3b5c79ff6, 0xa13dd1f49826, 0x7090a381fe4, 0xb87560f6a74, 0xc16b7fda401c, 0xaaaaffff0012, 0xcafc15d17bf8, 0xaafd15f07bf6, 0x16f3c18d190, 0x60000020000e, 0x6630880e5b4e, 0xcb977fcb401c, 0xada3b5c78ff6, 0x6663420cad0, 0xa13dd1f4b826, 0xc0045fc2f41c, 0x7090a385fe4, 0x6762e24b834, 0xb87560fea74, 0xc6351fed241c, 0xc16b7fdb401c, 0x60065622ea7a, 0xaaaafffd0012, 0xdf9562bea74, 0xcafc15d57bf8, 0x6657ea057bea, 0xaafd15f87bf6, 0xa79329ddaa66, 0x16f3c08d190, 0xa39229f0aa66, 0x60000000000e, 0x175fb4468ad0, 0x6630884e5b4e, 0, 0xcb977f4b401c, 0x2630884e5b40}); typedef Field<uint64_t, 48, 45, StatTable48, &SQR_TABLE_48, &SQR2_TABLE_48, &SQR4_TABLE_48, &SQR8_TABLE_48, &SQR16_TABLE_48, &QRT_TABLE_48, IdTrans, &ID_TRANS, &ID_TRANS> Field48; #endif } Sketch* ConstructClMul6Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_41 case 41: return new SketchImpl<Field41>(implementation, 41); #endif #ifdef ENABLE_FIELD_INT_42 case 42: return new SketchImpl<Field42>(implementation, 42); #endif #ifdef ENABLE_FIELD_INT_43 case 43: return new SketchImpl<Field43>(implementation, 43); #endif #ifdef ENABLE_FIELD_INT_44 case 44: return new SketchImpl<Field44>(implementation, 44); #endif #ifdef ENABLE_FIELD_INT_45 case 45: return new SketchImpl<Field45>(implementation, 45); #endif #ifdef ENABLE_FIELD_INT_47 case 47: return new SketchImpl<Field47>(implementation, 47); #endif #ifdef ENABLE_FIELD_INT_48 case 48: return new SketchImpl<Field48>(implementation, 48); #endif } return nullptr; } Sketch* ConstructClMulTri6Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_41 case 41: return new SketchImpl<FieldTri41>(implementation, 41); #endif #ifdef ENABLE_FIELD_INT_42 case 42: return new SketchImpl<FieldTri42>(implementation, 42); #endif #ifdef ENABLE_FIELD_INT_44 case 44: return new SketchImpl<FieldTri44>(implementation, 44); #endif #ifdef ENABLE_FIELD_INT_46 case 46: return new SketchImpl<FieldTri46>(implementation, 46); #endif #ifdef ENABLE_FIELD_INT_47 case 47: return new SketchImpl<FieldTri47>(implementation, 47); #endif } return nullptr; }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_common_impl.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_FIELDS_GENERIC_COMMON_IMPL_H_ #define _MINISKETCH_FIELDS_GENERIC_COMMON_IMPL_H_ 1 #include <stdint.h> #include "../int_utils.h" #include "../lintrans.h" namespace { /** Generic implementation for fields whose elements can be represented by an integer type. */ template<typename I, int B, uint32_t MOD, typename F, typename T, const F* SQR, const F* QRT> class Field { typedef BitsInt<I, B> O; typedef LFSR<O, MOD> L; public: typedef I Elem; constexpr int Bits() const { return B; } constexpr inline Elem Mul2(Elem val) const { return L::Call(val); } class Multiplier { T table; public: explicit Multiplier(const Field&, Elem a) { table.template Build<L::Call>(a); } constexpr inline Elem operator()(Elem a) const { return table.template Map<O>(a); } }; Elem Mul(Elem a, Elem b) const { return GFMul<I, B, L, O>(a, b); } /** Compute the square of a. */ inline constexpr Elem Sqr(Elem a) const { return SQR->template Map<O>(a); } /** Compute x such that x^2 + x = a (undefined result if no solution exists). */ inline constexpr Elem Qrt(Elem a) const { return QRT->template Map<O>(a); } /** Compute the inverse of x1. */ Elem Inv(Elem a) const { return InvExtGCD<I, O, B, MOD>(a); } /** Generate a random field element. */ Elem FromSeed(uint64_t seed) const { uint64_t k0 = 0x496e744669656c64ull; // "IntField" uint64_t k1 = seed; uint64_t count = ((uint64_t)B) << 32; Elem ret; do { ret = O::Mask(I(SipHash(k0, k1, count++))); } while(ret == 0); return ret; } Elem Deserialize(BitReader& in) const { return in.template Read<B, I>(); } void Serialize(BitWriter& out, Elem val) const { out.template Write<B, I>(val); } constexpr Elem FromUint64(uint64_t x) const { return O::Mask(I(x)); } constexpr uint64_t ToUint64(Elem val) const { return uint64_t(val); } }; } #endif
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_8bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_8) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_57 // 57 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5> StatTable57; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable57; constexpr StatTable57 SQR_TABLE_57({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x22, 0x88, 0x220, 0x880, 0x2200, 0x8800, 0x22000, 0x88000, 0x220000, 0x880000, 0x2200000, 0x8800000, 0x22000000, 0x88000000, 0x220000000, 0x880000000, 0x2200000000, 0x8800000000, 0x22000000000, 0x88000000000, 0x220000000000, 0x880000000000, 0x2200000000000, 0x8800000000000, 0x22000000000000, 0x88000000000000, 0x20000000000011, 0x80000000000044}); constexpr StatTable57 QRT_TABLE_57({0xd0c3a82c902426, 0x232aa54103915e, 0x232aa54103915c, 0x1763e291e61699c, 0x232aa541039158, 0x1f424d678bb15e, 0x1763e291e616994, 0x26fd8122f10d36, 0x232aa541039148, 0x1e0a0206002000, 0x1f424d678bb17e, 0x5d72563f39d7e, 0x1763e291e6169d4, 0x1519beb9d597df4, 0x26fd8122f10db6, 0x150c3a87c90e4aa, 0x232aa541039048, 0x15514891f6179d4, 0x1e0a0206002200, 0x14ec9ba7a94c6aa, 0x1f424d678bb57e, 0x1e0f4286382420, 0x5d72563f3957e, 0x4000080000, 0x1763e291e6179d4, 0x1ac0e804882000, 0x1519beb9d595df4, 0x1f430d6793b57e, 0x26fd8122f14db6, 0x3c68e806882000, 0x150c3a87c9064aa, 0x1484fe18b915e, 0x232aa541029048, 0x14f91eb9b595df4, 0x15514891f6379d4, 0x48f6a82380420, 0x1e0a0206042200, 0x14b1beb99595df4, 0x14ec9ba7a9cc6aa, 0x4cf2a82b00420, 0x1f424d679bb57e, 0x26aa0002000000, 0x1e0f4286182420, 0x173f1039dd17df4, 0x5d72563b3957e, 0x4aa0002000000, 0x4000880000, 0x16d31eb9b595df4, 0x1763e291f6179d4, 0x20000000000000, 0x1ac0e806882000, 0x2caa0002000000, 0x1519beb99595df4, 0, 0x1f430d6f93b57e, 0x73e90d6d93b57e, 0x26fd8132f14db6}); typedef Field<uint64_t, 57, 17, StatTable57, DynTable57, &SQR_TABLE_57, &QRT_TABLE_57> Field57; #endif #ifdef ENABLE_FIELD_INT_58 // 58 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5> StatTable58; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable58; constexpr StatTable58 SQR_TABLE_58({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x80001, 0x200004, 0x800010, 0x2000040, 0x8000100, 0x20000400, 0x80001000, 0x200004000, 0x800010000, 0x2000040000, 0x8000100000, 0x20000400000, 0x80001000000, 0x200004000000, 0x800010000000, 0x2000040000000, 0x8000100000000, 0x20000400000000, 0x80001000000000, 0x200004000000000, 0x10000100002, 0x40000400008, 0x100001000020, 0x400004000080, 0x1000010000200, 0x4000040000800, 0x10000100002000, 0x40000400008000, 0x100001000020000}); constexpr StatTable58 QRT_TABLE_58({0x2450096792a5c5c, 0x610014271011c, 0x610014271011e, 0x1f0cb811314ea88, 0x610014271011a, 0x8000000420, 0x1f0cb811314ea80, 0x265407ad8a20bcc, 0x610014271010a, 0x3d18be98392ebd0, 0x8000000400, 0xc29b930e407056, 0x1f0cb811314eac0, 0x1fcef001154dee8, 0x265407ad8a20b4c, 0xc69b924c61f94a, 0x610014271000a, 0x211006895845190, 0x3d18be98392e9d0, 0x54007accac09cc, 0x8000000000, 0xc08b934e107854, 0xc29b930e407856, 0x275407adc220bcc, 0x1f0cb811314fac0, 0x1f6db815164ea8a, 0x1fcef001154fee8, 0x1b2db801945e396, 0x265407ad8a24b4c, 0x21100ec95865590, 0xc69b924c61794a, 0x273507b1e530ad6, 0x610014270000a, 0x1b4cb835b34e29c, 0x211006895865190, 0x3839bf20d47e016, 0x3d18be98396e9d0, 0x3858bd34f36e01c, 0x54007acca409cc, 0, 0x8000100000, 0xc29a130e507856, 0xc08b934e307854, 0x13253921d448296, 0xc29b930e007856, 0x13c60935f6486bc, 0x275407adca20bcc, 0x3571be8c5e6c9da, 0x1f0cb811214fac0, 0x410014261011c, 0x1f6db815364ea8a, 0x13a50921d1486b6, 0x1fcef001554fee8, 0x64001249245a5c, 0x1b2db801145e396, 0x8610014670200a, 0x265407ac8a24b4c, 0x1a5cbfbdeb0f30c}); typedef Field<uint64_t, 58, 524289, StatTable58, DynTable58, &SQR_TABLE_58, &QRT_TABLE_58> Field58; #endif #ifdef ENABLE_FIELD_INT_59 // 59 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5> StatTable59; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable59; constexpr StatTable59 SQR_TABLE_59({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x400000000000000, 0x12a, 0x4a8, 0x12a0, 0x4a80, 0x12a00, 0x4a800, 0x12a000, 0x4a8000, 0x12a0000, 0x4a80000, 0x12a00000, 0x4a800000, 0x12a000000, 0x4a8000000, 0x12a0000000, 0x4a80000000, 0x12a00000000, 0x4a800000000, 0x12a000000000, 0x4a8000000000, 0x12a0000000000, 0x4a80000000000, 0x12a00000000000, 0x4a800000000000, 0x12a000000000000, 0x4a8000000000000, 0x2a000000000012a, 0x28000000000043d, 0x200000000001061}); constexpr StatTable59 QRT_TABLE_59({0x38d905ab028567a, 0x789fa6ed3b44d72, 0x789fa6ed3b44d70, 0x74ec857e93d828c, 0x789fa6ed3b44d74, 0x116b3c1203c96, 0x74ec857e93d8284, 0xc25ebc3871e280, 0x789fa6ed3b44d64, 0x47a37c3d910b6, 0x116b3c1203cb6, 0xc7322d7a8f48de, 0x74ec857e93d82c4, 0xb509a0ea52e496, 0xc25ebc3871e200, 0x74fdee4681d3e0c, 0x789fa6ed3b44c64, 0x7ffbbd080b2f09a, 0x47a37c3d912b6, 0xd5c937bae506c8, 0x116b3c12038b6, 0xb173c76987625e, 0xc7322d7a8f40de, 0x7591ff36b3a682c, 0x74ec857e93d92c4, 0x72b253bfbfc90c4, 0xb509a0ea52c496, 0x79f2e7b10e6d452, 0xc25ebc3871a200, 0x78c86e951086aac, 0x74fdee4681dbe0c, 0x78c96eb514c602c, 0x789fa6ed3b54c64, 0xc34818b95658e8, 0x7ffbbd080b0f09a, 0x7399f563b1980f2, 0x47a37c3dd12b6, 0xa29e0e28c58880, 0xd5c937baed06c8, 0x788ac23520ac82c, 0x116b3c13038b6, 0xa2c857e83d92b6, 0xb173c769a7625e, 0x608da990122e48, 0xc7322d7acf40de, 0xa3a89269eebefe, 0x7591ff36bba682c, 0xa25ebc2871a200, 0x74ec857e83d92c4, 0x11f62e419f1cfe, 0x72b253bf9fc90c4, 0x7425ebc2871a272, 0xb509a0ee52c496, 0x4ed8555979c8de, 0x79f2e7b18e6d452, 0x6c3580d5915d4d2, 0xc25ebc2871a200, 0, 0x78c86e971086aac}); typedef Field<uint64_t, 59, 149, StatTable59, DynTable59, &SQR_TABLE_59, &QRT_TABLE_59> Field59; #endif #ifdef ENABLE_FIELD_INT_60 // 60 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6> StatTable60; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable60; constexpr StatTable60 SQR_TABLE_60({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x400000000000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000, 0x30000000, 0xc0000000, 0x300000000, 0xc00000000, 0x3000000000, 0xc000000000, 0x30000000000, 0xc0000000000, 0x300000000000, 0xc00000000000, 0x3000000000000, 0xc000000000000, 0x30000000000000, 0xc0000000000000, 0x300000000000000, 0xc00000000000000}); constexpr StatTable60 QRT_TABLE_60({0x6983c00fe00104a, 0x804570322e054e6, 0x804570322e054e4, 0x15673387e0a4e4, 0x804570322e054e0, 0x100010110, 0x15673387e0a4ec, 0x920d01f34442a70, 0x804570322e054f0, 0x7a8dc0f2e4058f0, 0x100010130, 0x120c01f140462f0, 0x15673387e0a4ac, 0x7bdbb2ca9a4fe5c, 0x920d01f34442af0, 0xe9c6b039ce0c4ac, 0x804570322e055f0, 0xfac8b080ca20c00, 0x7a8dc0f2e405af0, 0x7a8dc4b2e4a59f0, 0x100010530, 0x10000100000, 0x120c01f14046af0, 0x131a02d91c5db6c, 0x15673387e0b4ac, 0x15623387d0b4ac, 0x7bdbb2ca9a4de5c, 0x7ffbbbca0a8ee5c, 0x920d01f34446af0, 0x800000020000000, 0xe9c6b039ce044ac, 0x81130302500f000, 0x804570322e155f0, 0x935b72eb3a48e9c, 0xfac8b080ca00c00, 0x120c016140563c0, 0x7a8dc0f2e445af0, 0x7bcbb3ca8a4ee5c, 0x7a8dc4b2e4259f0, 0xc4000a0300, 0x100110530, 0x11623285c1b19c, 0x10000300000, 0x420890090c3000, 0x120c01f14446af0, 0x68d7b33b9e0b4ac, 0x131a02d9145db6c, 0xe8ccb1e18a56fc0, 0x15673386e0b4ac, 0x7aadc8f2e485af0, 0x15623385d0b4ac, 0x4a0990093c3000, 0x7bdbb2cada4de5c, 0xf9d6b3389e0b4ac, 0x7ffbbbca8a8ee5c, 0xdf6ba38cec84ac, 0x920d01f24446af0, 0x520d01f24446af0, 0x800000000000000, 0}); typedef Field<uint64_t, 60, 3, StatTable60, DynTable60, &SQR_TABLE_60, &QRT_TABLE_60> Field60; #endif #ifdef ENABLE_FIELD_INT_61 // 61 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5> StatTable61; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable61; constexpr StatTable61 SQR_TABLE_61({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x400000000000000, 0x1000000000000000, 0x4e, 0x138, 0x4e0, 0x1380, 0x4e00, 0x13800, 0x4e000, 0x138000, 0x4e0000, 0x1380000, 0x4e00000, 0x13800000, 0x4e000000, 0x138000000, 0x4e0000000, 0x1380000000, 0x4e00000000, 0x13800000000, 0x4e000000000, 0x138000000000, 0x4e0000000000, 0x1380000000000, 0x4e00000000000, 0x13800000000000, 0x4e000000000000, 0x138000000000000, 0x4e0000000000000, 0x1380000000000000, 0xe0000000000004e, 0x180000000000011f}); constexpr StatTable61 QRT_TABLE_61({0x171d34fcdac955d0, 0x12cfc8c049e1c96, 0x12cfc8c049e1c94, 0x71d34fcdac955c2, 0x12cfc8c049e1c90, 0x631c871de564852, 0x71d34fcdac955ca, 0x129fa6407f27300, 0x12cfc8c049e1c80, 0x7094f6fdd0a3b12, 0x631c871de564872, 0xdb28cee59c8256a, 0x71d34fcdac9558a, 0xc8a0be15a915472, 0x129fa6407f27380, 0x12dfcb4058e0b80, 0x12cfc8c049e1d80, 0x117d7f04ad0118, 0x7094f6fdd0a3912, 0x621b576dbe35b6a, 0x631c871de564c72, 0x13c808a013a1ee0, 0xdb28cee59c82d6a, 0x113d79842a0272, 0x71d34fcdac9458a, 0x719776b580b6a98, 0xc8a0be15a917472, 0x6633498d6db760a, 0x129fa6407f23380, 0xbd4ae9e8c3e7560, 0x12dfcb4058e8b80, 0x8000000a, 0x12cfc8c049f1d80, 0x634ce9add3b26ea, 0x117d7f04af0118, 0xda3f19c5d66258a, 0x7094f6fdd0e3912, 0xb87427e85e71560, 0x621b576dbeb5b6a, 0xc8b0b085b8c4e0a, 0x631c871de464c72, 0x1538fc8649458a, 0x13c808a011a1ee0, 0xcddbca6d1cfe360, 0xdb28cee59882d6a, 0xae80f550d1ffff2, 0x113d7984aa0272, 0xda7770f5f195912, 0x71d34fcdbc9458a, 0x137c8a049a1ee0, 0x719776b5a0b6a98, 0xded39a9d236ba78, 0xc8a0be15e917472, 0x6732488ca7ce0a, 0x6633498dedb760a, 0xc0406d0527cb80a, 0x129fa6417f23380, 0x3d4ae9eac3e756a, 0xbd4ae9eac3e7560, 0, 0x12dfcb4458e8b80}); typedef Field<uint64_t, 61, 39, StatTable61, DynTable61, &SQR_TABLE_61, &QRT_TABLE_61> Field61; #endif #ifdef ENABLE_FIELD_INT_62 // 62 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5> StatTable62; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable62; constexpr StatTable62 SQR_TABLE_62({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x400000000000000, 0x1000000000000000, 0x20000001, 0x80000004, 0x200000010, 0x800000040, 0x2000000100, 0x8000000400, 0x20000001000, 0x80000004000, 0x200000010000, 0x800000040000, 0x2000000100000, 0x8000000400000, 0x20000001000000, 0x80000004000000, 0x200000010000000, 0x800000040000000, 0x2000000100000000, 0x440000002, 0x1100000008, 0x4400000020, 0x11000000080, 0x44000000200, 0x110000000800, 0x440000002000, 0x1100000008000, 0x4400000020000, 0x11000000080000, 0x44000000200000, 0x110000000800000, 0x440000002000000, 0x1100000008000000}); constexpr StatTable62 QRT_TABLE_62({0x30268b6fba455d2c, 0x200000006, 0x200000004, 0x3d67cb6c1fe66c76, 0x200000000, 0x3fc4f1901abfa400, 0x3d67cb6c1fe66c7e, 0x35e79b6c0a66bcbe, 0x200000010, 0x1e9372bc57a9941e, 0x3fc4f1901abfa420, 0x21ec9d424957a5b0, 0x3d67cb6c1fe66c3e, 0x1cb35a6e52f5fb0e, 0x35e79b6c0a66bc3e, 0x215481024c13a730, 0x200000110, 0x1c324a6c52f75b08, 0x1e9372bc57a9961e, 0x3764a9d00f676820, 0x3fc4f1901abfa020, 0x355481020e132730, 0x21ec9d424957adb0, 0x3c43c32c0f34301e, 0x3d67cb6c1fe67c3e, 0x1496122c45259728, 0x1cb35a6e52f5db0e, 0x15e418405b72ec20, 0x35e79b6c0a66fc3e, 0x30268b6e3a445c38, 0x215481024c132730, 0x100010114, 0x200010110, 0, 0x1c324a6c52f55b08, 0x215581044d133776, 0x1e9372bc57ad961e, 0x2155810e4d133766, 0x3764a9d00f6f6820, 0x2157833c4d12323e, 0x3fc4f1901aafa020, 0x1c324a4252f55b58, 0x355481020e332730, 0x28332fc0509d41e, 0x21ec9d424917adb0, 0x215783be4d12332e, 0x3c43c32c0fb4301e, 0x2157822c4d06363e, 0x3d67cb6c1ee67c3e, 0x23f6b9d2484afb78, 0x1496122c47259728, 0x14b8184047648a80, 0x1cb35a6e56f5db0e, 0x3fe4f1901aefa820, 0x15e418405372ec20, 0x3d5fd72c1be276be, 0x35e79b6c1a66fc3e, 0x14b038d24774cf10, 0x30268b6e1a445c38, 0x1d17022e43a7172e, 0x215481020c132730, 0x2157022e4d07372e}); typedef Field<uint64_t, 62, 536870913, StatTable62, DynTable62, &SQR_TABLE_62, &QRT_TABLE_62> Field62; #endif #ifdef ENABLE_FIELD_INT_63 // 63 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5> StatTable63; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable63; constexpr StatTable63 SQR_TABLE_63({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x400000000000000, 0x1000000000000000, 0x4000000000000000, 0x6, 0x18, 0x60, 0x180, 0x600, 0x1800, 0x6000, 0x18000, 0x60000, 0x180000, 0x600000, 0x1800000, 0x6000000, 0x18000000, 0x60000000, 0x180000000, 0x600000000, 0x1800000000, 0x6000000000, 0x18000000000, 0x60000000000, 0x180000000000, 0x600000000000, 0x1800000000000, 0x6000000000000, 0x18000000000000, 0x60000000000000, 0x180000000000000, 0x600000000000000, 0x1800000000000000, 0x6000000000000000}); constexpr StatTable63 QRT_TABLE_63({0, 0x100010114, 0x100010116, 0x1001701051372, 0x100010112, 0x1000040220, 0x100170105137a, 0x5107703453bba, 0x100010102, 0x101130117155a, 0x1000040200, 0x40000200800, 0x100170105133a, 0x103151a137276d8, 0x5107703453b3a, 0x134e65fc7c222be0, 0x100010002, 0x100030103115a, 0x101130117175a, 0x106052d103f4de2, 0x1000040600, 0x15122707691d3a, 0x40000200000, 0x4530770bc57b3a, 0x100170105033a, 0x103011a131256d8, 0x103151a137256d8, 0x176f29eb55c7a8da, 0x5107703457b3a, 0x130b158b7767d0da, 0x134e65fc7c22abe0, 0x7bcaf59d2f62d3e2, 0x100000002, 0x1001401041260, 0x100030101115a, 0x5107e03443ab8, 0x101130113175a, 0x1043701251b3a, 0x106052d10374de2, 0x134e657d7c232be2, 0x1000140600, 0x106073d103b4be2, 0x15122707491d3a, 0x4438600ac07800, 0x40000600000, 0x176a199c5682d3e0, 0x4530770b457b3a, 0x7bca759c2f62d3e0, 0x100170005033a, 0x6116d02572de2, 0x103011a111256d8, 0x1346656d7c372de2, 0x103151a177256d8, 0x643c600aa07800, 0x176f29eb5dc7a8da, 0x7b4b758b2f67d0da, 0x5107713457b3a, 0x104570776b457b3a, 0x130b158b5767d0da, 0x734e65fc3c22abe0, 0x134e65fc3c22abe0, 0x4000000000000000, 0x7bcaf59daf62d3e2}); typedef Field<uint64_t, 63, 3, StatTable63, DynTable63, &SQR_TABLE_63, &QRT_TABLE_63> Field63; #endif #ifdef ENABLE_FIELD_INT_64 // 64 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5> StatTable64; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable64; constexpr StatTable64 SQR_TABLE_64({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x100000000000000, 0x400000000000000, 0x1000000000000000, 0x4000000000000000, 0x1b, 0x6c, 0x1b0, 0x6c0, 0x1b00, 0x6c00, 0x1b000, 0x6c000, 0x1b0000, 0x6c0000, 0x1b00000, 0x6c00000, 0x1b000000, 0x6c000000, 0x1b0000000, 0x6c0000000, 0x1b00000000, 0x6c00000000, 0x1b000000000, 0x6c000000000, 0x1b0000000000, 0x6c0000000000, 0x1b00000000000, 0x6c00000000000, 0x1b000000000000, 0x6c000000000000, 0x1b0000000000000, 0x6c0000000000000, 0x1b00000000000000, 0x6c00000000000000, 0xb00000000000001b, 0xc00000000000005a}); constexpr StatTable64 QRT_TABLE_64({0x19c9369f278adc02, 0x84b2b22ab2383ee4, 0x84b2b22ab2383ee6, 0x9d7b84b495b3e3f6, 0x84b2b22ab2383ee2, 0x37c470b49213f790, 0x9d7b84b495b3e3fe, 0x1000a0105137c, 0x84b2b22ab2383ef2, 0x368e964a8edce1fc, 0x37c470b49213f7b0, 0x19c9368e278fdf4c, 0x9d7b84b495b3e3be, 0x2e4da23cbc7d4570, 0x1000a010513fc, 0x84f35772bac24232, 0x84b2b22ab2383ff2, 0x37c570ba9314e4fc, 0x368e964a8edce3fc, 0xb377c390213cdb0e, 0x37c470b49213f3b0, 0x85ed5a3aa99c24f2, 0x19c9368e278fd74c, 0xaabff0000780000e, 0x9d7b84b495b3f3be, 0x84b6b3dab03038f2, 0x2e4da23cbc7d6570, 0x511ea03494ffc, 0x1000a010553fc, 0xae0c0220343c6c0e, 0x84f35772bac2c232, 0x800000008000000e, 0x84b2b22ab2393ff2, 0xb376c29c202bc97e, 0x37c570ba9316e4fc, 0x9c3062488879e6ce, 0x368e964a8ed8e3fc, 0x41e42c08e47e70, 0xb377c3902134db0e, 0x85b9b108a60f56ce, 0x37c470b49203f3b0, 0x19dd3b6e21f3cb4c, 0x85ed5a3aa9bc24f2, 0x198ddf682c428ac0, 0x19c9368e27cfd74c, 0x4b7c68431ca84b0, 0xaabff0000700000e, 0x8040655489ffefbe, 0x9d7b84b494b3f3be, 0x18c1354e32bfa74c, 0x84b6b3dab23038f2, 0xaaf613cc0f74627e, 0x2e4da23cb87d6570, 0x3248b3d6b3342a8c, 0x511ea0b494ffc, 0xb60813c00e70700e, 0x1000a110553fc, 0x1e0d022a05393ffc, 0xae0c0220143c6c0e, 0xe0c0220143c6c00, 0x84f35772fac2c232, 0xc041e55948fbfdce, 0x800000000000000e, 0}); typedef Field<uint64_t, 64, 27, StatTable64, DynTable64, &SQR_TABLE_64, &QRT_TABLE_64> Field64; #endif } Sketch* ConstructGeneric8Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_57 case 57: return new SketchImpl<Field57>(implementation, 57); #endif #ifdef ENABLE_FIELD_INT_58 case 58: return new SketchImpl<Field58>(implementation, 58); #endif #ifdef ENABLE_FIELD_INT_59 case 59: return new SketchImpl<Field59>(implementation, 59); #endif #ifdef ENABLE_FIELD_INT_60 case 60: return new SketchImpl<Field60>(implementation, 60); #endif #ifdef ENABLE_FIELD_INT_61 case 61: return new SketchImpl<Field61>(implementation, 61); #endif #ifdef ENABLE_FIELD_INT_62 case 62: return new SketchImpl<Field62>(implementation, 62); #endif #ifdef ENABLE_FIELD_INT_63 case 63: return new SketchImpl<Field63>(implementation, 63); #endif #ifdef ENABLE_FIELD_INT_64 case 64: return new SketchImpl<Field64>(implementation, 64); #endif default: return nullptr; } }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_2bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_2) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_9 // 9 bit field typedef RecLinTrans<uint16_t, 5, 4> StatTable9; typedef RecLinTrans<uint16_t, 3, 3, 3> DynTable9; constexpr StatTable9 SQR_TABLE_9({0x1, 0x4, 0x10, 0x40, 0x100, 0x6, 0x18, 0x60, 0x180}); constexpr StatTable9 QRT_TABLE_9({0, 0x4e, 0x4c, 0x1aa, 0x48, 0x22, 0x1a2, 0x100, 0x58}); typedef Field<uint16_t, 9, 3, StatTable9, DynTable9, &SQR_TABLE_9, &QRT_TABLE_9> Field9; #endif #ifdef ENABLE_FIELD_INT_10 // 10 bit field typedef RecLinTrans<uint16_t, 5, 5> StatTable10; typedef RecLinTrans<uint16_t, 4, 3, 3> DynTable10; constexpr StatTable10 SQR_TABLE_10({0x1, 0x4, 0x10, 0x40, 0x100, 0x9, 0x24, 0x90, 0x240, 0x112}); constexpr StatTable10 QRT_TABLE_10({0xec, 0x86, 0x84, 0x30e, 0x80, 0x3c2, 0x306, 0, 0x90, 0x296}); typedef Field<uint16_t, 10, 9, StatTable10, DynTable10, &SQR_TABLE_10, &QRT_TABLE_10> Field10; #endif #ifdef ENABLE_FIELD_INT_11 // 11 bit field typedef RecLinTrans<uint16_t, 6, 5> StatTable11; typedef RecLinTrans<uint16_t, 4, 4, 3> DynTable11; constexpr StatTable11 SQR_TABLE_11({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0xa, 0x28, 0xa0, 0x280, 0x205}); constexpr StatTable11 QRT_TABLE_11({0x734, 0x48, 0x4a, 0x1de, 0x4e, 0x35e, 0x1d6, 0x200, 0x5e, 0, 0x37e}); typedef Field<uint16_t, 11, 5, StatTable11, DynTable11, &SQR_TABLE_11, &QRT_TABLE_11> Field11; #endif #ifdef ENABLE_FIELD_INT_12 // 12 bit field typedef RecLinTrans<uint16_t, 6, 6> StatTable12; typedef RecLinTrans<uint16_t, 4, 4, 4> DynTable12; constexpr StatTable12 SQR_TABLE_12({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x9, 0x24, 0x90, 0x240, 0x900, 0x412}); constexpr StatTable12 QRT_TABLE_12({0x48, 0xc10, 0xc12, 0x208, 0xc16, 0xd82, 0x200, 0x110, 0xc06, 0, 0xda2, 0x5a4}); typedef Field<uint16_t, 12, 9, StatTable12, DynTable12, &SQR_TABLE_12, &QRT_TABLE_12> Field12; #endif #ifdef ENABLE_FIELD_INT_13 // 13 bit field typedef RecLinTrans<uint16_t, 5, 4, 4> StatTable13; typedef RecLinTrans<uint16_t, 4, 3, 3, 3> DynTable13; constexpr StatTable13 SQR_TABLE_13({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x36, 0xd8, 0x360, 0xd80, 0x161b, 0x185a}); constexpr StatTable13 QRT_TABLE_13({0xcfc, 0x1500, 0x1502, 0x382, 0x1506, 0x149c, 0x38a, 0x118, 0x1516, 0, 0x14bc, 0x100e, 0x3ca}); typedef Field<uint16_t, 13, 27, StatTable13, DynTable13, &SQR_TABLE_13, &QRT_TABLE_13> Field13; #endif #ifdef ENABLE_FIELD_INT_14 // 14 bit field typedef RecLinTrans<uint16_t, 5, 5, 4> StatTable14; typedef RecLinTrans<uint16_t, 4, 4, 3, 3> DynTable14; constexpr StatTable14 SQR_TABLE_14({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x21, 0x84, 0x210, 0x840, 0x2100, 0x442, 0x1108}); constexpr StatTable14 QRT_TABLE_14({0x13f2, 0x206, 0x204, 0x3e06, 0x200, 0x1266, 0x3e0e, 0x114, 0x210, 0, 0x1246, 0x2848, 0x3e4e, 0x2258}); typedef Field<uint16_t, 14, 33, StatTable14, DynTable14, &SQR_TABLE_14, &QRT_TABLE_14> Field14; #endif #ifdef ENABLE_FIELD_INT_15 // 15 bit field typedef RecLinTrans<uint16_t, 5, 5, 5> StatTable15; typedef RecLinTrans<uint16_t, 4, 4, 4, 3> DynTable15; constexpr StatTable15 SQR_TABLE_15({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x6, 0x18, 0x60, 0x180, 0x600, 0x1800, 0x6000}); constexpr StatTable15 QRT_TABLE_15({0, 0x114, 0x116, 0x428, 0x112, 0x137a, 0x420, 0x6d62, 0x102, 0x73a, 0x135a, 0x6460, 0x460, 0x4000, 0x6de2}); typedef Field<uint16_t, 15, 3, StatTable15, DynTable15, &SQR_TABLE_15, &QRT_TABLE_15> Field15; #endif #ifdef ENABLE_FIELD_INT_16 // 16 bit field typedef RecLinTrans<uint16_t, 6, 5, 5> StatTable16; typedef RecLinTrans<uint16_t, 4, 4, 4, 4> DynTable16; constexpr StatTable16 SQR_TABLE_16({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x2b, 0xac, 0x2b0, 0xac0, 0x2b00, 0xac00, 0xb056, 0xc10e}); constexpr StatTable16 QRT_TABLE_16({0x732, 0x72b8, 0x72ba, 0x7e96, 0x72be, 0x78b2, 0x7e9e, 0x8cba, 0x72ae, 0xfa24, 0x7892, 0x5892, 0x7ede, 0xbec6, 0x8c3a, 0}); typedef Field<uint16_t, 16, 43, StatTable16, DynTable16, &SQR_TABLE_16, &QRT_TABLE_16> Field16; #endif } Sketch* ConstructGeneric2Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_9 case 9: return new SketchImpl<Field9>(implementation, 9); #endif #ifdef ENABLE_FIELD_INT_10 case 10: return new SketchImpl<Field10>(implementation, 10); #endif #ifdef ENABLE_FIELD_INT_11 case 11: return new SketchImpl<Field11>(implementation, 11); #endif #ifdef ENABLE_FIELD_INT_12 case 12: return new SketchImpl<Field12>(implementation, 12); #endif #ifdef ENABLE_FIELD_INT_13 case 13: return new SketchImpl<Field13>(implementation, 13); #endif #ifdef ENABLE_FIELD_INT_14 case 14: return new SketchImpl<Field14>(implementation, 14); #endif #ifdef ENABLE_FIELD_INT_15 case 15: return new SketchImpl<Field15>(implementation, 15); #endif #ifdef ENABLE_FIELD_INT_16 case 16: return new SketchImpl<Field16>(implementation, 16); #endif default: return nullptr; } }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_3bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_3) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_17 // 17 bit field typedef RecLinTrans<uint32_t, 6, 6, 5> StatTable17; typedef RecLinTrans<uint32_t, 4, 4, 3, 3, 3> DynTable17; constexpr StatTable17 SQR_TABLE_17({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x8012}); constexpr StatTable17 QRT_TABLE_17({0, 0x4c3e, 0x4c3c, 0x1a248, 0x4c38, 0x428, 0x1a240, 0x1b608, 0x4c28, 0x206, 0x408, 0x4000, 0x1a200, 0x18006, 0x1b688, 0x14d2e, 0x4d28}); typedef Field<uint32_t, 17, 9, StatTable17, DynTable17, &SQR_TABLE_17, &QRT_TABLE_17> Field17; #endif #ifdef ENABLE_FIELD_INT_18 // 18 bit field typedef RecLinTrans<uint32_t, 6, 6, 6> StatTable18; typedef RecLinTrans<uint32_t, 4, 4, 4, 3, 3> DynTable18; constexpr StatTable18 SQR_TABLE_18({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x9, 0x24, 0x90, 0x240, 0x900, 0x2400, 0x9000, 0x24000, 0x10012}); constexpr StatTable18 QRT_TABLE_18({0x9208, 0x422, 0x420, 0x8048, 0x424, 0x68b0, 0x8040, 0x30086, 0x434, 0x1040, 0x6890, 0x30ca2, 0x8000, 0x32896, 0x30006, 0, 0x534, 0x20532}); typedef Field<uint32_t, 18, 9, StatTable18, DynTable18, &SQR_TABLE_18, &QRT_TABLE_18> Field18; #endif #ifdef ENABLE_FIELD_INT_19 // 19 bit field typedef RecLinTrans<uint32_t, 5, 5, 5, 4> StatTable19; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 3> DynTable19; constexpr StatTable19 SQR_TABLE_19({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x4e, 0x138, 0x4e0, 0x1380, 0x4e00, 0x13800, 0x4e000, 0x3804e, 0x6011f}); constexpr StatTable19 QRT_TABLE_19({0x5d6b0, 0x2f476, 0x2f474, 0x1d6a2, 0x2f470, 0x42a, 0x1d6aa, 0x1060, 0x2f460, 0x19e92, 0x40a, 0x1da98, 0x1d6ea, 0x28c78, 0x10e0, 0xf56a, 0x2f560, 0, 0x19c92}); typedef Field<uint32_t, 19, 39, StatTable19, DynTable19, &SQR_TABLE_19, &QRT_TABLE_19> Field19; #endif #ifdef ENABLE_FIELD_INT_20 // 20 bit field typedef RecLinTrans<uint32_t, 5, 5, 5, 5> StatTable20; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4> DynTable20; constexpr StatTable20 SQR_TABLE_20({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x9, 0x24, 0x90, 0x240, 0x900, 0x2400, 0x9000, 0x24000, 0x90000, 0x40012}); constexpr StatTable20 QRT_TABLE_20({0xc5dea, 0xc0110, 0xc0112, 0xe11de, 0xc0116, 0x24814, 0xe11d6, 0x20080, 0xc0106, 0xfe872, 0x24834, 0xe4106, 0xe1196, 0x1d9a4, 0x20000, 0x31190, 0xc0006, 0, 0xfea72, 0x7ea74}); typedef Field<uint32_t, 20, 9, StatTable20, DynTable20, &SQR_TABLE_20, &QRT_TABLE_20> Field20; #endif #ifdef ENABLE_FIELD_INT_21 // 21 bit field typedef RecLinTrans<uint32_t, 6, 5, 5, 5> StatTable21; typedef RecLinTrans<uint32_t, 4, 4, 4, 3, 3, 3> DynTable21; constexpr StatTable21 SQR_TABLE_21({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0xa, 0x28, 0xa0, 0x280, 0xa00, 0x2800, 0xa000, 0x28000, 0xa0000, 0x80005}); constexpr StatTable21 QRT_TABLE_21({0x1bd5fc, 0xbc196, 0xbc194, 0x74b96, 0xbc190, 0x1048, 0x74b9e, 0x672c8, 0xbc180, 0x4080, 0x1068, 0xc8200, 0x74bde, 0x64280, 0x67248, 0xc4280, 0xbc080, 0x80000, 0x4280, 0, 0x1468}); typedef Field<uint32_t, 21, 5, StatTable21, DynTable21, &SQR_TABLE_21, &QRT_TABLE_21> Field21; #endif #ifdef ENABLE_FIELD_INT_22 // 22 bit field typedef RecLinTrans<uint32_t, 6, 6, 5, 5> StatTable22; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 3, 3> DynTable22; constexpr StatTable22 SQR_TABLE_22({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000}); constexpr StatTable22 QRT_TABLE_22({0x210d16, 0x104a, 0x1048, 0x4088, 0x104c, 0x200420, 0x4080, 0x492dc, 0x105c, 0x1a67f0, 0x200400, 0x21155c, 0x40c0, 0x20346c, 0x4925c, 0x1af7ac, 0x115c, 0x2274ac, 0x1a65f0, 0x2a65f0, 0x200000, 0}); typedef Field<uint32_t, 22, 3, StatTable22, DynTable22, &SQR_TABLE_22, &QRT_TABLE_22> Field22; #endif #ifdef ENABLE_FIELD_INT_23 // 23 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 5> StatTable23; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 3> DynTable23; constexpr StatTable23 SQR_TABLE_23({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x42, 0x108, 0x420, 0x1080, 0x4200, 0x10800, 0x42000, 0x108000, 0x420000, 0x80042, 0x200108}); constexpr StatTable23 QRT_TABLE_23({0, 0x1040, 0x1042, 0x43056, 0x1046, 0x121d76, 0x4305e, 0x40a0, 0x1056, 0x15176, 0x121d56, 0x7ee1f6, 0x4301e, 0x40000, 0x4020, 0x4f0be, 0x1156, 0x7cf0a0, 0x15376, 0x1ee9e8, 0x121956, 0x3ac9f6, 0x7ee9f6}); typedef Field<uint32_t, 23, 33, StatTable23, DynTable23, &SQR_TABLE_23, &QRT_TABLE_23> Field23; #endif #ifdef ENABLE_FIELD_INT_24 // 24 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 6> StatTable24; typedef RecLinTrans<uint32_t, 4, 4, 4, 4, 4, 4> DynTable24; constexpr StatTable24 SQR_TABLE_24({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1b, 0x6c, 0x1b0, 0x6c0, 0x1b00, 0x6c00, 0x1b000, 0x6c000, 0x1b0000, 0x6c0000, 0xb0001b, 0xc0005a}); constexpr StatTable24 QRT_TABLE_24({0x104e, 0xaf42a8, 0xaf42aa, 0xb78186, 0xaf42ae, 0x4090, 0xb7818e, 0x4a37c, 0xaf42be, 0x3688c0, 0x40b0, 0x80080e, 0xb781ce, 0xaf2232, 0x4a3fc, 0x856a82, 0xaf43be, 0x29c970, 0x368ac0, 0x968ace, 0x44b0, 0x77d570, 0x80000e, 0}); typedef Field<uint32_t, 24, 27, StatTable24, DynTable24, &SQR_TABLE_24, &QRT_TABLE_24> Field24; #endif } Sketch* ConstructGeneric3Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_17 case 17: return new SketchImpl<Field17>(implementation, 17); #endif #ifdef ENABLE_FIELD_INT_18 case 18: return new SketchImpl<Field18>(implementation, 18); #endif #ifdef ENABLE_FIELD_INT_19 case 19: return new SketchImpl<Field19>(implementation, 19); #endif #ifdef ENABLE_FIELD_INT_20 case 20: return new SketchImpl<Field20>(implementation, 20); #endif #ifdef ENABLE_FIELD_INT_21 case 21: return new SketchImpl<Field21>(implementation, 21); #endif #ifdef ENABLE_FIELD_INT_22 case 22: return new SketchImpl<Field22>(implementation, 22); #endif #ifdef ENABLE_FIELD_INT_23 case 23: return new SketchImpl<Field23>(implementation, 23); #endif #ifdef ENABLE_FIELD_INT_24 case 24: return new SketchImpl<Field24>(implementation, 24); #endif default: return nullptr; } }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/clmul_common_impl.h
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #ifndef _MINISKETCH_FIELDS_CLMUL_COMMON_IMPL_H_ #define _MINISKETCH_FIELDS_CLMUL_COMMON_IMPL_H_ 1 #include <stdint.h> #include <immintrin.h> #include "../int_utils.h" #include "../lintrans.h" namespace { // The memory sanitizer in clang < 11 cannot reason through _mm_clmulepi64_si128 calls. // Disable memory sanitization in the functions using them for those compilers. #if defined(__clang__) && (__clang_major__ < 11) # if defined(__has_feature) # if __has_feature(memory_sanitizer) # define NO_SANITIZE_MEMORY __attribute__((no_sanitize("memory"))) # endif # endif #endif #ifndef NO_SANITIZE_MEMORY # define NO_SANITIZE_MEMORY #endif template<typename I, int BITS, I MOD> NO_SANITIZE_MEMORY I MulWithClMulReduce(I a, I b) { static constexpr I MASK = Mask<BITS, I>(); const __m128i MOD128 = _mm_cvtsi64_si128(MOD); __m128i product = _mm_clmulepi64_si128(_mm_cvtsi64_si128((uint64_t)a), _mm_cvtsi64_si128((uint64_t)b), 0x00); if (BITS <= 32) { __m128i high1 = _mm_srli_epi64(product, BITS); __m128i red1 = _mm_clmulepi64_si128(high1, MOD128, 0x00); __m128i high2 = _mm_srli_epi64(red1, BITS); __m128i red2 = _mm_clmulepi64_si128(high2, MOD128, 0x00); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } else if (BITS == 64) { __m128i red1 = _mm_clmulepi64_si128(product, MOD128, 0x01); __m128i red2 = _mm_clmulepi64_si128(red1, MOD128, 0x01); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)); } else if ((BITS % 8) == 0) { __m128i high1 = _mm_srli_si128(product, BITS / 8); __m128i red1 = _mm_clmulepi64_si128(high1, MOD128, 0x00); __m128i high2 = _mm_srli_si128(red1, BITS / 8); __m128i red2 = _mm_clmulepi64_si128(high2, MOD128, 0x00); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } else { __m128i high1 = _mm_or_si128(_mm_srli_epi64(product, BITS), _mm_srli_si128(_mm_slli_epi64(product, 64 - BITS), 8)); __m128i red1 = _mm_clmulepi64_si128(high1, MOD128, 0x00); if ((uint64_t(MOD) >> (66 - BITS)) == 0) { __m128i high2 = _mm_srli_epi64(red1, BITS); __m128i red2 = _mm_clmulepi64_si128(high2, MOD128, 0x00); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } else { __m128i high2 = _mm_or_si128(_mm_srli_epi64(red1, BITS), _mm_srli_si128(_mm_slli_epi64(red1, 64 - BITS), 8)); __m128i red2 = _mm_clmulepi64_si128(high2, MOD128, 0x00); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } } } template<typename I, int BITS, int POS> NO_SANITIZE_MEMORY I MulTrinomial(I a, I b) { static constexpr I MASK = Mask<BITS, I>(); __m128i product = _mm_clmulepi64_si128(_mm_cvtsi64_si128((uint64_t)a), _mm_cvtsi64_si128((uint64_t)b), 0x00); if (BITS <= 32) { __m128i high1 = _mm_srli_epi64(product, BITS); __m128i red1 = _mm_xor_si128(high1, _mm_slli_epi64(high1, POS)); if (POS == 1) { return _mm_cvtsi128_si64(_mm_xor_si128(product, red1)) & MASK; } else { __m128i high2 = _mm_srli_epi64(red1, BITS); __m128i red2 = _mm_xor_si128(high2, _mm_slli_epi64(high2, POS)); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } } else { __m128i high1 = _mm_or_si128(_mm_srli_epi64(product, BITS), _mm_srli_si128(_mm_slli_epi64(product, 64 - BITS), 8)); if (BITS + POS <= 66) { __m128i red1 = _mm_xor_si128(high1, _mm_slli_epi64(high1, POS)); if (POS == 1) { return _mm_cvtsi128_si64(_mm_xor_si128(product, red1)) & MASK; } else if (BITS + POS <= 66) { __m128i high2 = _mm_srli_epi64(red1, BITS); __m128i red2 = _mm_xor_si128(high2, _mm_slli_epi64(high2, POS)); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } } else { const __m128i MOD128 = _mm_cvtsi64_si128(1 + (((uint64_t)1) << POS)); __m128i red1 = _mm_clmulepi64_si128(high1, MOD128, 0x00); __m128i high2 = _mm_or_si128(_mm_srli_epi64(red1, BITS), _mm_srli_si128(_mm_slli_epi64(red1, 64 - BITS), 8)); __m128i red2 = _mm_xor_si128(high2, _mm_slli_epi64(high2, POS)); return _mm_cvtsi128_si64(_mm_xor_si128(_mm_xor_si128(product, red1), red2)) & MASK; } } } /** Implementation of fields that use the SSE clmul intrinsic for multiplication. */ template<typename I, int B, I MOD, I (*MUL)(I, I), typename F, const F* SQR, const F* SQR2, const F* SQR4, const F* SQR8, const F* SQR16, const F* QRT, typename T, const T* LOAD, const T* SAVE> struct GenField { typedef BitsInt<I, B> O; typedef LFSR<O, MOD> L; static inline constexpr I Sqr1(I a) { return SQR->template Map<O>(a); } static inline constexpr I Sqr2(I a) { return SQR2->template Map<O>(a); } static inline constexpr I Sqr4(I a) { return SQR4->template Map<O>(a); } static inline constexpr I Sqr8(I a) { return SQR8->template Map<O>(a); } static inline constexpr I Sqr16(I a) { return SQR16->template Map<O>(a); } public: typedef I Elem; inline constexpr int Bits() const { return B; } inline constexpr Elem Mul2(Elem val) const { return L::Call(val); } inline Elem Mul(Elem a, Elem b) const { return MUL(a, b); } class Multiplier { Elem m_val; public: inline constexpr explicit Multiplier(const GenField&, Elem a) : m_val(a) {} constexpr Elem operator()(Elem a) const { return MUL(m_val, a); } }; /** Compute the square of a. */ inline constexpr Elem Sqr(Elem val) const { return SQR->template Map<O>(val); } /** Compute x such that x^2 + x = a (undefined result if no solution exists). */ inline constexpr Elem Qrt(Elem val) const { return QRT->template Map<O>(val); } /** Compute the inverse of x1. */ inline Elem Inv(Elem val) const { return InvLadder<I, O, B, MUL, Sqr1, Sqr2, Sqr4, Sqr8, Sqr16>(val); } /** Generate a random field element. */ Elem FromSeed(uint64_t seed) const { uint64_t k0 = 0x434c4d554c466c64ull; // "CLMULFld" uint64_t k1 = seed; uint64_t count = ((uint64_t)B) << 32; I ret; do { ret = O::Mask(I(SipHash(k0, k1, count++))); } while(ret == 0); return LOAD->template Map<O>(ret); } Elem Deserialize(BitReader& in) const { return LOAD->template Map<O>(in.Read<B, I>()); } void Serialize(BitWriter& out, Elem val) const { out.Write<B, I>(SAVE->template Map<O>(val)); } constexpr Elem FromUint64(uint64_t x) const { return LOAD->template Map<O>(O::Mask(I(x))); } constexpr uint64_t ToUint64(Elem val) const { return uint64_t(SAVE->template Map<O>(val)); } }; template<typename I, int B, I MOD, typename F, const F* SQR, const F* SQR2, const F* SQR4, const F* SQR8, const F* SQR16, const F* QRT, typename T, const T* LOAD, const T* SAVE> using Field = GenField<I, B, MOD, MulWithClMulReduce<I, B, MOD>, F, SQR, SQR2, SQR4, SQR8, SQR16, QRT, T, LOAD, SAVE>; template<typename I, int B, int POS, typename F, const F* SQR, const F* SQR2, const F* SQR4, const F* SQR8, const F* SQR16, const F* QRT, typename T, const T* LOAD, const T* SAVE> using FieldTri = GenField<I, B, I(1) + (I(1) << POS), MulTrinomial<I, B, POS>, F, SQR, SQR2, SQR4, SQR8, SQR16, QRT, T, LOAD, SAVE>; } #endif
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/clmul_4bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_4) #include "clmul_common_impl.h" #include "../int_utils.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_25 // 25 bit field typedef RecLinTrans<uint32_t, 5, 5, 5, 5, 5> StatTable25; constexpr StatTable25 SQR_TABLE_25({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x48000, 0x120000, 0x480000, 0x1200000, 0x800012}); constexpr StatTable25 SQR2_TABLE_25({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x48, 0x480, 0x4800, 0x48000, 0x480000, 0x800012, 0x104, 0x1040, 0x10400, 0x104000, 0x1040000, 0x400048, 0x492, 0x4920, 0x49200, 0x492000, 0x920012, 0x1200104}); constexpr StatTable25 SQR4_TABLE_25({0x1, 0x10000, 0x480, 0x800012, 0x104000, 0x4920, 0x1200104, 0x1001000, 0x48048, 0x481040, 0x410448, 0x492492, 0x930002, 0x580, 0x1800012, 0x14c000, 0x5960, 0x160014c, 0x1493000, 0x58058, 0x5814c0, 0xc14c5a, 0x596596, 0x1974922, 0x1249684}); constexpr StatTable25 SQR8_TABLE_25({0x1, 0x5960, 0x1411448, 0x1860922, 0x1d814d2, 0x1cdede8, 0x1e15e16, 0x1b79686, 0xfdf116, 0x1efe4c8, 0x1b839a8, 0x10ced66, 0xae05ce, 0x1459400, 0xa29fa6, 0x85e4d2, 0x7eecee, 0x183a96, 0x1eb2fa8, 0xede876, 0xf6e440, 0x1f7140a, 0xd07d7c, 0x10e4ea2, 0x1222a54}); constexpr StatTable25 QRT_TABLE_25({0, 0x482110, 0x482112, 0x1b3c3e6, 0x482116, 0x4960ae, 0x1b3c3ee, 0x4088, 0x482106, 0x58a726, 0x49608e, 0x5ce52e, 0x1b3c3ae, 0x2006, 0x4008, 0x1c1a8, 0x482006, 0x1e96488, 0x58a526, 0x400000, 0x49648e, 0x1800006, 0x5ced2e, 0xb3d3a8, 0x1b3d3ae}); typedef Field<uint32_t, 25, 9, StatTable25, &SQR_TABLE_25, &SQR2_TABLE_25, &SQR4_TABLE_25, &SQR8_TABLE_25, &QRT_TABLE_25, &QRT_TABLE_25, IdTrans, &ID_TRANS, &ID_TRANS> Field25; typedef FieldTri<uint32_t, 25, 3, RecLinTrans<uint32_t, 5, 5, 5, 5, 5>, &SQR_TABLE_25, &SQR2_TABLE_25, &SQR4_TABLE_25, &SQR8_TABLE_25, &QRT_TABLE_25, &QRT_TABLE_25, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri25; #endif #ifdef ENABLE_FIELD_INT_26 // 26 bit field typedef RecLinTrans<uint32_t, 6, 5, 5, 5, 5> StatTable26; constexpr StatTable26 SQR_TABLE_26({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x1b, 0x6c, 0x1b0, 0x6c0, 0x1b00, 0x6c00, 0x1b000, 0x6c000, 0x1b0000, 0x6c0000, 0x1b00000, 0x2c0001b, 0x300005a}); constexpr StatTable26 SQR2_TABLE_26({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x6c, 0x6c0, 0x6c00, 0x6c000, 0x6c0000, 0x2c0001b, 0x145, 0x1450, 0x14500, 0x145000, 0x1450000, 0x500077, 0x100076b, 0x76dc, 0x76dc0, 0x76dc00, 0x36dc01b, 0x2dc011f, 0x1c01105}); constexpr StatTable26 SQR4_TABLE_26({0x1, 0x10000, 0x6c0, 0x2c0001b, 0x145000, 0x76dc, 0x2dc011f, 0x1101100, 0x106ac6c, 0x6ad515, 0x1145127, 0x121b6dc, 0x2da1d0f, 0x10007c1, 0x3c7c01b, 0x128290, 0x29062e0, 0x2ee8d68, 0x167abcd, 0x3cabbce, 0x3c7a862, 0x6b83ce, 0x3cf5620, 0x229b787, 0x38a6b0f, 0x3071ade}); constexpr StatTable26 SQR8_TABLE_26({0x1, 0x29062e0, 0x2b2942d, 0x34ab63, 0x3bddebb, 0x7b1823, 0x58b9ae, 0x391720e, 0x1385e18, 0x3891746, 0x13069c5, 0x2dfd089, 0x12a35ff, 0x3e534f, 0x172c6a2, 0x55338f, 0x3887137, 0x3f45b03, 0x164a695, 0x2c7e7ef, 0x29c907d, 0x636c85, 0x3db4007, 0x97e7ff, 0x3cbfe55, 0x31c0d96}); constexpr StatTable26 QRT_TABLE_26({0x217b530, 0x2ae82a8, 0x2ae82aa, 0x2001046, 0x2ae82ae, 0x2de032e, 0x200104e, 0x70c10c, 0x2ae82be, 0x20151f2, 0x2de030e, 0xbc1400, 0x200100e, 0x178570, 0x70c18c, 0x2ae4232, 0x2ae83be, 0x211d742, 0x20153f2, 0x21f54f2, 0x2de070e, 0x5e0700, 0xbc1c00, 0x3abb97e, 0x200000e, 0}); typedef Field<uint32_t, 26, 27, StatTable26, &SQR_TABLE_26, &SQR2_TABLE_26, &SQR4_TABLE_26, &SQR8_TABLE_26, &QRT_TABLE_26, &QRT_TABLE_26, IdTrans, &ID_TRANS, &ID_TRANS> Field26; #endif #ifdef ENABLE_FIELD_INT_27 // 27 bit field typedef RecLinTrans<uint32_t, 6, 6, 5, 5, 5> StatTable27; constexpr StatTable27 SQR_TABLE_27({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x4e, 0x138, 0x4e0, 0x1380, 0x4e00, 0x13800, 0x4e000, 0x138000, 0x4e0000, 0x1380000, 0x4e00000, 0x380004e, 0x600011f}); constexpr StatTable27 SQR2_TABLE_27({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x4e, 0x4e0, 0x4e00, 0x4e000, 0x4e0000, 0x4e00000, 0x600011f, 0x1054, 0x10540, 0x105400, 0x1054000, 0x54004e, 0x54004e0, 0x4004f76, 0x4f658, 0x4f6580, 0x4f65800, 0x765811f, 0x658101a, 0x5810004}); constexpr StatTable27 SQR4_TABLE_27({0x1, 0x10000, 0x4e0, 0x4e00000, 0x105400, 0x4004f76, 0x765811f, 0x1001110, 0x114e04e, 0x4abe54, 0x6551445, 0x45e212e, 0x13ccbdc, 0x3d805ef, 0x5e10100, 0x114b0e0, 0xe4bf22, 0x721c505, 0x51b3ba8, 0x3bf04d5, 0x4dabba0, 0x3b0aa45, 0x24a80cb, 0xc3d4b0, 0x4b34626, 0x6372e18, 0x6028c1b}); constexpr StatTable27 SQR8_TABLE_27({0x1, 0xe4bf22, 0x430cb3c, 0x73b7225, 0x6526539, 0x3c278e3, 0x4724a6e, 0x48b39b4, 0x1dbf7de, 0x106508, 0x3564785, 0x33ae33f, 0x61d6685, 0x6adaca3, 0x2786b6f, 0x4e76784, 0x869f42, 0x466b048, 0x415e00e, 0x46c3c9a, 0x73ffd91, 0x49002e0, 0x3734fed, 0x3c04a43, 0x191d3ee, 0xe828b9, 0xfab68c}); constexpr StatTable27 QRT_TABLE_27({0x6bf0530, 0x2be4496, 0x2be4494, 0x2bf0522, 0x2be4490, 0x1896cca, 0x2bf052a, 0x408a, 0x2be4480, 0x368ae72, 0x1896cea, 0x18d2ee0, 0x2bf056a, 0x1c76d6a, 0x400a, 0x336e9f8, 0x2be4580, 0x36baf12, 0x368ac72, 0x430360, 0x18968ea, 0x34a6b80, 0x18d26e0, 0xbf1560, 0x2bf156a, 0, 0x1c74d6a}); typedef Field<uint32_t, 27, 39, StatTable27, &SQR_TABLE_27, &SQR2_TABLE_27, &SQR4_TABLE_27, &SQR8_TABLE_27, &QRT_TABLE_27, &QRT_TABLE_27, IdTrans, &ID_TRANS, &ID_TRANS> Field27; #endif #ifdef ENABLE_FIELD_INT_28 // 28 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 5, 5> StatTableTRI28; constexpr StatTableTRI28 SQR_TABLE_TRI28({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000}); constexpr StatTableTRI28 SQR2_TABLE_TRI28({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x3, 0x30, 0x300, 0x3000, 0x30000, 0x300000, 0x3000000, 0x5, 0x50, 0x500, 0x5000, 0x50000, 0x500000, 0x5000000, 0xf, 0xf0, 0xf00, 0xf000, 0xf0000, 0xf00000, 0xf000000}); constexpr StatTableTRI28 SQR4_TABLE_TRI28({0x1, 0x10000, 0x30, 0x300000, 0x500, 0x5000000, 0xf000, 0x11, 0x110000, 0x330, 0x3300000, 0x5500, 0x500000f, 0xff000, 0x101, 0x1010000, 0x3030, 0x300005, 0x50500, 0x50000f0, 0xf0f000, 0x1111, 0x1110003, 0x33330, 0x3300055, 0x555500, 0x5000fff, 0xffff000}); constexpr StatTableTRI28 SQR8_TABLE_TRI28({0x1, 0x3030, 0x5000500, 0xf0e111, 0x3210000, 0x6300faa, 0x40ef10e, 0x501, 0xf0c030, 0x5110630, 0x395b444, 0x621010e, 0x6010f9b, 0x13bc4cb, 0x110001, 0x3303065, 0xff50f, 0xf0e120, 0x3243530, 0x330fabb, 0x5ec232c, 0x511050e, 0x3c1c064, 0x2ec60a, 0x3954175, 0x7c5c43d, 0x20acba, 0x943bc43}); constexpr StatTableTRI28 QRT_TABLE_TRI28({0x121d57a, 0x40216, 0x40214, 0x8112578, 0x40210, 0x10110, 0x8112570, 0x12597ec, 0x40200, 0x6983e00, 0x10130, 0x972b99c, 0x8112530, 0x8002000, 0x125976c, 0x815a76c, 0x40300, 0x936b29c, 0x6983c00, 0x97bb8ac, 0x10530, 0x9103000, 0x972b19c, 0xf6384ac, 0x8113530, 0x4113530, 0x8000000, 0}); typedef FieldTri<uint32_t, 28, 1, StatTableTRI28, &SQR_TABLE_TRI28, &SQR2_TABLE_TRI28, &SQR4_TABLE_TRI28, &SQR8_TABLE_TRI28, &QRT_TABLE_TRI28, &QRT_TABLE_TRI28, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri28; #endif #ifdef ENABLE_FIELD_INT_29 // 29 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 6, 5> StatTable29; constexpr StatTable29 SQR_TABLE_29({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0xa, 0x28, 0xa0, 0x280, 0xa00, 0x2800, 0xa000, 0x28000, 0xa0000, 0x280000, 0xa00000, 0x2800000, 0xa000000, 0x8000005}); constexpr StatTable29 SQR2_TABLE_29({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x28, 0x280, 0x2800, 0x28000, 0x280000, 0x2800000, 0x8000005, 0x44, 0x440, 0x4400, 0x44000, 0x440000, 0x4400000, 0x400000a, 0xaa, 0xaa0, 0xaa00, 0xaa000, 0xaa0000, 0xaa00000, 0xa000011}); constexpr StatTable29 SQR4_TABLE_29({0x1, 0x10000, 0x28, 0x280000, 0x440, 0x4400000, 0xaa00, 0xa000011, 0x101000, 0x10000280, 0x2828000, 0x4444, 0x444000a, 0xaaaa0, 0xaa00101, 0x1000100, 0x1002800, 0x8002805, 0x8044005, 0x440aa, 0xaa00aa, 0xaa1010, 0x10101010, 0x10128280, 0x28282c4, 0x2c44444, 0x4444eaa, 0xeaaaaaa, 0xaaba001}); constexpr StatTable29 SQR8_TABLE_29({0x1, 0x1002800, 0x4680000, 0xae50ba, 0x2822a00, 0x14545eba, 0x110aed64, 0xc6eeaaf, 0x4ee00a0, 0x10aba290, 0x1bd6efc1, 0x8222b29, 0x1c791ebf, 0x174e85da, 0x1cc66c7f, 0x29292c4, 0x2886c20, 0xea04467, 0xc0eeb87, 0xccd4115, 0x16d5fa2e, 0x1cf8fe75, 0xe45a4e1, 0x19018b3f, 0x1d64778, 0x2e0bdf8, 0xa1bd96b, 0xff5b70e, 0x14d89770}); constexpr StatTable29 QRT_TABLE_29({0x1b8351dc, 0xb87135e, 0xb87135c, 0xda7b35e, 0xb871358, 0x621a116, 0xda7b356, 0x40200, 0xb871348, 0xc9e2620, 0x621a136, 0x478b16, 0xda7b316, 0x6762e20, 0x40280, 0x6202000, 0xb871248, 0x627a316, 0xc9e2420, 0xcd1ad36, 0x621a536, 0x760e20, 0x478316, 0xa760e20, 0xda7a316, 0x8000000, 0x6760e20, 0, 0x44280}); typedef Field<uint32_t, 29, 5, StatTable29, &SQR_TABLE_29, &SQR2_TABLE_29, &SQR4_TABLE_29, &SQR8_TABLE_29, &QRT_TABLE_29, &QRT_TABLE_29, IdTrans, &ID_TRANS, &ID_TRANS> Field29; typedef FieldTri<uint32_t, 29, 2, RecLinTrans<uint32_t, 6, 6, 6, 6, 5>, &SQR_TABLE_29, &SQR2_TABLE_29, &SQR4_TABLE_29, &SQR8_TABLE_29, &QRT_TABLE_29, &QRT_TABLE_29, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri29; #endif #ifdef ENABLE_FIELD_INT_30 // 30 bit field typedef RecLinTrans<uint32_t, 6, 6, 6, 6, 6> StatTableTRI30; constexpr StatTableTRI30 SQR_TABLE_TRI30({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000, 0x30000000}); constexpr StatTableTRI30 SQR2_TABLE_TRI30({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0xc, 0xc0, 0xc00, 0xc000, 0xc0000, 0xc00000, 0xc000000, 0x5, 0x50, 0x500, 0x5000, 0x50000, 0x500000, 0x5000000, 0x10000003, 0x3c, 0x3c0, 0x3c00, 0x3c000, 0x3c0000, 0x3c00000, 0x3c000000}); constexpr StatTableTRI30 SQR4_TABLE_TRI30({0x1, 0x10000, 0xc, 0xc0000, 0x50, 0x500000, 0x3c0, 0x3c00000, 0x1100, 0x11000000, 0xcc00, 0xc000005, 0x55000, 0x1000003f, 0x3fc000, 0x101, 0x1010000, 0xc0c, 0xc0c0000, 0x5050, 0x10500003, 0x3c3c0, 0x3c00011, 0x111100, 0x110000cc, 0xcccc00, 0xc000555, 0x5555000, 0x10003fff, 0x3fffc000}); constexpr StatTableTRI30 SQR8_TABLE_TRI30({0x1, 0x1010000, 0xc000c, 0xc0c5050, 0x390, 0x13900012, 0x12c012c0, 0x121ddddd, 0x54100, 0x1003f33, 0xc3f0d04, 0x9555558, 0xd379000, 0x105d3fa2, 0x1d615e9e, 0x1101, 0x100100cc, 0xc0ccc09, 0x5590505, 0x3a9390, 0x3913fec, 0x13fedfcd, 0x121ddd8c, 0x11544103, 0x2cc3cff, 0x3e24c45, 0x9558bc8, 0x3a7958b, 0x1e98b158, 0x29d629e9}); constexpr StatTableTRI30 QRT_TABLE_TRI30({0x2159df4a, 0x109134a, 0x1091348, 0x10114, 0x109134c, 0x3a203420, 0x1011c, 0x20004080, 0x109135c, 0x2005439c, 0x3a203400, 0x100400, 0x1015c, 0x3eb21930, 0x20004000, 0x20504c00, 0x109125c, 0x3b2b276c, 0x2005419c, 0x210450c0, 0x3a203000, 0x3e93186c, 0x100c00, 0x3aa23530, 0x1115c, 0x6b3286c, 0x3eb23930, 0xeb23930, 0x20000000, 0}); typedef FieldTri<uint32_t, 30, 1, StatTableTRI30, &SQR_TABLE_TRI30, &SQR2_TABLE_TRI30, &SQR4_TABLE_TRI30, &SQR8_TABLE_TRI30, &QRT_TABLE_TRI30, &QRT_TABLE_TRI30, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri30; #endif #ifdef ENABLE_FIELD_INT_31 // 31 bit field typedef RecLinTrans<uint32_t, 6, 5, 5, 5, 5, 5> StatTable31; constexpr StatTable31 SQR_TABLE_31({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x48000, 0x120000, 0x480000, 0x1200000, 0x4800000, 0x12000000, 0x48000000, 0x20000012}); constexpr StatTable31 SQR2_TABLE_31({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x12, 0x120, 0x1200, 0x12000, 0x120000, 0x1200000, 0x12000000, 0x20000012, 0x104, 0x1040, 0x10400, 0x104000, 0x1040000, 0x10400000, 0x4000012, 0x40000120, 0x1248, 0x12480, 0x124800, 0x1248000, 0x12480000, 0x24800012, 0x48000104}); constexpr StatTable31 SQR4_TABLE_31({0x1, 0x10000, 0x12, 0x120000, 0x104, 0x1040000, 0x1248, 0x12480000, 0x10010, 0x100012, 0x120120, 0x1200104, 0x1041040, 0x10401248, 0x12492480, 0x24810002, 0x112, 0x1120000, 0x1304, 0x13040000, 0x11648, 0x16480012, 0x134810, 0x48100116, 0x1121120, 0x11201304, 0x13053040, 0x3041165a, 0x16596492, 0x64934922, 0x49248016}); constexpr StatTable31 SQR8_TABLE_31({0x1, 0x112, 0x10104, 0x1131648, 0x10002, 0x1120224, 0x106021a, 0x146e3f86, 0x16, 0x174c, 0x161658, 0x175b1130, 0x16002c, 0x174c2e98, 0x16742dfc, 0x3f877966, 0x114, 0x10768, 0x1151050, 0x66b75b2, 0x1140228, 0x76a0ec2, 0x127a33da, 0x79648102, 0x1738, 0x1665f0, 0x172f64e0, 0x73cc668c, 0x17382e70, 0x65dccaac, 0x4abf956e}); constexpr StatTable31 QRT_TABLE_31({0, 0x10110, 0x10112, 0x15076e, 0x10116, 0x117130e, 0x150766, 0x4743fa0, 0x10106, 0x1121008, 0x117132e, 0x176b248e, 0x150726, 0x172a2c88, 0x4743f20, 0x7eb81e86, 0x10006, 0x20008, 0x1121208, 0x56b2c8e, 0x117172e, 0x133f1bae, 0x176b2c8e, 0x7f2a0c8e, 0x151726, 0x10000000, 0x172a0c88, 0x60000006, 0x4747f20, 0x3eb89e80, 0x7eb89e86}); typedef Field<uint32_t, 31, 9, StatTable31, &SQR_TABLE_31, &SQR2_TABLE_31, &SQR4_TABLE_31, &SQR8_TABLE_31, &QRT_TABLE_31, &QRT_TABLE_31, IdTrans, &ID_TRANS, &ID_TRANS> Field31; typedef FieldTri<uint32_t, 31, 3, RecLinTrans<uint32_t, 6, 5, 5, 5, 5, 5>, &SQR_TABLE_31, &SQR2_TABLE_31, &SQR4_TABLE_31, &SQR8_TABLE_31, &QRT_TABLE_31, &QRT_TABLE_31, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri31; #endif #ifdef ENABLE_FIELD_INT_32 // 32 bit field typedef RecLinTrans<uint32_t, 6, 6, 5, 5, 5, 5> StatTable32; constexpr StatTable32 SQR_TABLE_32({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x8d, 0x234, 0x8d0, 0x2340, 0x8d00, 0x23400, 0x8d000, 0x234000, 0x8d0000, 0x2340000, 0x8d00000, 0x23400000, 0x8d000000, 0x3400011a, 0xd0000468, 0x40001037}); constexpr StatTable32 SQR2_TABLE_32({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x8d, 0x8d0, 0x8d00, 0x8d000, 0x8d0000, 0x8d00000, 0x8d000000, 0xd0000468, 0x4051, 0x40510, 0x405100, 0x4051000, 0x40510000, 0x5100234, 0x51002340, 0x100236b9, 0x236b1d, 0x236b1d0, 0x236b1d00, 0x36b1d11a, 0x6b1d1037, 0xb1d1005e, 0x1d10001f, 0xd100017d}); constexpr StatTable32 SQR4_TABLE_32({0x1, 0x10000, 0x8d, 0x8d0000, 0x4051, 0x40510000, 0x236b1d, 0x6b1d1037, 0x10001101, 0x1109d000, 0xd00859e5, 0x59881468, 0x144737e8, 0x37e2c4e3, 0xc4f9a67a, 0xa61d8c55, 0x8c010001, 0x41dc8d, 0xdc8d23cd, 0x23a60c51, 0xc41630e, 0x63087fcd, 0x7ffe7368, 0x735580f6, 0x80cd8e29, 0x8e6fe311, 0xe350f32b, 0xf35edc90, 0xdced0bd6, 0xbbd3eb1, 0x3eb4a621, 0xa63f6bc4}); constexpr StatTable32 SQR8_TABLE_32({0x1, 0x8c010001, 0x6b9010bb, 0x7faf6b, 0xc4da8d37, 0xc10ab646, 0x445f546c, 0xe389129e, 0xd8aa2d3e, 0x85249468, 0xd599253f, 0x458976f9, 0xc9c86411, 0xccc2f34b, 0xa79e37dc, 0x9068e3c4, 0x3a30447f, 0x674c3398, 0x94f38a7, 0x402d3532, 0x116fffc7, 0x1c6b5ba2, 0xcd6a32e4, 0x49067a77, 0xa7f6a61e, 0x3cc3746, 0xeebe962e, 0x599276e1, 0x7b5fa4d9, 0x2aa3ce1, 0x990f8767, 0x1c3b66cb}); constexpr StatTable32 QRT_TABLE_32({0x54fd1264, 0xc26fcd64, 0xc26fcd66, 0x238a7462, 0xc26fcd62, 0x973bccaa, 0x238a746a, 0x77766712, 0xc26fcd72, 0xc1bdd556, 0x973bcc8a, 0x572a094c, 0x238a742a, 0xb693be84, 0x77766792, 0x9555c03e, 0xc26fcc72, 0x568419f8, 0xc1bdd756, 0x96c3d2ca, 0x973bc88a, 0x54861fdc, 0x572a014c, 0xb79badc4, 0x238a642a, 0xb9b99fe0, 0xb6939e84, 0xc519fa86, 0x77762792, 0, 0x9555403e, 0x377627ba}); typedef Field<uint32_t, 32, 141, StatTable32, &SQR_TABLE_32, &SQR2_TABLE_32, &SQR4_TABLE_32, &SQR8_TABLE_32, &QRT_TABLE_32, &QRT_TABLE_32, IdTrans, &ID_TRANS, &ID_TRANS> Field32; #endif } Sketch* ConstructClMul4Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_25 case 25: return new SketchImpl<Field25>(implementation, 25); #endif #ifdef ENABLE_FIELD_INT_26 case 26: return new SketchImpl<Field26>(implementation, 26); #endif #ifdef ENABLE_FIELD_INT_27 case 27: return new SketchImpl<Field27>(implementation, 27); #endif #ifdef ENABLE_FIELD_INT_29 case 29: return new SketchImpl<Field29>(implementation, 29); #endif #ifdef ENABLE_FIELD_INT_31 case 31: return new SketchImpl<Field31>(implementation, 31); #endif #ifdef ENABLE_FIELD_INT_32 case 32: return new SketchImpl<Field32>(implementation, 32); #endif } return nullptr; } Sketch* ConstructClMulTri4Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_25 case 25: return new SketchImpl<FieldTri25>(implementation, 25); #endif #ifdef ENABLE_FIELD_INT_28 case 28: return new SketchImpl<FieldTri28>(implementation, 28); #endif #ifdef ENABLE_FIELD_INT_29 case 29: return new SketchImpl<FieldTri29>(implementation, 29); #endif #ifdef ENABLE_FIELD_INT_30 case 30: return new SketchImpl<FieldTri30>(implementation, 30); #endif #ifdef ENABLE_FIELD_INT_31 case 31: return new SketchImpl<FieldTri31>(implementation, 31); #endif } return nullptr; }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/clmul_5bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_5) #include "clmul_common_impl.h" #include "../int_utils.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_33 // 33 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5> StatTable33; constexpr StatTable33 SQR_TABLE_33({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x802, 0x2008, 0x8020, 0x20080, 0x80200, 0x200800, 0x802000, 0x2008000, 0x8020000, 0x20080000, 0x80200000, 0x800401, 0x2001004, 0x8004010, 0x20010040, 0x80040100}); constexpr StatTable33 SQR2_TABLE_33({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x2008, 0x20080, 0x200800, 0x2008000, 0x20080000, 0x800401, 0x8004010, 0x80040100, 0x400004, 0x4000040, 0x40000400, 0x4802, 0x48020, 0x480200, 0x4802000, 0x48020000, 0x80200802, 0x2009024, 0x20090240, 0x902001, 0x9020010, 0x90200100, 0x102000004, 0x20002048}); constexpr StatTable33 SQR4_TABLE_33({0x1, 0x10000, 0x100000000, 0x2008000, 0x80040100, 0x4802, 0x48020000, 0x902001, 0x20002048, 0x20081000, 0x10400004, 0x248820, 0x88204812, 0x49020410, 0x4822081, 0x20880641, 0x6000044, 0x480300, 0x3009024, 0x90220180, 0xa00c11, 0xc104050, 0x40482608, 0x2688b024, 0xb0690344, 0x102248834, 0x8a30c912, 0xc8062518, 0x24886803, 0x684a0244, 0x294a025, 0xa020294a, 0x280a1010}); constexpr StatTable33 SQR8_TABLE_33({0x1, 0x6000044, 0x280a1010, 0x122ac8e75, 0x83209926, 0x4a7a8a1, 0xcada863d, 0x6f2ab824, 0x6b4a8654, 0x70484bd6, 0x164c04e0b, 0x2fbc1617, 0xe095e5a3, 0xeaf7847d, 0xe5625e26, 0xa6aaa3e5, 0xc0164126, 0xd06217c0, 0x1ae58d21, 0xa8600250, 0xbaf87951, 0x8e12c19a, 0xa9b413b9, 0xb75ef087, 0x17e9214d9, 0x85968f33, 0x1e299478f, 0x92bc9a0f, 0x1975d642, 0x11af0b3f1, 0x4e86ee77, 0xe75f4726, 0x38026cce}); constexpr StatTable33 SQR16_TABLE_33({0x1, 0x185df5e91, 0x193fb40eb, 0xd464f9e4, 0x1ba2d73a6, 0x1d9288c5e, 0x5de03a49, 0x1869ea37b, 0x13faaf379, 0x195d1a8f5, 0x6afd5625, 0xf9d75bab, 0xaf44fe50, 0x101034b9e, 0xcc889caf, 0x5ec7455, 0x7d232a66, 0x17dcfe2c3, 0x1c66ff8d0, 0x17107e836, 0x1939cdead, 0x9852afa0, 0x1b946909a, 0x1846638c5, 0xdd5fa94c, 0x1cb2600fe, 0x19241c856, 0x15fe05ccd, 0xc9f9a425, 0x89e0f463, 0x37b01b39, 0xab0410e0, 0x1ace4ca03}); constexpr StatTable33 QRT_TABLE_33({0xba504dd4, 0x1e2798ef2, 0x1e2798ef0, 0x6698a4ec, 0x1e2798ef4, 0x1c7f1bef0, 0x6698a4e4, 0x16da1b384, 0x1e2798ee4, 0x661ca6ec, 0x1c7f1bed0, 0x1483b87a6, 0x6698a4a4, 0x800000, 0x16da1b304, 0x1a185101c, 0x1e2798fe4, 0xaa400954, 0x661ca4ec, 0x667caeec, 0x1c7f1bad0, 0x400800, 0x1483b8fa6, 0, 0x6698b4a4, 0x1c61da4b8, 0x802000, 0x16e5dadec, 0x16da1f304, 0x62fc8eec, 0x1a185901c, 0x1661da5ec, 0x1e2788fe4}); typedef Field<uint64_t, 33, 1025, StatTable33, &SQR_TABLE_33, &SQR2_TABLE_33, &SQR4_TABLE_33, &SQR8_TABLE_33, &SQR16_TABLE_33, &QRT_TABLE_33, IdTrans, &ID_TRANS, &ID_TRANS> Field33; typedef FieldTri<uint64_t, 33, 10, RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5>, &SQR_TABLE_33, &SQR2_TABLE_33, &SQR4_TABLE_33, &SQR8_TABLE_33, &SQR16_TABLE_33, &QRT_TABLE_33, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri33; #endif #ifdef ENABLE_FIELD_INT_34 // 34 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5> StatTable34; constexpr StatTable34 SQR_TABLE_34({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x81, 0x204, 0x810, 0x2040, 0x8100, 0x20400, 0x81000, 0x204000, 0x810000, 0x2040000, 0x8100000, 0x20400000, 0x81000000, 0x204000000, 0x10000102, 0x40000408, 0x100001020}); constexpr StatTable34 SQR2_TABLE_34({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x204, 0x2040, 0x20400, 0x204000, 0x2040000, 0x20400000, 0x204000000, 0x40000408, 0x4001, 0x40010, 0x400100, 0x4001000, 0x40010000, 0x100081, 0x1000810, 0x10008100, 0x100081000, 0x810204, 0x8102040, 0x81020400, 0x10204102, 0x102041020, 0x20410004, 0x204100040, 0x41000008}); constexpr StatTable34 SQR4_TABLE_34({0x1, 0x10000, 0x100000000, 0x204000, 0x40000408, 0x4001000, 0x10008100, 0x81020400, 0x204100040, 0x304, 0x3040000, 0x6041, 0x60410000, 0x1000c1010, 0x10304183, 0x4181020c, 0x102042060, 0x20400001, 0x50010, 0x100100081, 0xa14204, 0x142041428, 0x14001001, 0x10038500, 0x385020400, 0x204704140, 0x41000f1c, 0xf143040, 0x3041e145, 0x1e1430410, 0x3042c5050, 0x5030448b, 0x4481120c, 0x112048120}); constexpr StatTable34 SQR8_TABLE_34({0x1, 0x102042060, 0x4481120c, 0x1523455ab, 0x307081050, 0x21410f1c, 0x275d0e309, 0x3f676408a, 0x143a54d38, 0x304100344, 0x181774550, 0x1003cd092, 0x3f36b6421, 0x164d51695, 0x3e7c7f2ab, 0x9309b234, 0x354f8d24c, 0x1f5431410, 0x142012478, 0xc5225409, 0x14033f3cf, 0x123bd530c, 0x1100ee58, 0x35490c368, 0x2e1f3dcba, 0x2018108d2, 0x3c61a735d, 0xbf8fa918, 0x282ab07ea, 0x19c32af, 0x175e54c02, 0x2e4dfe2bb, 0x3374ab928, 0x3124a055}); constexpr StatTable34 SQR16_TABLE_34({0x1, 0x3448e6f02, 0x352590eb9, 0xb173da17, 0x264977d39, 0x172d45e48, 0x1e026e5d6, 0x357b54017, 0x2925d27a4, 0x1f6a32696, 0x2f49f220c, 0x3a7383d9e, 0x28111d79b, 0x5580fcf1, 0x276ede679, 0x175b379f8, 0x34d67b66, 0xc7019416, 0x3f3d9d59f, 0x2a7c2c032, 0x2b3482ba7, 0x177cd0128, 0x1d6f4bd2e, 0x31647a632, 0x41353027, 0x56292eea, 0x2733c0501, 0x6d7ed066, 0x2f3db9a75, 0x3225bc5cc, 0x3f22da089, 0xd0a7588e, 0xb60b22d1, 0xc2fddb7e}); constexpr StatTable34 QRT_TABLE_34({0x2f973a1f6, 0x40202, 0x40200, 0x348102060, 0x40204, 0x8000420, 0x348102068, 0x1092195c8, 0x40214, 0x3f6881b6e, 0x8000400, 0x3f810383e, 0x348102028, 0x340002068, 0x109219548, 0x24015a774, 0x40314, 0x3f050343e, 0x3f688196e, 0x3f81c3a3a, 0x8000000, 0x24031a560, 0x3f810303e, 0xb08c1a12, 0x348103028, 0xb2881906, 0x340000068, 0, 0x10921d548, 0x2e131e576, 0x240152774, 0x18921d55e, 0x50314, 0x14015271c}); typedef Field<uint64_t, 34, 129, StatTable34, &SQR_TABLE_34, &SQR2_TABLE_34, &SQR4_TABLE_34, &SQR8_TABLE_34, &SQR16_TABLE_34, &QRT_TABLE_34, IdTrans, &ID_TRANS, &ID_TRANS> Field34; typedef FieldTri<uint64_t, 34, 7, RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5>, &SQR_TABLE_34, &SQR2_TABLE_34, &SQR4_TABLE_34, &SQR8_TABLE_34, &SQR16_TABLE_34, &QRT_TABLE_34, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri34; #endif #ifdef ENABLE_FIELD_INT_35 // 35 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5> StatTable35; constexpr StatTable35 SQR_TABLE_35({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0xa, 0x28, 0xa0, 0x280, 0xa00, 0x2800, 0xa000, 0x28000, 0xa0000, 0x280000, 0xa00000, 0x2800000, 0xa000000, 0x28000000, 0xa0000000, 0x280000000, 0x200000005}); constexpr StatTable35 SQR2_TABLE_35({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0xa, 0xa0, 0xa00, 0xa000, 0xa0000, 0xa00000, 0xa000000, 0xa0000000, 0x200000005, 0x44, 0x440, 0x4400, 0x44000, 0x440000, 0x4400000, 0x44000000, 0x440000000, 0x400000028, 0x2a8, 0x2a80, 0x2a800, 0x2a8000, 0x2a80000, 0x2a800000, 0x2a8000000, 0x280000011}); constexpr StatTable35 SQR4_TABLE_35({0x1, 0x10000, 0x100000000, 0xa000, 0xa0000000, 0x4400, 0x44000000, 0x2a80, 0x2a800000, 0x1010, 0x10100000, 0xa0a, 0xa0a0000, 0x200000445, 0x4444000, 0x4400002a8, 0x2aaa800, 0x2a8000101, 0x1000100, 0x10000a0, 0xa000a0, 0xa00044, 0x440044, 0x400440028, 0x4002a8028, 0x2802a8011, 0x280101011, 0x1010100a, 0x100a0a0a, 0x20a0a0a05, 0x20a044445, 0x444444440, 0x44442aaa8, 0x2aaaaaaa8, 0x2aaa90001}); constexpr StatTable35 SQR8_TABLE_35({0x1, 0x2aaa800, 0x44442aaa8, 0x6400006ed, 0x64e4e4e45, 0x14544000, 0x8a145454, 0x2000034df, 0x49a749a36, 0xaa0a0000, 0x10aa0aaa, 0x1ba1a, 0x393a91ba, 0x3febaaaa9, 0x285105155, 0xa0ad9ad4, 0x269ce8d3b, 0x4de74f4e6, 0x42aaa8028, 0x4002aeea8, 0x400e46eec, 0x544e4006c, 0x145440144, 0x2abede545, 0x44309e74c, 0xa74eeda4, 0x64444ee49, 0x1aa1aaaa, 0x2b90bb1b1, 0x393902109, 0x16bc47bb2, 0x271ad1511, 0x6c8f98767, 0x69d3aa74c, 0x27790dc3b}); constexpr StatTable35 SQR16_TABLE_35({0x1, 0x4c80f98a4, 0x763684437, 0x5a1cc86a0, 0x38922db8, 0x71755e12d, 0x2ca94c627, 0x388a2bc7f, 0x406596de0, 0x1818c6958, 0x174a92efe, 0x1a80c764e, 0x2f23eacbf, 0xd611ea8, 0x64d783fd5, 0x4fdfe0798, 0x31459de8d, 0x62c889d99, 0x9c419962, 0x2d8d865b3, 0x1ac7e7ffc, 0x38a0c12f3, 0x9fbc1076, 0x6f76d3b89, 0x6e472c757, 0x5f240de42, 0x10176ecc0, 0x20c1cef8, 0x8f77f91c, 0x3f6e533b9, 0x62017c147, 0x5ce81e2fa, 0x371fe4ad9, 0x2552b5046, 0xc3f3696c}); constexpr StatTable35 QRT_TABLE_35({0x5c2038114, 0x2bf547ee8, 0x2bf547eea, 0x2bf1074e8, 0x2bf547eee, 0x1883d0736, 0x2bf1074e0, 0x100420, 0x2bf547efe, 0x400800, 0x1883d0716, 0x5e90e4a0, 0x2bf1074a0, 0x4e70ac20, 0x1004a0, 0x2f060c880, 0x2bf547ffe, 0x37d55fffe, 0x400a00, 0x3372573de, 0x1883d0316, 0x700c20, 0x5e90eca0, 0x10604880, 0x2bf1064a0, 0x18f35377e, 0x4e708c20, 0x33f557ffe, 0x1044a0, 0x1bf557ffe, 0x2f0604880, 0x200000000, 0x2bf557ffe, 0, 0x37d57fffe}); typedef Field<uint64_t, 35, 5, StatTable35, &SQR_TABLE_35, &SQR2_TABLE_35, &SQR4_TABLE_35, &SQR8_TABLE_35, &SQR16_TABLE_35, &QRT_TABLE_35, IdTrans, &ID_TRANS, &ID_TRANS> Field35; typedef FieldTri<uint64_t, 35, 2, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5>, &SQR_TABLE_35, &SQR2_TABLE_35, &SQR4_TABLE_35, &SQR8_TABLE_35, &SQR16_TABLE_35, &QRT_TABLE_35, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri35; #endif #ifdef ENABLE_FIELD_INT_36 // 36 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6> StatTable36; constexpr StatTable36 SQR_TABLE_36({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x201, 0x804, 0x2010, 0x8040, 0x20100, 0x80400, 0x201000, 0x804000, 0x2010000, 0x8040000, 0x20100000, 0x80400000, 0x201000000, 0x804000000, 0x10000402, 0x40001008, 0x100004020, 0x400010080}); constexpr StatTable36 SQR2_TABLE_36({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x201, 0x2010, 0x20100, 0x201000, 0x2010000, 0x20100000, 0x201000000, 0x10000402, 0x100004020, 0x40001, 0x400010, 0x4000100, 0x40001000, 0x400010000, 0x100804, 0x1008040, 0x10080400, 0x100804000, 0x8040201, 0x80402010, 0x804020100, 0x40200008, 0x402000080, 0x20000004, 0x200000040, 0x2, 0x20}); constexpr StatTable36 SQR4_TABLE_36({0x1, 0x10000, 0x100000000, 0x201000, 0x10000402, 0x4000100, 0x1008040, 0x80402010, 0x20000004, 0x200, 0x2000000, 0x4020, 0x40200000, 0x80002, 0x800020000, 0x201008000, 0x80400010, 0x4, 0x40000, 0x400000000, 0x804000, 0x40001008, 0x10000400, 0x4020100, 0x201008040, 0x80000010, 0x800, 0x8000000, 0x10080, 0x100800000, 0x200008, 0x80402, 0x804020000, 0x201000040, 0x10, 0x100000}); constexpr StatTable36 SQR8_TABLE_36({0x1, 0x80400010, 0x804020000, 0x201008, 0x2000080, 0x20000804, 0x1008000, 0x402, 0x800000, 0x200, 0x80000010, 0x804020100, 0x40201000, 0x400010000, 0x100004, 0x201000000, 0x80400, 0x100000000, 0x40000, 0x10, 0x804000100, 0x40201008, 0x2010080, 0x20000800, 0x200008040, 0x10080000, 0x4020, 0x8000000, 0x2000, 0x800000100, 0x40200008, 0x402010000, 0x100804, 0x1000040, 0x10000402, 0x804000}); constexpr StatTable36 SQR16_TABLE_36({0x1, 0x402000000, 0x100800020, 0x201000, 0x10080402, 0x800000000, 0x1008040, 0x400000, 0x20000800, 0x200, 0x400010080, 0x100000020, 0x40200000, 0x10080002, 0x20100, 0x201008000, 0x80000000, 0x100804, 0x40000, 0x2000080, 0x20, 0x40001008, 0x10000002, 0x4020000, 0x201008040, 0x2010, 0x20100800, 0x8000000, 0x400010000, 0x4000, 0x200008, 0x2, 0x804000000, 0x201000040, 0x402000, 0x20100804}); constexpr StatTable36 QRT_TABLE_36({0x40200, 0x8b0526186, 0x8b0526184, 0x240001000, 0x8b0526180, 0xcb6894d94, 0x240001008, 0xdb6880c22, 0x8b0526190, 0x8000200, 0xcb6894db4, 0x500424836, 0x240001048, 0x406cb2834, 0xdb6880ca2, 0x241200008, 0x8b0526090, 0xdb05021a6, 0x8000000, 0xdb01829b2, 0xcb68949b4, 0x1001000, 0x500424036, 0x106116406, 0x240000048, 0xcb29968a4, 0x406cb0834, 0, 0xdb6884ca2, 0x110010516, 0x241208008, 0x430434520, 0x8b0536090, 0x41208040, 0xdb05221a6, 0xb6884d14}); typedef Field<uint64_t, 36, 513, StatTable36, &SQR_TABLE_36, &SQR2_TABLE_36, &SQR4_TABLE_36, &SQR8_TABLE_36, &SQR16_TABLE_36, &QRT_TABLE_36, IdTrans, &ID_TRANS, &ID_TRANS> Field36; typedef FieldTri<uint64_t, 36, 9, RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6>, &SQR_TABLE_36, &SQR2_TABLE_36, &SQR4_TABLE_36, &SQR8_TABLE_36, &SQR16_TABLE_36, &QRT_TABLE_36, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri36; #endif #ifdef ENABLE_FIELD_INT_37 // 37 bit field typedef RecLinTrans<uint64_t, 6, 6, 5, 5, 5, 5, 5> StatTable37; constexpr StatTable37 SQR_TABLE_37({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0xa6, 0x298, 0xa60, 0x2980, 0xa600, 0x29800, 0xa6000, 0x298000, 0xa60000, 0x2980000, 0xa600000, 0x29800000, 0xa6000000, 0x298000000, 0xa60000000, 0x980000053, 0x60000011f, 0x180000047c}); constexpr StatTable37 SQR2_TABLE_37({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x298, 0x2980, 0x29800, 0x298000, 0x2980000, 0x29800000, 0x298000000, 0x980000053, 0x180000047c, 0x4414, 0x44140, 0x441400, 0x4414000, 0x44140000, 0x441400000, 0x4140000a6, 0x140000ac6, 0x140000ac60, 0xac43e, 0xac43e0, 0xac43e00, 0xac43e000, 0xac43e0000, 0xc43e0011f, 0x43e00101a, 0x3e0010106, 0x1e00101033}); constexpr StatTable37 SQR4_TABLE_37({0x1, 0x10000, 0x100000000, 0x29800, 0x298000000, 0x44140, 0x441400000, 0xac43e, 0xac43e0000, 0x1e00101033, 0x1010011000, 0x11029a980, 0x9a982b1d3, 0x2b1c45014, 0x4501005f2, 0x1005f8ef80, 0x18efa98941, 0x9897de117, 0x1de10002ad, 0x2990398, 0x190398047c, 0x180443dee4, 0x3ded94ac6, 0x194ac071fa, 0x71c56e1a, 0x56e1adff2, 0x1adffa1690, 0x1a16a9ab31, 0x9ab0957cf, 0x957d85468, 0x18547edba2, 0x1edb9fc515, 0x1fc526c1a4, 0x6c1956aab, 0x156aa5b9d4, 0x5b9f59def, 0x159de6d961}); constexpr StatTable37 SQR8_TABLE_37({0x1, 0x18efa98941, 0x1fc526c1a4, 0x11352e16c4, 0xba7aa5340, 0x17346e075f, 0xe91c746aa, 0xe560ac1bd, 0xa4544c5d9, 0x11bd3c631f, 0xd70c4b63c, 0xfe77d107c, 0x10548e5288, 0x1183954fb3, 0x19b3aa4bb, 0x782a2943c, 0x1c19ba61de, 0x6ad01fe38, 0xa22701577, 0xb96546ca0, 0x1d7c6c8b9c, 0xffef807e2, 0x16fcc14dc2, 0x110cc4e83c, 0xc3a35629a, 0x1062330476, 0xb2e5d1de1, 0x1ca4e3d229, 0x67826b51b, 0xe7e4c36e7, 0x59f1ac963, 0x12777f22c6, 0x13963d623a, 0x9e305ac92, 0x219b91d13, 0x175bebeb0d, 0xc6b7b5572}); constexpr StatTable37 SQR16_TABLE_37({0x1, 0xcb88f2f8b, 0x1a2a0be7af, 0xb93048ada, 0x113ed92190, 0xc95a18e2b, 0x1e1cd4a85b, 0x19584a1a66, 0x1b947c28c2, 0x1b52b48e27, 0xe64e7b169, 0x14a256d011, 0xda657196d, 0x1947c1dcb4, 0x18b2fa3851, 0xae3d4171a, 0x658f1f4b9, 0x91852c314, 0x69346cf8e, 0x8224bf36c, 0x1086c810ed, 0x10419bc782, 0x57d6a4e36, 0xfbb31a43e, 0x18b502de05, 0x786795174, 0x1de0f1b7f3, 0x1d456b87dc, 0x1aabb2f3bc, 0xc5b80ef0c, 0x1ce4fd7543, 0x7ca740ca1, 0x29eaec26a, 0x1eb0b42043, 0xca3b2b17, 0x3453101c1, 0x1714c59187}); constexpr StatTable37 QRT_TABLE_37({0xa3c62e7ba, 0xdc7a0c16a, 0xdc7a0c168, 0x12f7484546, 0xdc7a0c16c, 0xa9803a20, 0x12f748454e, 0xda07064a4, 0xdc7a0c17c, 0x123908de8e, 0xa9803a00, 0x122a888a8e, 0x12f748450e, 0x6790add8, 0xda0706424, 0x12e0a0384c, 0xdc7a0c07c, 0xcb28a2c2, 0x123908dc8e, 0xd09f85e86, 0xa9803e00, 0x124d682b6e, 0x122a88828e, 0x1738711a, 0x12f748550e, 0x73035b8, 0x67908dd8, 0xa0702438, 0xda0702424, 0xe0a0b860, 0x12e0a0b84c, 0x1c7a1c060, 0xdc7a1c07c, 0, 0xcb2aa2c2, 0x100000002c, 0x12390cdc8e}); typedef Field<uint64_t, 37, 83, StatTable37, &SQR_TABLE_37, &SQR2_TABLE_37, &SQR4_TABLE_37, &SQR8_TABLE_37, &SQR16_TABLE_37, &QRT_TABLE_37, IdTrans, &ID_TRANS, &ID_TRANS> Field37; #endif #ifdef ENABLE_FIELD_INT_38 // 38 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5, 5> StatTable38; constexpr StatTable38 SQR_TABLE_38({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x63, 0x18c, 0x630, 0x18c0, 0x6300, 0x18c00, 0x63000, 0x18c000, 0x630000, 0x18c0000, 0x6300000, 0x18c00000, 0x63000000, 0x18c000000, 0x630000000, 0x18c0000000, 0x2300000063, 0xc0000014a, 0x3000000528}); constexpr StatTable38 SQR2_TABLE_38({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x18c, 0x18c0, 0x18c00, 0x18c000, 0x18c0000, 0x18c00000, 0x18c000000, 0x18c0000000, 0xc0000014a, 0x1405, 0x14050, 0x140500, 0x1405000, 0x14050000, 0x140500000, 0x1405000000, 0x500001ef, 0x500001ef0, 0x100001ef63, 0x1ef7bc, 0x1ef7bc0, 0x1ef7bc00, 0x1ef7bc000, 0x1ef7bc0000, 0x2f7bc00129, 0x37bc00112d, 0x3bc0011027, 0x3c00110022}); constexpr StatTable38 SQR4_TABLE_38({0x1, 0x10000, 0x100000000, 0x18c00, 0x18c000000, 0x14050, 0x140500000, 0x100001ef63, 0x1ef7bc000, 0x3bc0011027, 0x110001100, 0x110194c0, 0x194c0194c, 0x194d5455, 0xd5455154f, 0x151544a193, 0x4a18c631f, 0xc6319c6ca, 0x19c6c00014, 0x18c8d, 0x18c8d0000, 0xd00014096, 0x1409ddc00, 0x1ddc01efc6, 0x1efd5ab90, 0x15ab9110e1, 0x1110fe85b2, 0x3e85ab5465, 0x2b5445c97a, 0x5c9450993, 0x50994148f, 0x141488b12a, 0x8b134ee36, 0x34ee3a8ecc, 0x3a8ee3edc8, 0x23edeef7ed, 0x2ef7de8bf9, 0x1e8bc14041}); constexpr StatTable38 SQR8_TABLE_38({0x1, 0x4a18c631f, 0x8b134ee36, 0x10b5c9474c, 0x3330e98ecb, 0x939897650, 0xd74b026b9, 0x860251dd9, 0x3afbe829b4, 0x3ae6afc308, 0x239ecafe00, 0x2acbc94749, 0x3a5770e19e, 0x4052e180b, 0x321fa15712, 0x3a8a4869ef, 0x1948598082, 0x3b1bd98542, 0xc1deb9112, 0x1b5c9242e, 0x338ba58e8b, 0x8abe06d20, 0x145bb1d2a9, 0x1d6e10fbf0, 0x197d522629, 0x2ff1bbe50d, 0xcc1594a16, 0xc94db1b03, 0x3b20e51c56, 0x101d1e5d07, 0x19472478f7, 0x269635a968, 0x2fd4a35802, 0x1b63e116b6, 0x19fdf9d22a, 0x2ef0e4d419, 0x3e80f730f4, 0x29869b04b9}); constexpr StatTable38 SQR16_TABLE_38({0x1, 0x3f5fe2afaa, 0x4216541b5, 0x33b362f56a, 0x9d630d7e1, 0x11127694c1, 0x3f8daab2d6, 0x153ca20edc, 0x22a747a3de, 0xc6ab16040, 0x19cc9a7e37, 0x449d96001, 0x45a7e7c46, 0x36d11561ce, 0x114b93f52a, 0x42a87f1b3, 0x23112a30bc, 0x400df9212, 0x3aca9544df, 0x140c4b0bcf, 0x2ae2efa6d3, 0x2f7051159c, 0x19cca2f62e, 0x102023d8c0, 0xccc793f0b, 0x2ff4789b55, 0x339e4cd9ba, 0x2b02ab5052, 0x8c1b5db82, 0x2e461e4e32, 0xd93541605, 0x1acf12087, 0x33b88dca2b, 0x1e91723c8b, 0xd81047b2b, 0x2e5e54b97c, 0x85bb507d8, 0x2145b1864b}); constexpr StatTable38 QRT_TABLE_38({0x34b0ac6430, 0x2223262fa, 0x2223262f8, 0x35554405fe, 0x2223262fc, 0x355514098a, 0x35554405f6, 0x400840, 0x2223262ec, 0x1777726532, 0x35551409aa, 0x15c06fc0, 0x35554405b6, 0x1f5303fec, 0x4008c0, 0x236a21030, 0x2223263ec, 0x1a9008c00, 0x1777726732, 0x3692c60ab6, 0x3555140daa, 0x15556007ee, 0x15c067c0, 0x14a0b030f2, 0x35554415b6, 0x227c06d168, 0x1f5301fec, 0x16c3928fc2, 0x4048c0, 0x3a942c4c0, 0x236a29030, 0x1636a2902e, 0x2223363ec, 0x3a6e898276, 0x1a9028c00, 0x6de74eb2c, 0x1777766732, 0}); typedef Field<uint64_t, 38, 99, StatTable38, &SQR_TABLE_38, &SQR2_TABLE_38, &SQR4_TABLE_38, &SQR8_TABLE_38, &SQR16_TABLE_38, &QRT_TABLE_38, IdTrans, &ID_TRANS, &ID_TRANS> Field38; #endif #ifdef ENABLE_FIELD_INT_39 // 39 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5> StatTable39; constexpr StatTable39 SQR_TABLE_39({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x22, 0x88, 0x220, 0x880, 0x2200, 0x8800, 0x22000, 0x88000, 0x220000, 0x880000, 0x2200000, 0x8800000, 0x22000000, 0x88000000, 0x220000000, 0x880000000, 0x2200000000, 0x800000011, 0x2000000044}); constexpr StatTable39 SQR2_TABLE_39({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x22, 0x220, 0x2200, 0x22000, 0x220000, 0x2200000, 0x22000000, 0x220000000, 0x2200000000, 0x2000000044, 0x404, 0x4040, 0x40400, 0x404000, 0x4040000, 0x40400000, 0x404000000, 0x4040000000, 0x400000088, 0x4000000880, 0x8888, 0x88880, 0x888800, 0x8888000, 0x88880000, 0x888800000, 0x888000011, 0x880000101, 0x800001001}); constexpr StatTable39 SQR4_TABLE_39({0x1, 0x10000, 0x100000000, 0x2200, 0x22000000, 0x404, 0x4040000, 0x400000088, 0x888800, 0x888000011, 0x100010, 0x1000100000, 0x1000022000, 0x220022000, 0x220004040, 0x40404040, 0x4040400880, 0x4008888880, 0x888888101, 0x881000001, 0x122, 0x1220000, 0x2200000022, 0x260400, 0x2604000000, 0x48c88, 0x48c880000, 0x800009889, 0x98881000, 0x810001221, 0x12201220, 0x2012200264, 0x2002604264, 0x6042604044, 0x604048c8c4, 0x48c8c8c880, 0x48c8898881, 0x988888881, 0x888802201}); constexpr StatTable39 SQR8_TABLE_39({0x1, 0x4040400880, 0x2002604264, 0xaa8022011, 0x810049ea9, 0x100100010, 0xc04008101, 0x644048ea4c, 0x18c1764441, 0x60f8e8526c, 0x22000122, 0x48c88989a3, 0xae0032001, 0x2a7aeafae5, 0x6a76641225, 0x2036245242, 0x3e9ab0308b, 0x1c49f6fe41, 0x681b069e2d, 0x4edee8cae5, 0x898c04, 0x660daa8880, 0x69cae9ccc1, 0x4881320991, 0xd06280001, 0x1cc8c8e3d9, 0x445fc65628, 0x4c889a8a49, 0x300b8caeec, 0x50d842fc94, 0x1811acb89d, 0x9d22101c, 0x2025aa407e, 0x20370a744a, 0x3cf77cb80b, 0x54a13e66e7, 0x34c17e2e04, 0x5c19fe54c1, 0x6a72cc767d}); constexpr StatTable39 SQR16_TABLE_39({0x1, 0x37214861ce, 0x689e897065, 0x5678d6ee60, 0x619da834c4, 0x28352752d3, 0x14fed69ec6, 0x5b3d4aa637, 0x682fb8da4d, 0x2ce48c5615, 0x1591ac539c, 0x72d4fbcd0, 0x346b547296, 0x1e7065d419, 0x4e6eb48571, 0x26615d4c2c, 0x60d1c6122e, 0x78d0e2a2eb, 0x52bb3e2980, 0x3c2592d0ab, 0x701ba76b58, 0x5fdf53b685, 0x57cfd2d120, 0x75559e4344, 0x3837a46907, 0x15f961a4ce, 0x397b9a03e9, 0x5a8dd4ab69, 0x3a6ab3356f, 0x215d39c25e, 0x5bbaf82443, 0x6759e3c88c, 0x3c0b862ca1, 0x37eec7e79e, 0x6ce865e38, 0x4a56a338c0, 0x5684636aee, 0x325a019126, 0x24f18a4ef6}); constexpr StatTable39 QRT_TABLE_39({0x66b02a408c, 0x100420, 0x100422, 0x14206080, 0x100426, 0x5dccefab1c, 0x14206088, 0x9fc11e5b6, 0x100436, 0x5466bea62a, 0x5dccefab3c, 0x9aa110536, 0x142060c8, 0x54739ed6e2, 0x9fc11e536, 0xe7a82c080, 0x100536, 0x4002000, 0x5466bea42a, 0x6a4022000, 0x5dccefaf3c, 0x9e8118536, 0x9aa110d36, 0x5680e080, 0x142070c8, 0x7d293c5b6, 0x54739ef6e2, 0x8d680e080, 0x9fc11a536, 0x6d282c080, 0xe7a824080, 0x800000000, 0x110536, 0x2d680e080, 0x4022000, 0, 0x5466baa42a, 0x46b03a44aa, 0x6a40a2000}); typedef Field<uint64_t, 39, 17, StatTable39, &SQR_TABLE_39, &SQR2_TABLE_39, &SQR4_TABLE_39, &SQR8_TABLE_39, &SQR16_TABLE_39, &QRT_TABLE_39, IdTrans, &ID_TRANS, &ID_TRANS> Field39; typedef FieldTri<uint64_t, 39, 4, RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5>, &SQR_TABLE_39, &SQR2_TABLE_39, &SQR4_TABLE_39, &SQR8_TABLE_39, &SQR16_TABLE_39, &QRT_TABLE_39, IdTrans, &ID_TRANS, &ID_TRANS> FieldTri39; #endif #ifdef ENABLE_FIELD_INT_40 // 40 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5> StatTable40; constexpr StatTable40 SQR_TABLE_40({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x39, 0xe4, 0x390, 0xe40, 0x3900, 0xe400, 0x39000, 0xe4000, 0x390000, 0xe40000, 0x3900000, 0xe400000, 0x39000000, 0xe4000000, 0x390000000, 0xe40000000, 0x3900000000, 0xe400000000, 0x900000004b, 0x400000015e}); constexpr StatTable40 SQR2_TABLE_40({0x1, 0x10, 0x100, 0x1000, 0x10000, 0x100000, 0x1000000, 0x10000000, 0x100000000, 0x1000000000, 0x39, 0x390, 0x3900, 0x39000, 0x390000, 0x3900000, 0x39000000, 0x390000000, 0x3900000000, 0x900000004b, 0x541, 0x5410, 0x54100, 0x541000, 0x5410000, 0x54100000, 0x541000000, 0x5410000000, 0x41000000dd, 0x1000000d34, 0xd379, 0xd3790, 0xd37900, 0xd379000, 0xd3790000, 0xd37900000, 0xd379000000, 0x3790000115, 0x790000111b, 0x900001111f}); constexpr StatTable40 SQR4_TABLE_40({0x1, 0x10000, 0x100000000, 0x3900, 0x39000000, 0x541, 0x5410000, 0x41000000dd, 0xd37900, 0xd379000000, 0x111001, 0x1110010000, 0x10003aa90, 0x3aa903900, 0x903900511a, 0x51051541, 0x515410de9, 0x410de9de4d, 0xe9de437815, 0x437801010e, 0x101000038, 0x383939, 0x3839390000, 0x3900057d41, 0x57d444100, 0x444100d6e5, 0xd6ebaa79, 0xebaa7911c6, 0x7911d2791a, 0xd2791102a9, 0x1102b82901, 0xb82902a972, 0x2a96bfed1, 0x6bfed16851, 0xd16859f42e, 0x59f43f61a8, 0x3f61a43794, 0xa43791de59, 0x91de42401f, 0x424000390e}); constexpr StatTable40 SQR8_TABLE_40({0x1, 0x515410de9, 0x2a96bfed1, 0x13ba41ea90, 0x45bffe2b75, 0x5836900, 0x3887d7e690, 0xd34b688712, 0xc7a3d51557, 0xd1151ada71, 0x51442a740, 0x41cc5cbdb6, 0xc61a5701e9, 0x8757946d91, 0xa99e8b9e65, 0x80a0aca777, 0xc242b5c0e9, 0x6826eccb25, 0xad687ebd2d, 0xad5c69d802, 0x7ed2f8390, 0x51fa78eedf, 0xc0718c96f6, 0xaf4672a8c2, 0xc67436f2fd, 0x56ddb12767, 0x535afb0326, 0xbce1edda33, 0xef36202f0f, 0x45d13015ec, 0x104ab11aef, 0xef96c86d49, 0xc1b790bfc9, 0x2fa610e77f, 0x2a10a27d6e, 0xca5bb10773, 0xfdaf2b4642, 0xb3b4b7e20d, 0xe8bbe4d22e, 0xf9986bd2df}); constexpr StatTable40 SQR16_TABLE_40({0x1, 0xe88450a7de, 0x3a0a56c3e8, 0x1684757d36, 0xc7f40bf3e9, 0x38aa7009c0, 0x2b6f129659, 0xd1e0fc42e5, 0x96150bc554, 0x9774ef4cc1, 0xd34eebf74d, 0x2d183441ec, 0xeedf6d1c78, 0x3f93c5d217, 0xb924305809, 0xc383bb7c14, 0x3f242bb94e, 0x9313556f6b, 0x2f5e1ecc6b, 0x2e7f9df195, 0xac8b882870, 0xd14f457f55, 0xf9f936148d, 0x719190770, 0x6838b41a21, 0xb95ff30106, 0xc1527dd1c5, 0xe858b5f9b6, 0x9368a791c2, 0x7de23878af, 0x95c610d398, 0xed0edcb032, 0x9548a680b0, 0xc133469e7b, 0x68c96ccbb2, 0x7773231ebb, 0xbd5ef4207c, 0xdf8bd59374, 0xb862414268, 0xfa62b39e42}); constexpr StatTable40 QRT_TABLE_40({0x624b3cecc, 0xbc5c3f4c6, 0xbc5c3f4c4, 0xde1603e2c, 0xbc5c3f4c0, 0xaabec06cea, 0xde1603e24, 0x6cd9f724c2, 0xbc5c3f4d0, 0xcde1743818, 0xaabec06cca, 0xa138c314ca, 0xde1603e64, 0xaafc00f01a, 0x6cd9f72442, 0xcdca11bb4, 0xbc5c3f5d0, 0xa00002001a, 0xcde1743a18, 0xdf1407b90, 0xaabec068ca, 0xc043b482c8, 0xa138c31cca, 0xcb86977e3c, 0xde1602e64, 0x604596a326, 0xaafc00d01a, 0xcc1c165d0, 0x6cd9f76442, 0x673c94da26, 0xcdca19bb4, 0x67c0940a26, 0xbc5c2f5d0, 0xa4dca19bae, 0xa00000001a, 0x1bc5c2f5d0, 0xcde1703a18, 0, 0xdf1487b90, 0x8df1487b8a}); typedef Field<uint64_t, 40, 57, StatTable40, &SQR_TABLE_40, &SQR2_TABLE_40, &SQR4_TABLE_40, &SQR8_TABLE_40, &SQR16_TABLE_40, &QRT_TABLE_40, IdTrans, &ID_TRANS, &ID_TRANS> Field40; #endif } Sketch* ConstructClMul5Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_33 case 33: return new SketchImpl<Field33>(implementation, 33); #endif #ifdef ENABLE_FIELD_INT_34 case 34: return new SketchImpl<Field34>(implementation, 34); #endif #ifdef ENABLE_FIELD_INT_35 case 35: return new SketchImpl<Field35>(implementation, 35); #endif #ifdef ENABLE_FIELD_INT_36 case 36: return new SketchImpl<Field36>(implementation, 36); #endif #ifdef ENABLE_FIELD_INT_37 case 37: return new SketchImpl<Field37>(implementation, 37); #endif #ifdef ENABLE_FIELD_INT_38 case 38: return new SketchImpl<Field38>(implementation, 38); #endif #ifdef ENABLE_FIELD_INT_39 case 39: return new SketchImpl<Field39>(implementation, 39); #endif #ifdef ENABLE_FIELD_INT_40 case 40: return new SketchImpl<Field40>(implementation, 40); #endif } return nullptr; } Sketch* ConstructClMulTri5Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_33 case 33: return new SketchImpl<FieldTri33>(implementation, 33); #endif #ifdef ENABLE_FIELD_INT_34 case 34: return new SketchImpl<FieldTri34>(implementation, 34); #endif #ifdef ENABLE_FIELD_INT_35 case 35: return new SketchImpl<FieldTri35>(implementation, 35); #endif #ifdef ENABLE_FIELD_INT_36 case 36: return new SketchImpl<FieldTri36>(implementation, 36); #endif #ifdef ENABLE_FIELD_INT_39 case 39: return new SketchImpl<FieldTri39>(implementation, 39); #endif } return nullptr; }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_6bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_6) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_41 // 41 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5> StatTable41; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable41; constexpr StatTable41 SQR_TABLE_41({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x12, 0x48, 0x120, 0x480, 0x1200, 0x4800, 0x12000, 0x48000, 0x120000, 0x480000, 0x1200000, 0x4800000, 0x12000000, 0x48000000, 0x120000000, 0x480000000, 0x1200000000, 0x4800000000, 0x12000000000, 0x8000000012}); constexpr StatTable41 QRT_TABLE_41({0, 0x1599a5e0b0, 0x1599a5e0b2, 0x105c119e0, 0x1599a5e0b6, 0x1a2030452a6, 0x105c119e8, 0x1a307c55b2e, 0x1599a5e0a6, 0x1ee3f47bc8e, 0x1a203045286, 0x400808, 0x105c119a8, 0x1a3038573a6, 0x1a307c55bae, 0x4d2882a520, 0x1599a5e1a6, 0x1ffbaa0b720, 0x1ee3f47be8e, 0x4d68c22528, 0x1a203045686, 0x200006, 0x400008, 0x1b79a21b200, 0x105c109a8, 0x1ef3886a526, 0x1a3038553a6, 0x1b692209200, 0x1a307c51bae, 0x5d99a4e1a6, 0x4d28822520, 0x185e109ae, 0x1599a4e1a6, 0x4e3f43be88, 0x1ffbaa2b720, 0x4000000000, 0x1ee3f43be8e, 0x18000000006, 0x4d68ca2528, 0xa203145680, 0x1a203145686}); typedef Field<uint64_t, 41, 9, StatTable41, DynTable41, &SQR_TABLE_41, &QRT_TABLE_41> Field41; #endif #ifdef ENABLE_FIELD_INT_42 // 42 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6> StatTable42; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable42; constexpr StatTable42 SQR_TABLE_42({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x81, 0x204, 0x810, 0x2040, 0x8100, 0x20400, 0x81000, 0x204000, 0x810000, 0x2040000, 0x8100000, 0x20400000, 0x81000000, 0x204000000, 0x810000000, 0x2040000000, 0x8100000000, 0x20400000000, 0x1000000102, 0x4000000408, 0x10000001020}); constexpr StatTable42 QRT_TABLE_42({0x810200080, 0x120810806, 0x120810804, 0x1068c1a1000, 0x120810800, 0x34005023008, 0x1068c1a1008, 0x800004080, 0x120810810, 0x162818a10, 0x34005023028, 0x42408a14, 0x1068c1a1048, 0x1001040, 0x800004000, 0xb120808906, 0x120810910, 0x34000020068, 0x162818810, 0x68c021400, 0x34005023428, 0x10004000, 0x42408214, 0x162418214, 0x1068c1a0048, 0xb002018116, 0x1003040, 0x10008180448, 0x800000000, 0x62c08b04, 0xb120800906, 0x2408d1a3060, 0x120800910, 0x34401003028, 0x34000000068, 0, 0x162858810, 0xa042058116, 0x68c0a1400, 0x8162858806, 0x34005123428, 0x3068c0a1468}); typedef Field<uint64_t, 42, 129, StatTable42, DynTable42, &SQR_TABLE_42, &QRT_TABLE_42> Field42; #endif #ifdef ENABLE_FIELD_INT_43 // 43 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 5, 5, 5, 5, 5> StatTable43; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable43; constexpr StatTable43 SQR_TABLE_43({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0xb2, 0x2c8, 0xb20, 0x2c80, 0xb200, 0x2c800, 0xb2000, 0x2c8000, 0xb20000, 0x2c80000, 0xb200000, 0x2c800000, 0xb2000000, 0x2c8000000, 0xb20000000, 0x2c80000000, 0xb200000000, 0x2c800000000, 0x32000000059, 0x4800000013d, 0x20000000446}); constexpr StatTable43 QRT_TABLE_43({0x2bccc2d6f6c, 0x4bccc2d6f54, 0x4bccc2d6f56, 0x7cc7bc61df0, 0x4bccc2d6f52, 0x7d13b404b10, 0x7cc7bc61df8, 0x37456e9ac5a, 0x4bccc2d6f42, 0x4e042c6a6, 0x7d13b404b30, 0x4a56de9ef4c, 0x7cc7bc61db8, 0x14bc18d8e, 0x37456e9acda, 0x7c89f84fb1e, 0x4bccc2d6e42, 0x7ffae40d210, 0x4e042c4a6, 0x366f45dd06, 0x7d13b404f30, 0x496fcaf8cca, 0x4a56de9e74c, 0x370b62b6af4, 0x7cc7bc60db8, 0x1498185a8, 0x14bc1ad8e, 0x7e602c46a98, 0x37456e9ecda, 0x36ccc2c6e74, 0x7c89f847b1e, 0x7e27d06d516, 0x4bccc2c6e42, 0x7f93302c396, 0x7ffae42d210, 0x3dd3440706, 0x4e046c4a6, 0x78bbc09da36, 0x366f4ddd06, 0, 0x7d13b504f30, 0x8bbc09da00, 0x496fc8f8cca}); typedef Field<uint64_t, 43, 89, StatTable43, DynTable43, &SQR_TABLE_43, &QRT_TABLE_43> Field43; #endif #ifdef ENABLE_FIELD_INT_44 // 44 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5, 5> StatTable44; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable44; constexpr StatTable44 SQR_TABLE_44({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x21, 0x84, 0x210, 0x840, 0x2100, 0x8400, 0x21000, 0x84000, 0x210000, 0x840000, 0x2100000, 0x8400000, 0x21000000, 0x84000000, 0x210000000, 0x840000000, 0x2100000000, 0x8400000000, 0x21000000000, 0x84000000000, 0x10000000042, 0x40000000108}); constexpr StatTable44 QRT_TABLE_44({0xf05334f4f6e, 0x4002016, 0x4002014, 0xf04350e6246, 0x4002010, 0x4935b379a26, 0xf04350e624e, 0xf84250c228e, 0x4002000, 0xf04300e521e, 0x4935b379a06, 0xb966838dd48, 0xf04350e620e, 0xf7b8b80feda, 0xf84250c220e, 0xf972e097d5e, 0x4002100, 0x8000020000, 0xf04300e501e, 0x430025000, 0x4935b379e06, 0xf976a09dc5e, 0xb966838d548, 0xf84218c029a, 0xf04350e720e, 0x4925f36bf06, 0xf7b8b80deda, 0xb047d3ee758, 0xf84250c620e, 0xf80350e720e, 0xf972e09fd5e, 0x8091825284, 0x4012100, 0x9015063210, 0x8000000000, 0xff31a028c5e, 0xf04300a501e, 0x44340b7100, 0x4300a5000, 0, 0x4935b279e06, 0xa976b2dce18, 0xf976a29dc5e, 0x8935b279e18}); typedef Field<uint64_t, 44, 33, StatTable44, DynTable44, &SQR_TABLE_44, &QRT_TABLE_44> Field44; #endif #ifdef ENABLE_FIELD_INT_45 // 45 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5> StatTable45; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable45; constexpr StatTable45 SQR_TABLE_45({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x36, 0xd8, 0x360, 0xd80, 0x3600, 0xd800, 0x36000, 0xd8000, 0x360000, 0xd80000, 0x3600000, 0xd800000, 0x36000000, 0xd8000000, 0x360000000, 0xd80000000, 0x3600000000, 0xd800000000, 0x36000000000, 0xd8000000000, 0x16000000001b, 0x18000000005a}); constexpr StatTable45 QRT_TABLE_45({0xede34e3e0fc, 0x1554148191aa, 0x1554148191a8, 0x1767be1dc4a6, 0x1554148191ac, 0x26bd4931492, 0x1767be1dc4ae, 0x233ab9c454a, 0x1554148191bc, 0x16939e8bb3dc, 0x26bd49314b2, 0x3c6ca8bac52, 0x1767be1dc4ee, 0x16caa5054c16, 0x233ab9c45ca, 0x14a1649628bc, 0x1554148190bc, 0x3c382881252, 0x16939e8bb1dc, 0x3c7ca0aa160, 0x26bd49310b2, 0x27f40158000, 0x3c6ca8ba452, 0x173fc092853c, 0x1767be1dd4ee, 0x16cbe284f25c, 0x16caa5056c16, 0x155559002f96, 0x233ab9c05ca, 0x26eb8908b32, 0x14a16496a8bc, 0x15440885333c, 0x1554148090bc, 0x17d60702e0, 0x3c3828a1252, 0x54548d10b2, 0x16939e8fb1dc, 0x3ac1e81b1d2, 0x3c7ca02a160, 0x166bd48310bc, 0x26bd48310b2, 0, 0x27f40358000, 0x10000000000e, 0x3c6cacba452}); typedef Field<uint64_t, 45, 27, StatTable45, DynTable45, &SQR_TABLE_45, &QRT_TABLE_45> Field45; #endif #ifdef ENABLE_FIELD_INT_46 // 46 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5> StatTable46; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable46; constexpr StatTable46 SQR_TABLE_46({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x3, 0xc, 0x30, 0xc0, 0x300, 0xc00, 0x3000, 0xc000, 0x30000, 0xc0000, 0x300000, 0xc00000, 0x3000000, 0xc000000, 0x30000000, 0xc0000000, 0x300000000, 0xc00000000, 0x3000000000, 0xc000000000, 0x30000000000, 0xc0000000000, 0x300000000000}); constexpr StatTable46 QRT_TABLE_46({0x211c4fd486ba, 0x100104a, 0x1001048, 0x104d0492d4, 0x100104c, 0x20005040c820, 0x104d0492dc, 0x40008080, 0x100105c, 0x24835068ce00, 0x20005040c800, 0x200000400800, 0x104d04929c, 0x100904325c, 0x40008000, 0x25da9e77daf0, 0x100115c, 0x1184e1696f0, 0x24835068cc00, 0x24825169dd5c, 0x20005040cc00, 0x3ea3241c60c0, 0x200000400000, 0x211c4e5496f0, 0x104d04829c, 0x20005340d86c, 0x100904125c, 0x24835968de5c, 0x4000c000, 0x6400a0c0, 0x25da9e775af0, 0x118cf1687ac, 0x101115c, 0x1ea1745cacc0, 0x1184e1496f0, 0x20181e445af0, 0x2483506ccc00, 0x20240060c0, 0x24825161dd5c, 0x1e21755dbd9c, 0x20005050cc00, 0x26a3746cacc0, 0x3ea3243c60c0, 0xea3243c60c0, 0x200000000000, 0}); typedef Field<uint64_t, 46, 3, StatTable46, DynTable46, &SQR_TABLE_46, &QRT_TABLE_46> Field46; #endif #ifdef ENABLE_FIELD_INT_47 // 47 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5> StatTable47; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable47; constexpr StatTable47 SQR_TABLE_47({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x42, 0x108, 0x420, 0x1080, 0x4200, 0x10800, 0x42000, 0x108000, 0x420000, 0x1080000, 0x4200000, 0x10800000, 0x42000000, 0x108000000, 0x420000000, 0x1080000000, 0x4200000000, 0x10800000000, 0x42000000000, 0x108000000000, 0x420000000000, 0x80000000042, 0x200000000108}); constexpr StatTable47 QRT_TABLE_47({0, 0x1001040, 0x1001042, 0x1047043076, 0x1001046, 0x112471c241e, 0x104704307e, 0x4304e052168, 0x1001056, 0x10004000, 0x112471c243e, 0x172a09c949d6, 0x104704303e, 0x4002020, 0x4304e0521e8, 0x5400e220, 0x1001156, 0x172b08c85080, 0x10004200, 0x41200b0800, 0x112471c203e, 0x172f0cca50a0, 0x172a09c941d6, 0x7eb88a11c1d6, 0x104704203e, 0x1044042020, 0x4000020, 0x42001011156, 0x4304e0561e8, 0x172a28c95880, 0x54006220, 0x112931cc21e, 0x1011156, 0x53670f283e, 0x172b08ca5080, 0x7a80c414a03e, 0x10044200, 0x40000000000, 0x4120030800, 0x1928318801e, 0x112470c203e, 0x799283188000, 0x172f0cea50a0, 0x1eb88a91c1c8, 0x172a098941d6, 0x3ea8cc95e1f6, 0x7eb88a91c1d6}); typedef Field<uint64_t, 47, 33, StatTable47, DynTable47, &SQR_TABLE_47, &QRT_TABLE_47> Field47; #endif #ifdef ENABLE_FIELD_INT_48 // 48 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6> StatTable48; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable48; constexpr StatTable48 SQR_TABLE_48({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x2d, 0xb4, 0x2d0, 0xb40, 0x2d00, 0xb400, 0x2d000, 0xb4000, 0x2d0000, 0xb40000, 0x2d00000, 0xb400000, 0x2d000000, 0xb4000000, 0x2d0000000, 0xb40000000, 0x2d00000000, 0xb400000000, 0x2d000000000, 0xb4000000000, 0x2d0000000000, 0xb40000000000, 0xd0000000005a, 0x40000000011f}); constexpr StatTable48 QRT_TABLE_48({0xc00442c284f0, 0xc16b7fda410a, 0xc16b7fda4108, 0xada3b5c79fbe, 0xc16b7fda410c, 0x16f3c18d5b0, 0xada3b5c79fb6, 0x7090a381f64, 0xc16b7fda411c, 0xcafc15d179f8, 0x16f3c18d590, 0x6630880e534e, 0xada3b5c79ff6, 0xa13dd1f49826, 0x7090a381fe4, 0xb87560f6a74, 0xc16b7fda401c, 0xaaaaffff0012, 0xcafc15d17bf8, 0xaafd15f07bf6, 0x16f3c18d190, 0x60000020000e, 0x6630880e5b4e, 0xcb977fcb401c, 0xada3b5c78ff6, 0x6663420cad0, 0xa13dd1f4b826, 0xc0045fc2f41c, 0x7090a385fe4, 0x6762e24b834, 0xb87560fea74, 0xc6351fed241c, 0xc16b7fdb401c, 0x60065622ea7a, 0xaaaafffd0012, 0xdf9562bea74, 0xcafc15d57bf8, 0x6657ea057bea, 0xaafd15f87bf6, 0xa79329ddaa66, 0x16f3c08d190, 0xa39229f0aa66, 0x60000000000e, 0x175fb4468ad0, 0x6630884e5b4e, 0, 0xcb977f4b401c, 0x2630884e5b40}); typedef Field<uint64_t, 48, 45, StatTable48, DynTable48, &SQR_TABLE_48, &QRT_TABLE_48> Field48; #endif } Sketch* ConstructGeneric6Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_41 case 41: return new SketchImpl<Field41>(implementation, 41); #endif #ifdef ENABLE_FIELD_INT_42 case 42: return new SketchImpl<Field42>(implementation, 42); #endif #ifdef ENABLE_FIELD_INT_43 case 43: return new SketchImpl<Field43>(implementation, 43); #endif #ifdef ENABLE_FIELD_INT_44 case 44: return new SketchImpl<Field44>(implementation, 44); #endif #ifdef ENABLE_FIELD_INT_45 case 45: return new SketchImpl<Field45>(implementation, 45); #endif #ifdef ENABLE_FIELD_INT_46 case 46: return new SketchImpl<Field46>(implementation, 46); #endif #ifdef ENABLE_FIELD_INT_47 case 47: return new SketchImpl<Field47>(implementation, 47); #endif #ifdef ENABLE_FIELD_INT_48 case 48: return new SketchImpl<Field48>(implementation, 48); #endif default: return nullptr; } }
0
bitcoin/src/minisketch/src
bitcoin/src/minisketch/src/fields/generic_7bytes.cpp
/********************************************************************** * Copyright (c) 2018 Pieter Wuille, Greg Maxwell, Gleb Naumenko * * Distributed under the MIT software license, see the accompanying * * file LICENSE or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ /* This file was substantially auto-generated by doc/gen_params.sage. */ #include "../fielddefines.h" #if defined(ENABLE_FIELD_BYTES_INT_7) #include "generic_common_impl.h" #include "../lintrans.h" #include "../sketch_impl.h" #endif #include "../sketch.h" namespace { #ifdef ENABLE_FIELD_INT_49 // 49 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 5, 5, 5, 5, 5> StatTable49; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable49; constexpr StatTable49 SQR_TABLE_49({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x402, 0x1008, 0x4020, 0x10080, 0x40200, 0x100800, 0x402000, 0x1008000, 0x4020000, 0x10080000, 0x40200000, 0x100800000, 0x402000000, 0x1008000000, 0x4020000000, 0x10080000000, 0x40200000000, 0x100800000000, 0x402000000000, 0x1008000000000, 0x20000000402, 0x80000001008, 0x200000004020, 0x800000010080}); constexpr StatTable49 QRT_TABLE_49({0, 0x10004196, 0x10004194, 0x5099461f080, 0x10004190, 0x40840600c20, 0x5099461f088, 0x58a56349cfde, 0x10004180, 0x48641a0c03fe, 0x40840600c00, 0x10084002848, 0x5099461f0c8, 0x4002048, 0x58a56349cf5e, 0x5088460a048, 0x10004080, 0x4c2852624dde, 0x48641a0c01fe, 0x14893129c280, 0x40840600800, 0x1eb23c323ace8, 0x10084002048, 0x48740a09417e, 0x5099461e0c8, 0x40852604d96, 0x4000048, 0x5cad2b29c37e, 0x58a563498f5e, 0x20000200, 0x50884602048, 0x10000000000, 0x10014080, 0x4c2a56624d96, 0x4c2852604dde, 0x1ee2347438ca0, 0x48641a0801fe, 0x480000000048, 0x14893121c280, 0x14091121c080, 0x40840700800, 0x1a5099561e17e, 0x1eb23c303ace8, 0x8740a894136, 0x10084402048, 0x18101c501ace8, 0x48740a89417e, 0x15dace6286f96, 0x5099561e0c8}); typedef Field<uint64_t, 49, 513, StatTable49, DynTable49, &SQR_TABLE_49, &QRT_TABLE_49> Field49; #endif #ifdef ENABLE_FIELD_INT_50 // 50 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5, 5> StatTable50; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable50; constexpr StatTable50 SQR_TABLE_50({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x1d, 0x74, 0x1d0, 0x740, 0x1d00, 0x7400, 0x1d000, 0x74000, 0x1d0000, 0x740000, 0x1d00000, 0x7400000, 0x1d000000, 0x74000000, 0x1d0000000, 0x740000000, 0x1d00000000, 0x7400000000, 0x1d000000000, 0x74000000000, 0x1d0000000000, 0x740000000000, 0x1d00000000000, 0x340000000001d, 0x1000000000053}); constexpr StatTable50 QRT_TABLE_50({0xfbdfa3ae9d4c, 0x38143245a4878, 0x38143245a487a, 0x38527487e7492, 0x38143245a487e, 0x3124c61f56d2a, 0x38527487e749a, 0xfa8c91b087c0, 0x38143245a486e, 0x3eca48c6196be, 0x3124c61f56d0a, 0x380000040080a, 0x38527487e74da, 0x976b2d8b39b4, 0xfa8c91b08740, 0xfa8cd5b02724, 0x38143245a496e, 0x316291dd013fe, 0x3eca48c6194be, 0x10344122064, 0x3124c61f5690a, 0x68c5f006ee40, 0x380000040000a, 0x852749fe64d0, 0x38527487e64da, 0x37ef8e9d0e9da, 0x976b2d8b19b4, 0x37fabd1cef34a, 0xfa8c91b0c740, 0x96282d9159b4, 0xfa8cd5b0a724, 0x464a8249dd0, 0x38143245b496e, 0x37eaa8ddc94be, 0x316291dd213fe, 0x392446035690a, 0x3eca48c6594be, 0x974b258b4964, 0x103441a2064, 0x385a7c87fb4da, 0x3124c61e5690a, 0xeb8ad5d9a724, 0x68c5f026ee40, 0x3724c61e5690a, 0x380000000000a, 0x3a8c5f026ee4a, 0x8527497e64d0, 0, 0x38527497e64da, 0x2fbdfa2ae8d0a}); typedef Field<uint64_t, 50, 29, StatTable50, DynTable50, &SQR_TABLE_50, &QRT_TABLE_50> Field50; #endif #ifdef ENABLE_FIELD_INT_51 // 51 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5, 5> StatTable51; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable51; constexpr StatTable51 SQR_TABLE_51({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x96, 0x258, 0x960, 0x2580, 0x9600, 0x25800, 0x96000, 0x258000, 0x960000, 0x2580000, 0x9600000, 0x25800000, 0x96000000, 0x258000000, 0x960000000, 0x2580000000, 0x9600000000, 0x25800000000, 0x96000000000, 0x258000000000, 0x960000000000, 0x2580000000000, 0x160000000004b, 0x580000000012c, 0x6000000000426}); constexpr StatTable51 QRT_TABLE_51({0x778bf2703d152, 0x2aaaafbff2092, 0x2aaaafbff2090, 0x4d2119c7e7780, 0x2aaaafbff2094, 0x65de1df8ae194, 0x4d2119c7e7788, 0x67d63d7ba262c, 0x2aaaafbff2084, 0x28ff003f4167c, 0x65de1df8ae1b4, 0x658397fb1d034, 0x4d2119c7e77c8, 0x4d7c9284526ba, 0x67d63d7ba26ac, 0x6666333fc0cbe, 0x2aaaafbff2184, 0x295b807ab55ee, 0x28ff003f4147c, 0x2aaabfffe0016, 0x65de1df8ae5b4, 0x209210349d60, 0x658397fb1d834, 0x4d215dc7cf1c8, 0x4d2119c7e67c8, 0x662b2b3d7b4be, 0x4d7c9284506ba, 0x255af00b36e0, 0x67d63d7ba66ac, 0x65de1fb8ac1a6, 0x6666333fc8cbe, 0x662f3b3ded4be, 0x2aaaafbfe2184, 0x663a9dbc3a426, 0x295b807a955ee, 0x4cdc9ec128928, 0x28ff003f0147c, 0x28a0c93cd511c, 0x2aaabfff60016, 0x65d73cf8e78d4, 0x65de1df9ae5b4, 0x4d5eddc44f1c8, 0x209210149d60, 0x357fcc506c8a, 0x658397ff1d834, 0, 0x4d215dcfcf1c8, 0x63f536f5d4554, 0x4d2119d7e67c8, 0x4000000000022, 0x662b2b1d7b4be}); typedef Field<uint64_t, 51, 75, StatTable51, DynTable51, &SQR_TABLE_51, &QRT_TABLE_51> Field51; #endif #ifdef ENABLE_FIELD_INT_52 // 52 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 5, 5> StatTable52; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable52; constexpr StatTable52 SQR_TABLE_52({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x9, 0x24, 0x90, 0x240, 0x900, 0x2400, 0x9000, 0x24000, 0x90000, 0x240000, 0x900000, 0x2400000, 0x9000000, 0x24000000, 0x90000000, 0x240000000, 0x900000000, 0x2400000000, 0x9000000000, 0x24000000000, 0x90000000000, 0x240000000000, 0x900000000000, 0x2400000000000, 0x9000000000000, 0x4000000000012}); constexpr StatTable52 QRT_TABLE_52({0xc108165459b0e, 0x10004086, 0x10004084, 0xc00000100104e, 0x10004080, 0x2041810a545b0, 0xc000001001046, 0x1181e055efc0, 0x10004090, 0x40810214390, 0x2041810a54590, 0xc000141019106, 0xc000001001006, 0x10816045ab40, 0x1181e055ef40, 0xc000111015196, 0x10004190, 0xe045c19af44a2, 0x40810214190, 0xe045809ad0532, 0x2041810a54190, 0xdb387a03fe646, 0xc000141019906, 0x2000000800000, 0xc000001000006, 0x2486548199c34, 0x108160458b40, 0x2041808a50534, 0x1181e055af40, 0xc0408312153d6, 0xc00011101d196, 0x21499f0e0eed0, 0x10014190, 0xe15dff9faabe2, 0xe045c19ad44a2, 0xdb787b01ea7d6, 0x40810254190, 0xe484409180532, 0xe045809a50532, 0xc14095164d896, 0x2041810b54190, 0x217dee8fb7a74, 0xdb387a01fe646, 0x441810b54190, 0xc000141419906, 0xc3386e15e7f46, 0x2000000000000, 0x1000141419900, 0xc000000000006, 0, 0x248654a199c34, 0xa48654a199c32}); typedef Field<uint64_t, 52, 9, StatTable52, DynTable52, &SQR_TABLE_52, &QRT_TABLE_52> Field52; #endif #ifdef ENABLE_FIELD_INT_53 // 53 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 5> StatTable53; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3> DynTable53; constexpr StatTable53 SQR_TABLE_53({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x8e, 0x238, 0x8e0, 0x2380, 0x8e00, 0x23800, 0x8e000, 0x238000, 0x8e0000, 0x2380000, 0x8e00000, 0x23800000, 0x8e000000, 0x238000000, 0x8e0000000, 0x2380000000, 0x8e00000000, 0x23800000000, 0x8e000000000, 0x238000000000, 0x8e0000000000, 0x2380000000000, 0x8e00000000000, 0x3800000000047, 0xe00000000011c, 0x18000000000437}); constexpr StatTable53 QRT_TABLE_53({0xf940b90844076, 0x1f940b90844052, 0x1f940b90844050, 0x9d2a063b43e64, 0x1f940b90844054, 0x936f69323ec14, 0x9d2a063b43e6c, 0xe12270a88898, 0x1f940b90844044, 0x1f917f00bb5a3c, 0x936f69323ec34, 0x1f622df85b46ee, 0x9d2a063b43e2c, 0x9bc65ab040b66, 0xe12270a88818, 0x958330b931986, 0x1f940b90844144, 0x98e2a06e32e0, 0x1f917f00bb583c, 0x1f877970dc1024, 0x936f69323e834, 0x16cc3c9b1558c2, 0x1f622df85b4eee, 0x16de1c3351dae8, 0x9d2a063b42e2c, 0x1fecdc7855f8ee, 0x9bc65ab042b66, 0x933821b1cb6fe, 0xe12270a8c818, 0x1f675958641c0e, 0x958330b939986, 0x9d97e050e960, 0x1f940b90854144, 0x1f820fa0e38adc, 0x98e2a06c32e0, 0x1650f0e358a010, 0x1f917f00bf583c, 0x1643af4b037a3a, 0x1f877970d41024, 0x1ffe2c281d8c16, 0x936f69333e834, 0xf00d50ffccf8, 0x16cc3c9b3558c2, 0x16bc31cbca943a, 0x1f622df81b4eee, 0xa6cbd8007232, 0x16de1c33d1dae8, 0x15d2a062b42e10, 0x9d2a062b42e2c, 0x1aa77896586ca, 0x1fecdc7a55f8ee, 0, 0x9bc65af042b66}); typedef Field<uint64_t, 53, 71, StatTable53, DynTable53, &SQR_TABLE_53, &QRT_TABLE_53> Field53; #endif #ifdef ENABLE_FIELD_INT_54 // 54 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 6, 6, 6> StatTable54; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3> DynTable54; constexpr StatTable54 SQR_TABLE_54({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x201, 0x804, 0x2010, 0x8040, 0x20100, 0x80400, 0x201000, 0x804000, 0x2010000, 0x8040000, 0x20100000, 0x80400000, 0x201000000, 0x804000000, 0x2010000000, 0x8040000000, 0x20100000000, 0x80400000000, 0x201000000000, 0x804000000000, 0x2010000000000, 0x8040000000000, 0x20100000000000, 0x400000000402, 0x1000000001008, 0x4000000004020, 0x10000000010080}); constexpr StatTable54 QRT_TABLE_54({0x201008000200, 0x26c10916494994, 0x26c10916494996, 0x40008008, 0x26c10916494992, 0x141a2434c12d12, 0x40008000, 0x36c00110594c22, 0x26c10916494982, 0x200000040200, 0x141a2434c12d32, 0x10010816104534, 0x40008040, 0x36da60b01308b2, 0x36c00110594ca2, 0x48200209000, 0x26c10916494882, 0x41b6da2d86106, 0x200000040000, 0x32db2c228965b0, 0x141a2434c12932, 0x9000000200048, 0x10010816104d34, 0x32db68b2832da4, 0x40009040, 0x40045928b4902, 0x36da60b01328b2, 0x1000040000, 0x36c00110590ca2, 0x101b69865a4120, 0x48200201000, 0x22da6434912884, 0x26c10916484882, 0x9000240208008, 0x41b6da2da6106, 0x22c14484c20180, 0x200000000000, 0x4016db29b6812, 0x32db2c228165b0, 0x9008200201048, 0x141a2434d12932, 0x32c36ca2c264b0, 0x9000000000048, 0x140a65b48a2c32, 0x10010816504d34, 0, 0x32db68b2032da4, 0x404490824814, 0x41009040, 0x14da60a4536126, 0x40045908b4902, 0x8000041009008, 0x36da60b41328b2, 0x6db68b2032c12}); typedef Field<uint64_t, 54, 513, StatTable54, DynTable54, &SQR_TABLE_54, &QRT_TABLE_54> Field54; #endif #ifdef ENABLE_FIELD_INT_55 // 55 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5> StatTable55; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3> DynTable55; constexpr StatTable55 SQR_TABLE_55({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x102, 0x408, 0x1020, 0x4080, 0x10200, 0x40800, 0x102000, 0x408000, 0x1020000, 0x4080000, 0x10200000, 0x40800000, 0x102000000, 0x408000000, 0x1020000000, 0x4080000000, 0x10200000000, 0x40800000000, 0x102000000000, 0x408000000000, 0x1020000000000, 0x4080000000000, 0x10200000000000, 0x40800000000000, 0x2000000000102, 0x8000000000408, 0x20000000001020}); constexpr StatTable55 QRT_TABLE_55({0, 0x121d57b6623fde, 0x121d57b6623fdc, 0x68908340d10e00, 0x121d57b6623fd8, 0x100300510e20, 0x68908340d10e08, 0x10004096, 0x121d57b6623fc8, 0x100010000, 0x100300510e00, 0x7ea8c890a088e8, 0x68908340d10e48, 0x68809540871648, 0x10004016, 0x68808000808068, 0x121d57b6623ec8, 0x68909240d41c48, 0x100010200, 0x6884c170ad0216, 0x100300510a00, 0x68848160a50200, 0x7ea8c890a080e8, 0x7eecbca04ab4b6, 0x68908340d11e48, 0x120c54b62234c8, 0x68809540873648, 0x69929240d61c48, 0x10000016, 0x68808060800000, 0x68808000800068, 0x80000080, 0x121d57b6633ec8, 0x7ea8cb90a18ae8, 0x68909240d61c48, 0x16284090200080, 0x100050200, 0x474302a345e, 0x6884c170a50216, 0x166cbca0cab4de, 0x100300410a00, 0x1000000000000, 0x68848160850200, 0x688cc1f0a50296, 0x7ea8c890e080e8, 0x7e8cc1f0a50280, 0x7eecbca0cab4b6, 0x68000000000068, 0x68908341d11e48, 0x7880954487365e, 0x120c54b42234c8, 0x9929248d61c20, 0x68809544873648, 0x41121208561c20, 0x69929248d61c48}); typedef Field<uint64_t, 55, 129, StatTable55, DynTable55, &SQR_TABLE_55, &QRT_TABLE_55> Field55; #endif #ifdef ENABLE_FIELD_INT_56 // 56 bit field typedef RecLinTrans<uint64_t, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5> StatTable56; typedef RecLinTrans<uint64_t, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4> DynTable56; constexpr StatTable56 SQR_TABLE_56({0x1, 0x4, 0x10, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0x10000, 0x40000, 0x100000, 0x400000, 0x1000000, 0x4000000, 0x10000000, 0x40000000, 0x100000000, 0x400000000, 0x1000000000, 0x4000000000, 0x10000000000, 0x40000000000, 0x100000000000, 0x400000000000, 0x1000000000000, 0x4000000000000, 0x10000000000000, 0x40000000000000, 0x95, 0x254, 0x950, 0x2540, 0x9500, 0x25400, 0x95000, 0x254000, 0x950000, 0x2540000, 0x9500000, 0x25400000, 0x95000000, 0x254000000, 0x950000000, 0x2540000000, 0x9500000000, 0x25400000000, 0x95000000000, 0x254000000000, 0x950000000000, 0x2540000000000, 0x9500000000000, 0x25400000000000, 0x95000000000000, 0x5400000000012a, 0x5000000000043d, 0x40000000001061}); constexpr StatTable56 QRT_TABLE_56({0x10004084, 0xd058f12fd5925e, 0xd058f12fd5925c, 0x41a60b5566d9f0, 0xd058f12fd59258, 0xbda60a142740ba, 0x41a60b5566d9f8, 0xd059f1afc5e688, 0xd058f12fd59248, 0xfc040841615a22, 0xbda60a1427409a, 0xbda60b5426c1ca, 0x41a60b5566d9b8, 0x1a60b4166b950, 0xd059f1afc5e608, 0xfc000041409822, 0xd058f12fd59348, 0xd1ee7a4ef4185c, 0xfc040841615822, 0x9049759b80b4a4, 0xbda60a1427449a, 0xd258e06f301e18, 0xbda60b5426c9ca, 0x6dfeeb3bf6d7d2, 0x41a60b5566c9b8, 0xbdef3ed4ae398a, 0x1a60b41669950, 0xd1ef3f8eeff04c, 0xd059f1afc5a608, 0xbda203340783de, 0xfc000041401822, 0x2dfefbaff2b27a, 0xd058f12fd49348, 0xfdb788a0706776, 0xd1ee7a4ef6185c, 0x2e5de0ae41337a, 0xfc040841655822, 0x41eb17d5ceecf8, 0x9049759b88b4a4, 0x40048874211afc, 0xbda60a1437449a, 0xd04a720f93400c, 0xd258e06f101e18, 0xbc559cf5ac7fce, 0xbda60b5466c9ca, 0x6dc9759b88b4d6, 0x6dfeeb3b76d7d2, 0x92feea7b275af0, 0x41a60b5466c9b8, 0, 0xbdef3ed6ae398a, 0x2811d5edd8ee2a, 0x1a60b45669950, 0xb1a60b5466c9ca, 0xd1ef3f86eff04c, 0xec493582c8f032}); typedef Field<uint64_t, 56, 149, StatTable56, DynTable56, &SQR_TABLE_56, &QRT_TABLE_56> Field56; #endif } Sketch* ConstructGeneric7Bytes(int bits, int implementation) { switch (bits) { #ifdef ENABLE_FIELD_INT_49 case 49: return new SketchImpl<Field49>(implementation, 49); #endif #ifdef ENABLE_FIELD_INT_50 case 50: return new SketchImpl<Field50>(implementation, 50); #endif #ifdef ENABLE_FIELD_INT_51 case 51: return new SketchImpl<Field51>(implementation, 51); #endif #ifdef ENABLE_FIELD_INT_52 case 52: return new SketchImpl<Field52>(implementation, 52); #endif #ifdef ENABLE_FIELD_INT_53 case 53: return new SketchImpl<Field53>(implementation, 53); #endif #ifdef ENABLE_FIELD_INT_54 case 54: return new SketchImpl<Field54>(implementation, 54); #endif #ifdef ENABLE_FIELD_INT_55 case 55: return new SketchImpl<Field55>(implementation, 55); #endif #ifdef ENABLE_FIELD_INT_56 case 56: return new SketchImpl<Field56>(implementation, 56); #endif default: return nullptr; } }
0