repo_id
stringlengths
0
42
file_path
stringlengths
15
97
content
stringlengths
2
2.41M
__index_level_0__
int64
0
0
bitcoin/src
bitcoin/src/util/rbf.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_UTIL_RBF_H #define BITCOIN_UTIL_RBF_H #include <cstdint> class CTransaction; static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE{0xfffffffd}; /** Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee, * according to BIP 125. Allow opt-out of transaction replacement by setting nSequence > * MAX_BIP125_RBF_SEQUENCE (SEQUENCE_FINAL-2) on all inputs. * * SEQUENCE_FINAL-1 is picked to still allow use of nLockTime by non-replaceable transactions. All * inputs rather than just one is for the sake of multi-party protocols, where we don't want a single * party to be able to disable replacement by opting out in their own input. */ bool SignalsOptInRBF(const CTransaction& tx); #endif // BITCOIN_UTIL_RBF_H
0
bitcoin/src
bitcoin/src/util/readwritefile.h
// Copyright (c) 2015-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_UTIL_READWRITEFILE_H #define BITCOIN_UTIL_READWRITEFILE_H #include <util/fs.h> #include <limits> #include <string> #include <utility> /** Read full contents of a file and return them in a std::string. * Returns a pair <status, string>. * If an error occurred, status will be false, otherwise status will be true and the data will be returned in string. * * @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data * (with len > maxsize) will be returned. */ std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max()); /** Write contents of std::string to a file. * @return true on success. */ bool WriteBinaryFile(const fs::path &filename, const std::string &data); #endif // BITCOIN_UTIL_READWRITEFILE_H
0
bitcoin/src
bitcoin/src/util/fees.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-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_UTIL_FEES_H #define BITCOIN_UTIL_FEES_H #include <string> enum class FeeEstimateMode; enum class FeeReason; bool FeeModeFromString(const std::string& mode_string, FeeEstimateMode& fee_estimate_mode); std::string StringForFeeReason(FeeReason reason); std::string FeeModes(const std::string& delimiter); std::string InvalidEstimateModeErrorMessage(); #endif // BITCOIN_UTIL_FEES_H
0
bitcoin/src
bitcoin/src/util/message.cpp
// Copyright (c) 2009-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 <hash.h> #include <key.h> #include <key_io.h> #include <pubkey.h> #include <uint256.h> #include <util/message.h> #include <util/strencodings.h> #include <cassert> #include <optional> #include <string> #include <variant> #include <vector> /** * Text used to signify that a signed message follows and to prevent * inadvertently signing a transaction. */ const std::string MESSAGE_MAGIC = "Bitcoin Signed Message:\n"; MessageVerificationResult MessageVerify( const std::string& address, const std::string& signature, const std::string& message) { CTxDestination destination = DecodeDestination(address); if (!IsValidDestination(destination)) { return MessageVerificationResult::ERR_INVALID_ADDRESS; } if (std::get_if<PKHash>(&destination) == nullptr) { return MessageVerificationResult::ERR_ADDRESS_NO_KEY; } auto signature_bytes = DecodeBase64(signature); if (!signature_bytes) { return MessageVerificationResult::ERR_MALFORMED_SIGNATURE; } CPubKey pubkey; if (!pubkey.RecoverCompact(MessageHash(message), *signature_bytes)) { return MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED; } if (!(PKHash(pubkey) == *std::get_if<PKHash>(&destination))) { return MessageVerificationResult::ERR_NOT_SIGNED; } return MessageVerificationResult::OK; } bool MessageSign( const CKey& privkey, const std::string& message, std::string& signature) { std::vector<unsigned char> signature_bytes; if (!privkey.SignCompact(MessageHash(message), signature_bytes)) { return false; } signature = EncodeBase64(signature_bytes); return true; } uint256 MessageHash(const std::string& message) { HashWriter hasher{}; hasher << MESSAGE_MAGIC << message; return hasher.GetHash(); } std::string SigningResultString(const SigningResult res) { switch (res) { case SigningResult::OK: return "No error"; case SigningResult::PRIVATE_KEY_NOT_AVAILABLE: return "Private key not available"; case SigningResult::SIGNING_FAILED: return "Sign failed"; // no default case, so the compiler can warn about missing cases } assert(false); }
0
bitcoin/src
bitcoin/src/util/golombrice.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_UTIL_GOLOMBRICE_H #define BITCOIN_UTIL_GOLOMBRICE_H #include <util/fastrange.h> #include <streams.h> #include <cstdint> template <typename OStream> void GolombRiceEncode(BitStreamWriter<OStream>& bitwriter, uint8_t P, uint64_t x) { // Write quotient as unary-encoded: q 1's followed by one 0. uint64_t q = x >> P; while (q > 0) { int nbits = q <= 64 ? static_cast<int>(q) : 64; bitwriter.Write(~0ULL, nbits); q -= nbits; } bitwriter.Write(0, 1); // Write the remainder in P bits. Since the remainder is just the bottom // P bits of x, there is no need to mask first. bitwriter.Write(x, P); } template <typename IStream> uint64_t GolombRiceDecode(BitStreamReader<IStream>& bitreader, uint8_t P) { // Read unary-encoded quotient: q 1's followed by one 0. uint64_t q = 0; while (bitreader.Read(1) == 1) { ++q; } uint64_t r = bitreader.Read(P); return (q << P) + r; } #endif // BITCOIN_UTIL_GOLOMBRICE_H
0
bitcoin/src
bitcoin/src/util/exception.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2023 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 <util/exception.h> #include <logging.h> #include <tinyformat.h> #include <exception> #include <iostream> #include <string> #include <typeinfo> #ifdef WIN32 #include <windows.h> #endif // WIN32 static std::string FormatException(const std::exception* pex, std::string_view thread_name) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(nullptr, pszModule, sizeof(pszModule)); #else const char* pszModule = "bitcoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, thread_name); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, thread_name); } void PrintExceptionContinue(const std::exception* pex, std::string_view thread_name) { std::string message = FormatException(pex, thread_name); LogPrintf("\n\n************************\n%s\n", message); tfm::format(std::cerr, "\n\n************************\n%s\n", message); }
0
bitcoin/src
bitcoin/src/util/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_UTIL_TYPES_H #define BITCOIN_UTIL_TYPES_H template <class> inline constexpr bool ALWAYS_FALSE{false}; #endif // BITCOIN_UTIL_TYPES_H
0
bitcoin/src
bitcoin/src/util/batchpriority.cpp
// Copyright (c) 2023 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 <logging.h> #include <util/syserror.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 #include <sched.h> #endif void ScheduleBatchPriority() { #ifdef SCHED_BATCH const static sched_param param{}; const int rc = pthread_setschedparam(pthread_self(), SCHED_BATCH, &param); if (rc != 0) { LogPrintf("Failed to pthread_setschedparam: %s\n", SysErrorString(rc)); } #endif }
0
bitcoin/src
bitcoin/src/util/bytevectorhash.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_UTIL_BYTEVECTORHASH_H #define BITCOIN_UTIL_BYTEVECTORHASH_H #include <cstdint> #include <cstddef> #include <vector> /** * Implementation of Hash named requirement for types that internally store a byte array. This may * be used as the hash function in std::unordered_set or std::unordered_map over such types. * Internally, this uses a random instance of SipHash-2-4. */ class ByteVectorHash final { private: uint64_t m_k0, m_k1; public: ByteVectorHash(); size_t operator()(const std::vector<unsigned char>& input) const; }; #endif // BITCOIN_UTIL_BYTEVECTORHASH_H
0
bitcoin/src
bitcoin/src/util/error.cpp
// Copyright (c) 2010-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 <util/error.h> #include <tinyformat.h> #include <util/translation.h> #include <cassert> #include <string> bilingual_str TransactionErrorString(const TransactionError err) { switch (err) { case TransactionError::OK: return Untranslated("No error"); case TransactionError::MISSING_INPUTS: return Untranslated("Inputs missing or spent"); case TransactionError::ALREADY_IN_CHAIN: return Untranslated("Transaction already in block chain"); case TransactionError::P2P_DISABLED: return Untranslated("Peer-to-peer functionality missing or disabled"); case TransactionError::MEMPOOL_REJECTED: return Untranslated("Transaction rejected by mempool"); case TransactionError::MEMPOOL_ERROR: return Untranslated("Mempool internal error"); case TransactionError::INVALID_PSBT: return Untranslated("PSBT is not well-formed"); case TransactionError::PSBT_MISMATCH: return Untranslated("PSBTs not compatible (different transactions)"); case TransactionError::SIGHASH_MISMATCH: return Untranslated("Specified sighash value does not match value stored in PSBT"); case TransactionError::MAX_FEE_EXCEEDED: return Untranslated("Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)"); case TransactionError::MAX_BURN_EXCEEDED: return Untranslated("Unspendable output exceeds maximum configured by user (maxburnamount)"); case TransactionError::EXTERNAL_SIGNER_NOT_FOUND: return Untranslated("External signer not found"); case TransactionError::EXTERNAL_SIGNER_FAILED: return Untranslated("External signer failed to sign"); case TransactionError::INVALID_PACKAGE: return Untranslated("Transaction rejected due to invalid package"); // no default case, so the compiler can warn about missing cases } assert(false); } bilingual_str ResolveErrMsg(const std::string& optname, const std::string& strBind) { return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind); } bilingual_str InvalidPortErrMsg(const std::string& optname, const std::string& invalid_value) { return strprintf(_("Invalid port specified in %s: '%s'"), optname, invalid_value); } bilingual_str AmountHighWarn(const std::string& optname) { return strprintf(_("%s is set very high!"), optname); } bilingual_str AmountErrMsg(const std::string& optname, const std::string& strValue) { return strprintf(_("Invalid amount for -%s=<amount>: '%s'"), optname, strValue); }
0
bitcoin/src
bitcoin/src/util/hash_type.h
// 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. #ifndef BITCOIN_UTIL_HASH_TYPE_H #define BITCOIN_UTIL_HASH_TYPE_H template <typename HashType> class BaseHash { protected: HashType m_hash; public: BaseHash() : m_hash() {} explicit BaseHash(const HashType& in) : m_hash(in) {} unsigned char* begin() { return m_hash.begin(); } const unsigned char* begin() const { return m_hash.begin(); } unsigned char* end() { return m_hash.end(); } const unsigned char* end() const { return m_hash.end(); } operator std::vector<unsigned char>() const { return std::vector<unsigned char>{m_hash.begin(), m_hash.end()}; } std::string ToString() const { return m_hash.ToString(); } bool operator==(const BaseHash<HashType>& other) const noexcept { return m_hash == other.m_hash; } bool operator!=(const BaseHash<HashType>& other) const noexcept { return !(m_hash == other.m_hash); } bool operator<(const BaseHash<HashType>& other) const noexcept { return m_hash < other.m_hash; } size_t size() const { return m_hash.size(); } unsigned char* data() { return m_hash.data(); } const unsigned char* data() const { return m_hash.data(); } }; #endif // BITCOIN_UTIL_HASH_TYPE_H
0
bitcoin/src
bitcoin/src/util/overloaded.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_UTIL_OVERLOADED_H #define BITCOIN_UTIL_OVERLOADED_H namespace util { //! Overloaded helper for std::visit. This helper and std::visit in general are //! useful to write code that switches on a variant type. Unlike if/else-if and //! switch/case statements, std::visit will trigger compile errors if there are //! unhandled cases. //! //! Implementation comes from and example usage can be found at //! https://en.cppreference.com/w/cpp/utility/variant/visit#Example template<class... Ts> struct Overloaded : Ts... { using Ts::operator()...; }; //! Explicit deduction guide (not needed as of C++20) template<class... Ts> Overloaded(Ts...) -> Overloaded<Ts...>; } // namespace util #endif // BITCOIN_UTIL_OVERLOADED_H
0
bitcoin/src
bitcoin/src/util/rbf.cpp
// Copyright (c) 2016-2019 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 <util/rbf.h> #include <primitives/transaction.h> bool SignalsOptInRBF(const CTransaction &tx) { for (const CTxIn &txin : tx.vin) { if (txin.nSequence <= MAX_BIP125_RBF_SEQUENCE) { return true; } } return false; }
0
bitcoin/src
bitcoin/src/util/bip32.h
// 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. #ifndef BITCOIN_UTIL_BIP32_H #define BITCOIN_UTIL_BIP32_H #include <cstdint> #include <string> #include <vector> /** Parse an HD keypaths like "m/7/0'/2000". */ [[nodiscard]] bool ParseHDKeypath(const std::string& keypath_str, std::vector<uint32_t>& keypath); /** Write HD keypaths as strings */ std::string WriteHDKeypath(const std::vector<uint32_t>& keypath, bool apostrophe = false); std::string FormatHDKeypath(const std::vector<uint32_t>& path, bool apostrophe = false); #endif // BITCOIN_UTIL_BIP32_H
0
bitcoin/src
bitcoin/src/util/result.h
// 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. #ifndef BITCOIN_UTIL_RESULT_H #define BITCOIN_UTIL_RESULT_H #include <attributes.h> #include <util/translation.h> #include <variant> namespace util { struct Error { bilingual_str message; }; //! The util::Result class provides a standard way for functions to return //! either error messages or result values. //! //! It is intended for high-level functions that need to report error strings to //! end users. Lower-level functions that don't need this error-reporting and //! only need error-handling should avoid util::Result and instead use standard //! classes like std::optional, std::variant, and std::tuple, or custom structs //! and enum types to return function results. //! //! Usage examples can be found in \example ../test/result_tests.cpp, but in //! general code returning `util::Result<T>` values is very similar to code //! returning `std::optional<T>` values. Existing functions returning //! `std::optional<T>` can be updated to return `util::Result<T>` and return //! error strings usually just replacing `return std::nullopt;` with `return //! util::Error{error_string};`. template <class M> class Result { private: using T = std::conditional_t<std::is_same_v<M, void>, std::monostate, M>; std::variant<bilingual_str, T> m_variant; template <typename FT> friend bilingual_str ErrorString(const Result<FT>& result); public: Result() : m_variant{std::in_place_index_t<1>{}, std::monostate{}} {} // constructor for void Result(T obj) : m_variant{std::in_place_index_t<1>{}, std::move(obj)} {} Result(Error error) : m_variant{std::in_place_index_t<0>{}, std::move(error.message)} {} //! std::optional methods, so functions returning optional<T> can change to //! return Result<T> with minimal changes to existing code, and vice versa. bool has_value() const noexcept { return m_variant.index() == 1; } const T& value() const LIFETIMEBOUND { assert(has_value()); return std::get<1>(m_variant); } T& value() LIFETIMEBOUND { assert(has_value()); return std::get<1>(m_variant); } template <class U> T value_or(U&& default_value) const& { return has_value() ? value() : std::forward<U>(default_value); } template <class U> T value_or(U&& default_value) && { return has_value() ? std::move(value()) : std::forward<U>(default_value); } explicit operator bool() const noexcept { return has_value(); } const T* operator->() const LIFETIMEBOUND { return &value(); } const T& operator*() const LIFETIMEBOUND { return value(); } T* operator->() LIFETIMEBOUND { return &value(); } T& operator*() LIFETIMEBOUND { return value(); } }; template <typename T> bilingual_str ErrorString(const Result<T>& result) { return result ? bilingual_str{} : std::get<0>(result.m_variant); } } // namespace util #endif // BITCOIN_UTIL_RESULT_H
0
bitcoin/src
bitcoin/src/util/threadinterrupt.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_UTIL_THREADINTERRUPT_H #define BITCOIN_UTIL_THREADINTERRUPT_H #include <sync.h> #include <threadsafety.h> #include <atomic> #include <chrono> #include <condition_variable> /** * A helper class for interruptible sleeps. Calling operator() will interrupt * any current sleep, and after that point operator bool() will return true * until reset. * * This class should not be used in a signal handler. It uses thread * synchronization primitives that are not safe to use with signals. If sending * an interrupt from a signal handler is necessary, the \ref SignalInterrupt * class can be used instead. */ class CThreadInterrupt { public: using Clock = std::chrono::steady_clock; CThreadInterrupt(); explicit operator bool() const; void operator()() EXCLUSIVE_LOCKS_REQUIRED(!mut); void reset(); bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut); private: std::condition_variable cond; Mutex mut; std::atomic<bool> flag; }; #endif // BITCOIN_UTIL_THREADINTERRUPT_H
0
bitcoin/src
bitcoin/src/util/syserror.h
// Copyright (c) 2010-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_UTIL_SYSERROR_H #define BITCOIN_UTIL_SYSERROR_H #include <string> /** Return system error string from errno value. Use this instead of * std::strerror, which is not thread-safe. For network errors use * NetworkErrorString from sock.h instead. */ std::string SysErrorString(int err); #if defined(WIN32) std::string Win32ErrorString(int err); #endif #endif // BITCOIN_UTIL_SYSERROR_H
0
bitcoin/src
bitcoin/src/util/message.h
// Copyright (c) 2009-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. #ifndef BITCOIN_UTIL_MESSAGE_H #define BITCOIN_UTIL_MESSAGE_H #include <uint256.h> #include <string> class CKey; extern const std::string MESSAGE_MAGIC; /** The result of a signed message verification. * Message verification takes as an input: * - address (with whose private key the message is supposed to have been signed) * - signature * - message */ enum class MessageVerificationResult { //! The provided address is invalid. ERR_INVALID_ADDRESS, //! The provided address is valid but does not refer to a public key. ERR_ADDRESS_NO_KEY, //! The provided signature couldn't be parsed (maybe invalid base64). ERR_MALFORMED_SIGNATURE, //! A public key could not be recovered from the provided signature and message. ERR_PUBKEY_NOT_RECOVERED, //! The message was not signed with the private key of the provided address. ERR_NOT_SIGNED, //! The message verification was successful. OK }; enum class SigningResult { OK, //!< No error PRIVATE_KEY_NOT_AVAILABLE, SIGNING_FAILED, }; /** Verify a signed message. * @param[in] address Signer's bitcoin address, it must refer to a public key. * @param[in] signature The signature in base64 format. * @param[in] message The message that was signed. * @return result code */ MessageVerificationResult MessageVerify( const std::string& address, const std::string& signature, const std::string& message); /** Sign a message. * @param[in] privkey Private key to sign with. * @param[in] message The message to sign. * @param[out] signature Signature, base64 encoded, only set if true is returned. * @return true if signing was successful. */ bool MessageSign( const CKey& privkey, const std::string& message, std::string& signature); /** * Hashes a message for signing and verification in a manner that prevents * inadvertently signing a transaction. */ uint256 MessageHash(const std::string& message); std::string SigningResultString(const SigningResult res); #endif // BITCOIN_UTIL_MESSAGE_H
0
bitcoin/src
bitcoin/src/util/translation.h
// 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. #ifndef BITCOIN_UTIL_TRANSLATION_H #define BITCOIN_UTIL_TRANSLATION_H #include <tinyformat.h> #include <functional> #include <string> /** * Bilingual messages: * - in GUI: user's native language + untranslated (i.e. English) * - in log and stderr: untranslated only */ struct bilingual_str { std::string original; std::string translated; bilingual_str& operator+=(const bilingual_str& rhs) { original += rhs.original; translated += rhs.translated; return *this; } bool empty() const { return original.empty(); } void clear() { original.clear(); translated.clear(); } }; inline bilingual_str operator+(bilingual_str lhs, const bilingual_str& rhs) { lhs += rhs; return lhs; } /** Mark a bilingual_str as untranslated */ inline bilingual_str Untranslated(std::string original) { return {original, original}; } // Provide an overload of tinyformat::format which can take bilingual_str arguments. namespace tinyformat { template <typename... Args> bilingual_str format(const bilingual_str& fmt, const Args&... args) { const auto translate_arg{[](const auto& arg, bool translated) -> const auto& { if constexpr (std::is_same_v<decltype(arg), const bilingual_str&>) { return translated ? arg.translated : arg.original; } else { return arg; } }}; return bilingual_str{tfm::format(fmt.original, translate_arg(args, false)...), tfm::format(fmt.translated, translate_arg(args, true)...)}; } } // namespace tinyformat /** Translate a message to the native language of the user. */ const extern std::function<std::string(const char*)> G_TRANSLATION_FUN; /** * Translation function. * If no translation function is set, simply return the input. */ inline bilingual_str _(const char* psz) { return bilingual_str{psz, G_TRANSLATION_FUN ? (G_TRANSLATION_FUN)(psz) : psz}; } #endif // BITCOIN_UTIL_TRANSLATION_H
0
bitcoin/src
bitcoin/src/util/string.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 <util/string.h> #include <regex> #include <string> void ReplaceAll(std::string& in_out, const std::string& search, const std::string& substitute) { if (search.empty()) return; in_out = std::regex_replace(in_out, std::regex(search), substitute); }
0
bitcoin/src
bitcoin/src/util/moneystr.h
// Copyright (c) 2009-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. /** * Money parsing/formatting utilities. */ #ifndef BITCOIN_UTIL_MONEYSTR_H #define BITCOIN_UTIL_MONEYSTR_H #include <consensus/amount.h> #include <optional> #include <string> /* Do not use these functions to represent or parse monetary amounts to or from * JSON but use AmountFromValue and ValueFromAmount for that. */ std::string FormatMoney(const CAmount n); /** Parse an amount denoted in full coins. E.g. "0.0034" supplied on the command line. **/ std::optional<CAmount> ParseMoney(const std::string& str); #endif // BITCOIN_UTIL_MONEYSTR_H
0
bitcoin/src
bitcoin/src/util/batchpriority.h
// Copyright (c) 2023 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_UTIL_BATCHPRIORITY_H #define BITCOIN_UTIL_BATCHPRIORITY_H /** * On platforms that support it, tell the kernel the calling thread is * CPU-intensive and non-interactive. See SCHED_BATCH in sched(7) for details. * */ void ScheduleBatchPriority(); #endif // BITCOIN_UTIL_BATCHPRIORITY_H
0
bitcoin/src
bitcoin/src/util/hasher.h
// 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. #ifndef BITCOIN_UTIL_HASHER_H #define BITCOIN_UTIL_HASHER_H #include <crypto/common.h> #include <crypto/siphash.h> #include <primitives/transaction.h> #include <uint256.h> #include <cstdint> #include <cstring> template <typename C> class Span; class SaltedTxidHasher { private: /** Salt */ const uint64_t k0, k1; public: SaltedTxidHasher(); size_t operator()(const uint256& txid) const { return SipHashUint256(k0, k1, txid); } }; class SaltedOutpointHasher { private: /** Salt */ const uint64_t k0, k1; public: SaltedOutpointHasher(bool deterministic = false); /** * Having the hash noexcept allows libstdc++'s unordered_map to recalculate * the hash during rehash, so it does not have to cache the value. This * reduces node's memory by sizeof(size_t). The required recalculation has * a slight performance penalty (around 1.6%), but this is compensated by * memory savings of about 9% which allow for a larger dbcache setting. * * @see https://gcc.gnu.org/onlinedocs/gcc-13.2.0/libstdc++/manual/manual/unordered_associative.html */ size_t operator()(const COutPoint& id) const noexcept { return SipHashUint256Extra(k0, k1, id.hash, id.n); } }; struct FilterHeaderHasher { size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); } }; /** * We're hashing a nonce into the entries themselves, so we don't need extra * blinding in the set hash computation. * * This may exhibit platform endian dependent behavior but because these are * nonced hashes (random) and this state is only ever used locally it is safe. * All that matters is local consistency. */ class SignatureCacheHasher { public: template <uint8_t hash_select> uint32_t operator()(const uint256& key) const { static_assert(hash_select <8, "SignatureCacheHasher only has 8 hashes available."); uint32_t u; std::memcpy(&u, key.begin()+4*hash_select, 4); return u; } }; struct BlockHasher { // this used to call `GetCheapHash()` in uint256, which was later moved; the // cheap hash function simply calls ReadLE64() however, so the end result is // identical size_t operator()(const uint256& hash) const { return ReadLE64(hash.begin()); } }; class SaltedSipHasher { private: /** Salt */ const uint64_t m_k0, m_k1; public: SaltedSipHasher(); size_t operator()(const Span<const unsigned char>& script) const; }; #endif // BITCOIN_UTIL_HASHER_H
0
bitcoin/src
bitcoin/src/util/threadnames.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. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <string> #include <thread> #include <utility> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #include <util/threadnames.h> #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif //! Set the thread's name at the process level. Does not affect the //! internal name. static void SetThreadName(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) pthread_setname_np(name); #else // Prevent warnings for unused parameters... (void)name; #endif } // If we have thread_local, just keep thread ID and name in a thread_local // global. #if defined(HAVE_THREAD_LOCAL) static thread_local std::string g_thread_name; const std::string& util::ThreadGetInternalName() { return g_thread_name; } //! Set the in-memory internal name for this thread. Does not affect the process //! name. static void SetInternalName(std::string name) { g_thread_name = std::move(name); } // Without thread_local available, don't handle internal name at all. #else static const std::string empty_string; const std::string& util::ThreadGetInternalName() { return empty_string; } static void SetInternalName(std::string name) { } #endif void util::ThreadRename(std::string&& name) { SetThreadName(("b-" + name).c_str()); SetInternalName(std::move(name)); } void util::ThreadSetInternalName(std::string&& name) { SetInternalName(std::move(name)); }
0
bitcoin/src
bitcoin/src/util/thread.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_UTIL_THREAD_H #define BITCOIN_UTIL_THREAD_H #include <functional> #include <string> namespace util { /** * A wrapper for do-something-once thread functions. */ void TraceThread(std::string_view thread_name, std::function<void()> thread_func); } // namespace util #endif // BITCOIN_UTIL_THREAD_H
0
bitcoin/src
bitcoin/src/util/trace.h
// 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. #ifndef BITCOIN_UTIL_TRACE_H #define BITCOIN_UTIL_TRACE_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #ifdef ENABLE_TRACING #include <sys/sdt.h> #define TRACE(context, event) DTRACE_PROBE(context, event) #define TRACE1(context, event, a) DTRACE_PROBE1(context, event, a) #define TRACE2(context, event, a, b) DTRACE_PROBE2(context, event, a, b) #define TRACE3(context, event, a, b, c) DTRACE_PROBE3(context, event, a, b, c) #define TRACE4(context, event, a, b, c, d) DTRACE_PROBE4(context, event, a, b, c, d) #define TRACE5(context, event, a, b, c, d, e) DTRACE_PROBE5(context, event, a, b, c, d, e) #define TRACE6(context, event, a, b, c, d, e, f) DTRACE_PROBE6(context, event, a, b, c, d, e, f) #define TRACE7(context, event, a, b, c, d, e, f, g) DTRACE_PROBE7(context, event, a, b, c, d, e, f, g) #define TRACE8(context, event, a, b, c, d, e, f, g, h) DTRACE_PROBE8(context, event, a, b, c, d, e, f, g, h) #define TRACE9(context, event, a, b, c, d, e, f, g, h, i) DTRACE_PROBE9(context, event, a, b, c, d, e, f, g, h, i) #define TRACE10(context, event, a, b, c, d, e, f, g, h, i, j) DTRACE_PROBE10(context, event, a, b, c, d, e, f, g, h, i, j) #define TRACE11(context, event, a, b, c, d, e, f, g, h, i, j, k) DTRACE_PROBE11(context, event, a, b, c, d, e, f, g, h, i, j, k) #define TRACE12(context, event, a, b, c, d, e, f, g, h, i, j, k, l) DTRACE_PROBE12(context, event, a, b, c, d, e, f, g, h, i, j, k, l) #else #define TRACE(context, event) #define TRACE1(context, event, a) #define TRACE2(context, event, a, b) #define TRACE3(context, event, a, b, c) #define TRACE4(context, event, a, b, c, d) #define TRACE5(context, event, a, b, c, d, e) #define TRACE6(context, event, a, b, c, d, e, f) #define TRACE7(context, event, a, b, c, d, e, f, g) #define TRACE8(context, event, a, b, c, d, e, f, g, h) #define TRACE9(context, event, a, b, c, d, e, f, g, h, i) #define TRACE10(context, event, a, b, c, d, e, f, g, h, i, j) #define TRACE11(context, event, a, b, c, d, e, f, g, h, i, j, k) #define TRACE12(context, event, a, b, c, d, e, f, g, h, i, j, k, l) #endif #endif // BITCOIN_UTIL_TRACE_H
0
bitcoin/src
bitcoin/src/util/fs_helpers.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2023 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_UTIL_FS_HELPERS_H #define BITCOIN_UTIL_FS_HELPERS_H #include <util/fs.h> #include <cstdint> #include <cstdio> #include <iosfwd> #include <limits> /** * Ensure file contents are fully committed to disk, using a platform-specific * feature analogous to fsync(). */ bool FileCommit(FILE* file); /** * Sync directory contents. This is required on some environments to ensure that * newly created files are committed to disk. */ void DirectoryCommit(const fs::path& dirname); bool TruncateFile(FILE* file, unsigned int length); int RaiseFileDescriptorLimit(int nMinFD); void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length); /** * Rename src to dest. * @return true if the rename was successful. */ [[nodiscard]] bool RenameOver(fs::path src, fs::path dest); namespace util { enum class LockResult { Success, ErrorWrite, ErrorLock, }; [[nodiscard]] LockResult LockDirectory(const fs::path& directory, const fs::path& lockfile_name, bool probe_only = false); } // namespace util void UnlockDirectory(const fs::path& directory, const fs::path& lockfile_name); bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes = 0); /** Get the size of a file by scanning it. * * @param[in] path The file path * @param[in] max Stop seeking beyond this limit * @return The file size or max */ std::streampos GetFileSize(const char* path, std::streamsize max = std::numeric_limits<std::streamsize>::max()); /** Release all directory locks. This is used for unit testing only, at runtime * the global destructor will take care of the locks. */ void ReleaseDirectoryLocks(); bool TryCreateDirectories(const fs::path& p); fs::path GetDefaultDataDir(); #ifdef WIN32 fs::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif #endif // BITCOIN_UTIL_FS_HELPERS_H
0
bitcoin/src
bitcoin/src/util/strencodings.cpp
// Copyright (c) 2009-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 <span.h> #include <util/strencodings.h> #include <array> #include <cassert> #include <cstring> #include <limits> #include <optional> #include <ostream> #include <string> #include <vector> static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static const std::string SAFE_CHARS[] = { CHARS_ALPHA_NUM + " .,;-_/:?@()", // SAFE_CHARS_DEFAULT CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME CHARS_ALPHA_NUM + "!*'();:@&=+$,/?#[]-_.~%", // SAFE_CHARS_URI }; std::string SanitizeString(std::string_view str, int rule) { std::string result; for (char c : str) { if (SAFE_CHARS[rule].find(c) != std::string::npos) { result.push_back(c); } } return result; } const signed char p_util_hexdigit[256] = { -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,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-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,0xa,0xb,0xc,0xd,0xe,0xf,-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,-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,-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,-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,-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,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; signed char HexDigit(char c) { return p_util_hexdigit[(unsigned char)c]; } bool IsHex(std::string_view str) { for (char c : str) { if (HexDigit(c) < 0) return false; } return (str.size() > 0) && (str.size()%2 == 0); } bool IsHexNumber(std::string_view str) { if (str.substr(0, 2) == "0x") str.remove_prefix(2); for (char c : str) { if (HexDigit(c) < 0) return false; } // Return false for empty string or "0x". return str.size() > 0; } template <typename Byte> std::optional<std::vector<Byte>> TryParseHex(std::string_view str) { std::vector<Byte> vch; auto it = str.begin(); while (it != str.end()) { if (IsSpace(*it)) { ++it; continue; } auto c1 = HexDigit(*(it++)); if (it == str.end()) return std::nullopt; auto c2 = HexDigit(*(it++)); if (c1 < 0 || c2 < 0) return std::nullopt; vch.push_back(Byte(c1 << 4) | Byte(c2)); } return vch; } template std::optional<std::vector<std::byte>> TryParseHex(std::string_view); template std::optional<std::vector<uint8_t>> TryParseHex(std::string_view); bool SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut) { bool valid = false; size_t colon = in.find_last_of(':'); // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator bool fHaveColon = colon != in.npos; bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe bool fMultiColon{fHaveColon && colon != 0 && (in.find_last_of(':', colon - 1) != in.npos)}; if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) { uint16_t n; if (ParseUInt16(in.substr(colon + 1), &n)) { in = in.substr(0, colon); portOut = n; valid = (portOut != 0); } } else { valid = true; } if (in.size() > 0 && in[0] == '[' && in[in.size() - 1] == ']') { hostOut = in.substr(1, in.size() - 2); } else { hostOut = in; } return valid; } std::string EncodeBase64(Span<const unsigned char> input) { static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string str; str.reserve(((input.size() + 2) / 3) * 4); ConvertBits<8, 6, true>([&](int v) { str += pbase64[v]; }, input.begin(), input.end()); while (str.size() % 4) str += '='; return str; } std::optional<std::vector<unsigned char>> DecodeBase64(std::string_view str) { static const int8_t decode64_table[256]{ -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 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, -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, -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, -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, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (str.size() % 4 != 0) return {}; /* One or two = characters at the end are permitted. */ if (str.size() >= 1 && str.back() == '=') str.remove_suffix(1); if (str.size() >= 1 && str.back() == '=') str.remove_suffix(1); std::vector<unsigned char> ret; ret.reserve((str.size() * 3) / 4); bool valid = ConvertBits<6, 8, false>( [&](unsigned char c) { ret.push_back(c); }, str.begin(), str.end(), [](char c) { return decode64_table[uint8_t(c)]; } ); if (!valid) return {}; return ret; } std::string EncodeBase32(Span<const unsigned char> input, bool pad) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; std::string str; str.reserve(((input.size() + 4) / 5) * 8); ConvertBits<8, 5, true>([&](int v) { str += pbase32[v]; }, input.begin(), input.end()); if (pad) { while (str.size() % 8) { str += '='; } } return str; } std::string EncodeBase32(std::string_view str, bool pad) { return EncodeBase32(MakeUCharSpan(str), pad); } std::optional<std::vector<unsigned char>> DecodeBase32(std::string_view str) { static const int8_t decode32_table[256]{ -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -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, -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, -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, -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, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (str.size() % 8 != 0) return {}; /* 1, 3, 4, or 6 padding '=' suffix characters are permitted. */ if (str.size() >= 1 && str.back() == '=') str.remove_suffix(1); if (str.size() >= 2 && str.substr(str.size() - 2) == "==") str.remove_suffix(2); if (str.size() >= 1 && str.back() == '=') str.remove_suffix(1); if (str.size() >= 2 && str.substr(str.size() - 2) == "==") str.remove_suffix(2); std::vector<unsigned char> ret; ret.reserve((str.size() * 5) / 8); bool valid = ConvertBits<5, 8, false>( [&](unsigned char c) { ret.push_back(c); }, str.begin(), str.end(), [](char c) { return decode32_table[uint8_t(c)]; } ); if (!valid) return {}; return ret; } namespace { template <typename T> bool ParseIntegral(std::string_view str, T* out) { static_assert(std::is_integral<T>::value); // Replicate the exact behavior of strtol/strtoll/strtoul/strtoull when // handling leading +/- for backwards compatibility. if (str.length() >= 2 && str[0] == '+' && str[1] == '-') { return false; } const std::optional<T> opt_int = ToIntegral<T>((!str.empty() && str[0] == '+') ? str.substr(1) : str); if (!opt_int) { return false; } if (out != nullptr) { *out = *opt_int; } return true; } }; // namespace bool ParseInt32(std::string_view str, int32_t* out) { return ParseIntegral<int32_t>(str, out); } bool ParseInt64(std::string_view str, int64_t* out) { return ParseIntegral<int64_t>(str, out); } bool ParseUInt8(std::string_view str, uint8_t* out) { return ParseIntegral<uint8_t>(str, out); } bool ParseUInt16(std::string_view str, uint16_t* out) { return ParseIntegral<uint16_t>(str, out); } bool ParseUInt32(std::string_view str, uint32_t* out) { return ParseIntegral<uint32_t>(str, out); } bool ParseUInt64(std::string_view str, uint64_t* out) { return ParseIntegral<uint64_t>(str, out); } std::string FormatParagraph(std::string_view in, size_t width, size_t indent) { assert(width >= indent); std::stringstream out; size_t ptr = 0; size_t indented = 0; while (ptr < in.size()) { size_t lineend = in.find_first_of('\n', ptr); if (lineend == std::string::npos) { lineend = in.size(); } const size_t linelen = lineend - ptr; const size_t rem_width = width - indented; if (linelen <= rem_width) { out << in.substr(ptr, linelen + 1); ptr = lineend + 1; indented = 0; } else { size_t finalspace = in.find_last_of(" \n", ptr + rem_width); if (finalspace == std::string::npos || finalspace < ptr) { // No place to break; just include the entire word and move on finalspace = in.find_first_of("\n ", ptr); if (finalspace == std::string::npos) { // End of the string, just add it and break out << in.substr(ptr); break; } } out << in.substr(ptr, finalspace - ptr) << "\n"; if (in[finalspace] == '\n') { indented = 0; } else if (indent) { out << std::string(indent, ' '); indented = indent; } ptr = finalspace + 1; } } return out.str(); } /** Upper bound for mantissa. * 10^18-1 is the largest arbitrary decimal that will fit in a signed 64-bit integer. * Larger integers cannot consist of arbitrary combinations of 0-9: * * 999999999999999999 1^18-1 * 9223372036854775807 (1<<63)-1 (max int64_t) * 9999999999999999999 1^19-1 (would overflow) */ static const int64_t UPPER_BOUND = 1000000000000000000LL - 1LL; /** Helper function for ParseFixedPoint */ static inline bool ProcessMantissaDigit(char ch, int64_t &mantissa, int &mantissa_tzeros) { if(ch == '0') ++mantissa_tzeros; else { for (int i=0; i<=mantissa_tzeros; ++i) { if (mantissa > (UPPER_BOUND / 10LL)) return false; /* overflow */ mantissa *= 10; } mantissa += ch - '0'; mantissa_tzeros = 0; } return true; } bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out) { int64_t mantissa = 0; int64_t exponent = 0; int mantissa_tzeros = 0; bool mantissa_sign = false; bool exponent_sign = false; int ptr = 0; int end = val.size(); int point_ofs = 0; if (ptr < end && val[ptr] == '-') { mantissa_sign = true; ++ptr; } if (ptr < end) { if (val[ptr] == '0') { /* pass single 0 */ ++ptr; } else if (val[ptr] >= '1' && val[ptr] <= '9') { while (ptr < end && IsDigit(val[ptr])) { if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) return false; /* overflow */ ++ptr; } } else return false; /* missing expected digit */ } else return false; /* empty string or loose '-' */ if (ptr < end && val[ptr] == '.') { ++ptr; if (ptr < end && IsDigit(val[ptr])) { while (ptr < end && IsDigit(val[ptr])) { if (!ProcessMantissaDigit(val[ptr], mantissa, mantissa_tzeros)) return false; /* overflow */ ++ptr; ++point_ofs; } } else return false; /* missing expected digit */ } if (ptr < end && (val[ptr] == 'e' || val[ptr] == 'E')) { ++ptr; if (ptr < end && val[ptr] == '+') ++ptr; else if (ptr < end && val[ptr] == '-') { exponent_sign = true; ++ptr; } if (ptr < end && IsDigit(val[ptr])) { while (ptr < end && IsDigit(val[ptr])) { if (exponent > (UPPER_BOUND / 10LL)) return false; /* overflow */ exponent = exponent * 10 + val[ptr] - '0'; ++ptr; } } else return false; /* missing expected digit */ } if (ptr != end) return false; /* trailing garbage */ /* finalize exponent */ if (exponent_sign) exponent = -exponent; exponent = exponent - point_ofs + mantissa_tzeros; /* finalize mantissa */ if (mantissa_sign) mantissa = -mantissa; /* convert to one 64-bit fixed-point value */ exponent += decimals; if (exponent < 0) return false; /* cannot represent values smaller than 10^-decimals */ if (exponent >= 18) return false; /* cannot represent values larger than or equal to 10^(18-decimals) */ for (int i=0; i < exponent; ++i) { if (mantissa > (UPPER_BOUND / 10LL) || mantissa < -(UPPER_BOUND / 10LL)) return false; /* overflow */ mantissa *= 10; } if (mantissa > UPPER_BOUND || mantissa < -UPPER_BOUND) return false; /* overflow */ if (amount_out) *amount_out = mantissa; return true; } std::string ToLower(std::string_view str) { std::string r; for (auto ch : str) r += ToLower(ch); return r; } std::string ToUpper(std::string_view str) { std::string r; for (auto ch : str) r += ToUpper(ch); return r; } std::string Capitalize(std::string str) { if (str.empty()) return str; str[0] = ToUpper(str.front()); return str; } namespace { using ByteAsHex = std::array<char, 2>; constexpr std::array<ByteAsHex, 256> CreateByteToHexMap() { constexpr char hexmap[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; std::array<ByteAsHex, 256> byte_to_hex{}; for (size_t i = 0; i < byte_to_hex.size(); ++i) { byte_to_hex[i][0] = hexmap[i >> 4]; byte_to_hex[i][1] = hexmap[i & 15]; } return byte_to_hex; } } // namespace std::string HexStr(const Span<const uint8_t> s) { std::string rv(s.size() * 2, '\0'); static constexpr auto byte_to_hex = CreateByteToHexMap(); static_assert(sizeof(byte_to_hex) == 512); char* it = rv.data(); for (uint8_t v : s) { std::memcpy(it, byte_to_hex[v].data(), 2); it += 2; } assert(it == rv.data() + rv.size()); return rv; } std::optional<uint64_t> ParseByteUnits(std::string_view str, ByteUnit default_multiplier) { if (str.empty()) { return std::nullopt; } auto multiplier = default_multiplier; char unit = str.back(); switch (unit) { case 'k': multiplier = ByteUnit::k; break; case 'K': multiplier = ByteUnit::K; break; case 'm': multiplier = ByteUnit::m; break; case 'M': multiplier = ByteUnit::M; break; case 'g': multiplier = ByteUnit::g; break; case 'G': multiplier = ByteUnit::G; break; case 't': multiplier = ByteUnit::t; break; case 'T': multiplier = ByteUnit::T; break; default: unit = 0; break; } uint64_t unit_amount = static_cast<uint64_t>(multiplier); auto parsed_num = ToIntegral<uint64_t>(unit ? str.substr(0, str.size() - 1) : str); if (!parsed_num || parsed_num > std::numeric_limits<uint64_t>::max() / unit_amount) { // check overflow return std::nullopt; } return *parsed_num * unit_amount; }
0
bitcoin/src
bitcoin/src/util/macros.h
// 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. #ifndef BITCOIN_UTIL_MACROS_H #define BITCOIN_UTIL_MACROS_H #define PASTE(x, y) x ## y #define PASTE2(x, y) PASTE(x, y) #define UNIQUE_NAME(name) PASTE2(name, __COUNTER__) /** * Converts the parameter X to a string after macro replacement on X has been performed. * Don't merge these into one macro! */ #define STRINGIZE(X) DO_STRINGIZE(X) #define DO_STRINGIZE(X) #X #endif // BITCOIN_UTIL_MACROS_H
0
bitcoin/src
bitcoin/src/util/transaction_identifier.h
#ifndef BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H #define BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H #include <attributes.h> #include <uint256.h> #include <util/types.h> /** transaction_identifier represents the two canonical transaction identifier * types (txid, wtxid).*/ template <bool has_witness> class transaction_identifier { uint256 m_wrapped; // Note: Use FromUint256 externally instead. transaction_identifier(const uint256& wrapped) : m_wrapped{wrapped} {} // TODO: Comparisons with uint256 should be disallowed once we have // converted most of the code to using the new txid types. constexpr int Compare(const uint256& other) const { return m_wrapped.Compare(other); } constexpr int Compare(const transaction_identifier<has_witness>& other) const { return m_wrapped.Compare(other.m_wrapped); } template <typename Other> constexpr int Compare(const Other& other) const { static_assert(ALWAYS_FALSE<Other>, "Forbidden comparison type"); return 0; } public: transaction_identifier() : m_wrapped{} {} template <typename Other> bool operator==(const Other& other) const { return Compare(other) == 0; } template <typename Other> bool operator!=(const Other& other) const { return Compare(other) != 0; } template <typename Other> bool operator<(const Other& other) const { return Compare(other) < 0; } const uint256& ToUint256() const LIFETIMEBOUND { return m_wrapped; } static transaction_identifier FromUint256(const uint256& id) { return {id}; } /** Wrapped `uint256` methods. */ constexpr bool IsNull() const { return m_wrapped.IsNull(); } constexpr void SetNull() { m_wrapped.SetNull(); } std::string GetHex() const { return m_wrapped.GetHex(); } std::string ToString() const { return m_wrapped.ToString(); } constexpr const std::byte* data() const { return reinterpret_cast<const std::byte*>(m_wrapped.data()); } constexpr const std::byte* begin() const { return reinterpret_cast<const std::byte*>(m_wrapped.begin()); } constexpr const std::byte* end() const { return reinterpret_cast<const std::byte*>(m_wrapped.end()); } template <typename Stream> void Serialize(Stream& s) const { m_wrapped.Serialize(s); } template <typename Stream> void Unserialize(Stream& s) { m_wrapped.Unserialize(s); } /** Conversion function to `uint256`. * * Note: new code should use `ToUint256`. * * TODO: This should be removed once the majority of the code has switched * to using the Txid and Wtxid types. Until then it makes for a smoother * transition to allow this conversion. */ operator const uint256&() const LIFETIMEBOUND { return m_wrapped; } }; /** Txid commits to all transaction fields except the witness. */ using Txid = transaction_identifier<false>; /** Wtxid commits to all transaction fields including the witness. */ using Wtxid = transaction_identifier<true>; inline Txid TxidFromString(std::string_view str) { return Txid::FromUint256(uint256S(str.data())); } #endif // BITCOIN_UTIL_TRANSACTION_IDENTIFIER_H
0
bitcoin/src
bitcoin/src/util/check.h
// 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. #ifndef BITCOIN_UTIL_CHECK_H #define BITCOIN_UTIL_CHECK_H #include <attributes.h> #include <cassert> // IWYU pragma: export #include <stdexcept> #include <string> #include <string_view> #include <utility> std::string StrFormatInternalBug(std::string_view msg, std::string_view file, int line, std::string_view func); class NonFatalCheckError : public std::runtime_error { public: NonFatalCheckError(std::string_view msg, std::string_view file, int line, std::string_view func); }; /** Helper for CHECK_NONFATAL() */ template <typename T> T&& inline_check_non_fatal(LIFETIMEBOUND T&& val, const char* file, int line, const char* func, const char* assertion) { if (!val) { throw NonFatalCheckError{assertion, file, line, func}; } return std::forward<T>(val); } #if defined(NDEBUG) #error "Cannot compile without assertions!" #endif /** Helper for Assert() */ void assertion_fail(std::string_view file, int line, std::string_view func, std::string_view assertion); /** Helper for Assert()/Assume() */ template <bool IS_ASSERT, typename T> T&& inline_assertion_check(LIFETIMEBOUND T&& val, [[maybe_unused]] const char* file, [[maybe_unused]] int line, [[maybe_unused]] const char* func, [[maybe_unused]] const char* assertion) { if constexpr (IS_ASSERT #ifdef ABORT_ON_FAILED_ASSUME || true #endif ) { if (!val) { assertion_fail(file, line, func, assertion); } } return std::forward<T>(val); } // All macros may use __func__ inside a lambda, so put them under nolint. // NOLINTBEGIN(bugprone-lambda-function-name) #define STR_INTERNAL_BUG(msg) StrFormatInternalBug((msg), __FILE__, __LINE__, __func__) /** * Identity function. Throw a NonFatalCheckError when the condition evaluates to false * * This should only be used * - where the condition is assumed to be true, not for error handling or validating user input * - where a failure to fulfill the condition is recoverable and does not abort the program * * For example in RPC code, where it is undesirable to crash the whole program, this can be generally used to replace * asserts or recoverable logic errors. A NonFatalCheckError in RPC code is caught and passed as a string to the RPC * caller, which can then report the issue to the developers. */ #define CHECK_NONFATAL(condition) \ inline_check_non_fatal(condition, __FILE__, __LINE__, __func__, #condition) /** Identity function. Abort if the value compares equal to zero */ #define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val) /** * Assume is the identity function. * * - Should be used to run non-fatal checks. In debug builds it behaves like * Assert()/assert() to notify developers and testers about non-fatal errors. * In production it doesn't warn or log anything. * - For fatal errors, use Assert(). * - For non-fatal errors in interactive sessions (e.g. RPC or command line * interfaces), CHECK_NONFATAL() might be more appropriate. */ #define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val) /** * NONFATAL_UNREACHABLE() is a macro that is used to mark unreachable code. It throws a NonFatalCheckError. */ #define NONFATAL_UNREACHABLE() \ throw NonFatalCheckError( \ "Unreachable code reached (non-fatal)", __FILE__, __LINE__, __func__) // NOLINTEND(bugprone-lambda-function-name) #endif // BITCOIN_UTIL_CHECK_H
0
bitcoin/src
bitcoin/src/util/strencodings.h
// Copyright (c) 2009-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. /** * Utilities for converting data from/to strings. */ #ifndef BITCOIN_UTIL_STRENCODINGS_H #define BITCOIN_UTIL_STRENCODINGS_H #include <span.h> #include <util/string.h> #include <charconv> #include <cstddef> #include <cstdint> #include <limits> #include <optional> #include <string> // IWYU pragma: export #include <string_view> // IWYU pragma: export #include <system_error> #include <type_traits> #include <vector> /** Used by SanitizeString() */ enum SafeChars { SAFE_CHARS_DEFAULT, //!< The full set of allowed chars SAFE_CHARS_UA_COMMENT, //!< BIP-0014 subset SAFE_CHARS_FILENAME, //!< Chars allowed in filenames SAFE_CHARS_URI, //!< Chars allowed in URIs (RFC 3986) }; /** * Used by ParseByteUnits() * Lowercase base 1000 * Uppercase base 1024 */ enum class ByteUnit : uint64_t { NOOP = 1ULL, k = 1000ULL, K = 1024ULL, m = 1'000'000ULL, M = 1ULL << 20, g = 1'000'000'000ULL, G = 1ULL << 30, t = 1'000'000'000'000ULL, T = 1ULL << 40, }; /** * Remove unsafe chars. Safe chars chosen to allow simple messages/URLs/email * addresses, but avoid anything even possibly remotely dangerous like & or > * @param[in] str The string to sanitize * @param[in] rule The set of safe chars to choose (default: least restrictive) * @return A new string without unsafe chars */ std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT); /** Parse the hex string into bytes (uint8_t or std::byte). Ignores whitespace. Returns nullopt on invalid input. */ template <typename Byte = std::byte> std::optional<std::vector<Byte>> TryParseHex(std::string_view str); /** Like TryParseHex, but returns an empty vector on invalid input. */ template <typename Byte = uint8_t> std::vector<Byte> ParseHex(std::string_view hex_str) { return TryParseHex<Byte>(hex_str).value_or(std::vector<Byte>{}); } signed char HexDigit(char c); /* Returns true if each character in str is a hex character, and has an even * number of hex digits.*/ bool IsHex(std::string_view str); /** * Return true if the string is a hex number, optionally prefixed with "0x" */ bool IsHexNumber(std::string_view str); std::optional<std::vector<unsigned char>> DecodeBase64(std::string_view str); std::string EncodeBase64(Span<const unsigned char> input); inline std::string EncodeBase64(Span<const std::byte> input) { return EncodeBase64(MakeUCharSpan(input)); } inline std::string EncodeBase64(std::string_view str) { return EncodeBase64(MakeUCharSpan(str)); } std::optional<std::vector<unsigned char>> DecodeBase32(std::string_view str); /** * Base32 encode. * If `pad` is true, then the output will be padded with '=' so that its length * is a multiple of 8. */ std::string EncodeBase32(Span<const unsigned char> input, bool pad = true); /** * Base32 encode. * If `pad` is true, then the output will be padded with '=' so that its length * is a multiple of 8. */ std::string EncodeBase32(std::string_view str, bool pad = true); /** * Splits socket address string into host string and port value. * Validates port value. * * @param[in] in The socket address string to split. * @param[out] portOut Port-portion of the input, if found and parsable. * @param[out] hostOut Host-portion of the input, if found. * @return true if port-portion is absent or within its allowed range, otherwise false */ bool SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut); // LocaleIndependentAtoi is provided for backwards compatibility reasons. // // New code should use ToIntegral or the ParseInt* functions // which provide parse error feedback. // // The goal of LocaleIndependentAtoi is to replicate the defined behaviour of // std::atoi as it behaves under the "C" locale, and remove some undefined // behavior. If the parsed value is bigger than the integer type's maximum // value, or smaller than the integer type's minimum value, std::atoi has // undefined behavior, while this function returns the maximum or minimum // values, respectively. template <typename T> T LocaleIndependentAtoi(std::string_view str) { static_assert(std::is_integral<T>::value); T result; // Emulate atoi(...) handling of white space and leading +/-. std::string_view s = TrimStringView(str); if (!s.empty() && s[0] == '+') { if (s.length() >= 2 && s[1] == '-') { return 0; } s = s.substr(1); } auto [_, error_condition] = std::from_chars(s.data(), s.data() + s.size(), result); if (error_condition == std::errc::result_out_of_range) { if (s.length() >= 1 && s[0] == '-') { // Saturate underflow, per strtoll's behavior. return std::numeric_limits<T>::min(); } else { // Saturate overflow, per strtoll's behavior. return std::numeric_limits<T>::max(); } } else if (error_condition != std::errc{}) { return 0; } return result; } /** * Tests if the given character is a decimal digit. * @param[in] c character to test * @return true if the argument is a decimal digit; otherwise false. */ constexpr bool IsDigit(char c) { return c >= '0' && c <= '9'; } /** * Tests if the given character is a whitespace character. The whitespace characters * are: space, form-feed ('\f'), newline ('\n'), carriage return ('\r'), horizontal * tab ('\t'), and vertical tab ('\v'). * * This function is locale independent. Under the C locale this function gives the * same result as std::isspace. * * @param[in] c character to test * @return true if the argument is a whitespace character; otherwise false */ constexpr inline bool IsSpace(char c) noexcept { return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v'; } /** * Convert string to integral type T. Leading whitespace, a leading +, or any * trailing character fail the parsing. The required format expressed as regex * is `-?[0-9]+`. The minus sign is only permitted for signed integer types. * * @returns std::nullopt if the entire string could not be parsed, or if the * parsed value is not in the range representable by the type T. */ template <typename T> std::optional<T> ToIntegral(std::string_view str) { static_assert(std::is_integral<T>::value); T result; const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result); if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) { return std::nullopt; } return result; } /** * Convert string to signed 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ [[nodiscard]] bool ParseInt32(std::string_view str, int32_t *out); /** * Convert string to signed 64-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ [[nodiscard]] bool ParseInt64(std::string_view str, int64_t *out); /** * Convert decimal string to unsigned 8-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ [[nodiscard]] bool ParseUInt8(std::string_view str, uint8_t *out); /** * Convert decimal string to unsigned 16-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if the entire string could not be parsed or if overflow or underflow occurred. */ [[nodiscard]] bool ParseUInt16(std::string_view str, uint16_t* out); /** * Convert decimal string to unsigned 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ [[nodiscard]] bool ParseUInt32(std::string_view str, uint32_t *out); /** * Convert decimal string to unsigned 64-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ [[nodiscard]] bool ParseUInt64(std::string_view str, uint64_t *out); /** * Convert a span of bytes to a lower-case hexadecimal string. */ std::string HexStr(const Span<const uint8_t> s); inline std::string HexStr(const Span<const char> s) { return HexStr(MakeUCharSpan(s)); } inline std::string HexStr(const Span<const std::byte> s) { return HexStr(MakeUCharSpan(s)); } /** * Format a paragraph of text to a fixed width, adding spaces for * indentation to any added line. */ std::string FormatParagraph(std::string_view in, size_t width = 79, size_t indent = 0); /** * Timing-attack-resistant comparison. * Takes time proportional to length * of first argument. */ template <typename T> bool TimingResistantEqual(const T& a, const T& b) { if (b.size() == 0) return a.size() == 0; size_t accumulator = a.size() ^ b.size(); for (size_t i = 0; i < a.size(); i++) accumulator |= size_t(a[i] ^ b[i%b.size()]); return accumulator == 0; } /** Parse number as fixed point according to JSON number syntax. * @returns true on success, false on error. * @note The result must be in the range (-10^18,10^18), otherwise an overflow error will trigger. */ [[nodiscard]] bool ParseFixedPoint(std::string_view, int decimals, int64_t *amount_out); namespace { /** Helper class for the default infn argument to ConvertBits (just returns the input). */ struct IntIdentity { [[maybe_unused]] int operator()(int x) const { return x; } }; } // namespace /** Convert from one power-of-2 number base to another. */ template<int frombits, int tobits, bool pad, typename O, typename It, typename I = IntIdentity> bool ConvertBits(O outfn, It it, It end, I infn = {}) { size_t acc = 0; size_t bits = 0; constexpr size_t maxv = (1 << tobits) - 1; constexpr size_t max_acc = (1 << (frombits + tobits - 1)) - 1; while (it != end) { int v = infn(*it); if (v < 0) return false; acc = ((acc << frombits) | v) & max_acc; bits += frombits; while (bits >= tobits) { bits -= tobits; outfn((acc >> bits) & maxv); } ++it; } if (pad) { if (bits) outfn((acc << (tobits - bits)) & maxv); } else if (bits >= frombits || ((acc << (tobits - bits)) & maxv)) { return false; } return true; } /** * Converts the given character to its lowercase equivalent. * This function is locale independent. It only converts uppercase * characters in the standard 7-bit ASCII range. * This is a feature, not a limitation. * * @param[in] c the character to convert to lowercase. * @return the lowercase equivalent of c; or the argument * if no conversion is possible. */ constexpr char ToLower(char c) { return (c >= 'A' && c <= 'Z' ? (c - 'A') + 'a' : c); } /** * Returns the lowercase equivalent of the given string. * This function is locale independent. It only converts uppercase * characters in the standard 7-bit ASCII range. * This is a feature, not a limitation. * * @param[in] str the string to convert to lowercase. * @returns lowercased equivalent of str */ std::string ToLower(std::string_view str); /** * Converts the given character to its uppercase equivalent. * This function is locale independent. It only converts lowercase * characters in the standard 7-bit ASCII range. * This is a feature, not a limitation. * * @param[in] c the character to convert to uppercase. * @return the uppercase equivalent of c; or the argument * if no conversion is possible. */ constexpr char ToUpper(char c) { return (c >= 'a' && c <= 'z' ? (c - 'a') + 'A' : c); } /** * Returns the uppercase equivalent of the given string. * This function is locale independent. It only converts lowercase * characters in the standard 7-bit ASCII range. * This is a feature, not a limitation. * * @param[in] str the string to convert to uppercase. * @returns UPPERCASED EQUIVALENT OF str */ std::string ToUpper(std::string_view str); /** * Capitalizes the first character of the given string. * This function is locale independent. It only converts lowercase * characters in the standard 7-bit ASCII range. * This is a feature, not a limitation. * * @param[in] str the string to capitalize. * @returns string with the first letter capitalized. */ std::string Capitalize(std::string str); /** * Parse a string with suffix unit [k|K|m|M|g|G|t|T]. * Must be a whole integer, fractions not allowed (0.5t), no whitespace or +- * Lowercase units are 1000 base. Uppercase units are 1024 base. * Examples: 2m,27M,19g,41T * * @param[in] str the string to convert into bytes * @param[in] default_multiplier if no unit is found in str use this unit * @returns optional uint64_t bytes from str or nullopt * if ToIntegral is false, str is empty, trailing whitespace or overflow */ std::optional<uint64_t> ParseByteUnits(std::string_view str, ByteUnit default_multiplier); #endif // BITCOIN_UTIL_STRENCODINGS_H
0
bitcoin/src
bitcoin/src/util/fs.cpp
// Copyright (c) 2017-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 <util/fs.h> #include <util/syserror.h> #ifndef WIN32 #include <cstring> #include <fcntl.h> #include <sys/file.h> #include <sys/utsname.h> #include <unistd.h> #else #include <codecvt> #include <limits> #include <windows.h> #endif #include <cassert> #include <cerrno> #include <string> namespace fsbridge { FILE *fopen(const fs::path& p, const char *mode) { #ifndef WIN32 return ::fopen(p.c_str(), mode); #else std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t> utf8_cvt; return ::_wfopen(p.wstring().c_str(), utf8_cvt.from_bytes(mode).c_str()); #endif } fs::path AbsPathJoin(const fs::path& base, const fs::path& path) { assert(base.is_absolute()); return path.empty() ? base : fs::path(base / path); } #ifndef WIN32 static std::string GetErrorReason() { return SysErrorString(errno); } FileLock::FileLock(const fs::path& file) { fd = open(file.c_str(), O_RDWR); if (fd == -1) { reason = GetErrorReason(); } } FileLock::~FileLock() { if (fd != -1) { close(fd); } } bool FileLock::TryLock() { if (fd == -1) { return false; } struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (fcntl(fd, F_SETLK, &lock) == -1) { reason = GetErrorReason(); return false; } return true; } #else static std::string GetErrorReason() { return Win32ErrorString(GetLastError()); } FileLock::FileLock(const fs::path& file) { hFile = CreateFileW(file.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) { reason = GetErrorReason(); } } FileLock::~FileLock() { if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } } bool FileLock::TryLock() { if (hFile == INVALID_HANDLE_VALUE) { return false; } _OVERLAPPED overlapped = {}; if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, std::numeric_limits<DWORD>::max(), std::numeric_limits<DWORD>::max(), &overlapped)) { reason = GetErrorReason(); return false; } return true; } #endif std::string get_filesystem_error_message(const fs::filesystem_error& e) { #ifndef WIN32 return e.what(); #else // Convert from Multi Byte to utf-16 std::string mb_string(e.what()); int size = MultiByteToWideChar(CP_ACP, 0, mb_string.data(), mb_string.size(), nullptr, 0); std::wstring utf16_string(size, L'\0'); MultiByteToWideChar(CP_ACP, 0, mb_string.data(), mb_string.size(), &*utf16_string.begin(), size); // Convert from utf-16 to utf-8 return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().to_bytes(utf16_string); #endif } } // namespace fsbridge
0
bitcoin/src
bitcoin/src/util/insert.h
// Copyright (c) 2023 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_UTIL_INSERT_H #define BITCOIN_UTIL_INSERT_H #include <set> namespace util { //! Simplification of std insertion template <typename Tdst, typename Tsrc> inline void insert(Tdst& dst, const Tsrc& src) { dst.insert(dst.begin(), src.begin(), src.end()); } template <typename TsetT, typename Tsrc> inline void insert(std::set<TsetT>& dst, const Tsrc& src) { dst.insert(src.begin(), src.end()); } } // namespace util #endif // BITCOIN_UTIL_INSERT_H
0
bitcoin/src
bitcoin/src/util/syserror.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. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <tinyformat.h> #include <util/syserror.h> #include <cstring> #include <string> #if defined(WIN32) #include <windows.h> #include <locale> #include <codecvt> #endif std::string SysErrorString(int err) { char buf[1024]; /* Too bad there are three incompatible implementations of the * thread-safe strerror. */ const char *s = nullptr; #ifdef WIN32 if (strerror_s(buf, sizeof(buf), err) == 0) s = buf; #else #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ if (strerror_r(err, buf, sizeof(buf)) == 0) s = buf; #endif #endif if (s != nullptr) { return strprintf("%s (%d)", s, err); } else { return strprintf("Unknown error (%d)", err); } } #if defined(WIN32) std::string Win32ErrorString(int err) { wchar_t buf[256]; buf[0] = 0; if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, ARRAYSIZE(buf), nullptr)) { return strprintf("%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().to_bytes(buf), err); } else { return strprintf("Unknown error (%d)", err); } } #endif
0
bitcoin/src
bitcoin/src/util/moneystr.cpp
// Copyright (c) 2009-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 <util/moneystr.h> #include <consensus/amount.h> #include <tinyformat.h> #include <util/strencodings.h> #include <util/string.h> #include <cstdint> #include <optional> std::string FormatMoney(const CAmount n) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. static_assert(COIN > 1); int64_t quotient = n / COIN; int64_t remainder = n % COIN; if (n < 0) { quotient = -quotient; remainder = -remainder; } std::string str = strprintf("%d.%08d", quotient, remainder); // Right-trim excess zeros before the decimal point: int nTrim = 0; for (int i = str.size()-1; (str[i] == '0' && IsDigit(str[i-2])); --i) ++nTrim; if (nTrim) str.erase(str.size()-nTrim, nTrim); if (n < 0) str.insert(uint32_t{0}, 1, '-'); return str; } std::optional<CAmount> ParseMoney(const std::string& money_string) { if (!ContainsNoNUL(money_string)) { return std::nullopt; } const std::string str = TrimString(money_string); if (str.empty()) { return std::nullopt; } std::string strWhole; int64_t nUnits = 0; const char* p = str.c_str(); for (; *p; p++) { if (*p == '.') { p++; int64_t nMult = COIN / 10; while (IsDigit(*p) && (nMult > 0)) { nUnits += nMult * (*p++ - '0'); nMult /= 10; } break; } if (IsSpace(*p)) return std::nullopt; if (!IsDigit(*p)) return std::nullopt; strWhole.insert(strWhole.end(), *p); } if (*p) { return std::nullopt; } if (strWhole.size() > 10) // guard against 63 bit overflow return std::nullopt; if (nUnits < 0 || nUnits > COIN) return std::nullopt; int64_t nWhole = LocaleIndependentAtoi<int64_t>(strWhole); CAmount value = nWhole * COIN + nUnits; if (!MoneyRange(value)) { return std::nullopt; } return value; }
0
bitcoin/src
bitcoin/src/util/overflow.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_UTIL_OVERFLOW_H #define BITCOIN_UTIL_OVERFLOW_H #include <limits> #include <optional> #include <type_traits> template <class T> [[nodiscard]] bool AdditionOverflow(const T i, const T j) noexcept { static_assert(std::is_integral<T>::value, "Integral required."); if constexpr (std::numeric_limits<T>::is_signed) { return (i > 0 && j > std::numeric_limits<T>::max() - i) || (i < 0 && j < std::numeric_limits<T>::min() - i); } return std::numeric_limits<T>::max() - i < j; } template <class T> [[nodiscard]] std::optional<T> CheckedAdd(const T i, const T j) noexcept { if (AdditionOverflow(i, j)) { return std::nullopt; } return i + j; } template <class T> [[nodiscard]] T SaturatingAdd(const T i, const T j) noexcept { if constexpr (std::numeric_limits<T>::is_signed) { if (i > 0 && j > std::numeric_limits<T>::max() - i) { return std::numeric_limits<T>::max(); } if (i < 0 && j < std::numeric_limits<T>::min() - i) { return std::numeric_limits<T>::min(); } } else { if (std::numeric_limits<T>::max() - i < j) { return std::numeric_limits<T>::max(); } } return i + j; } #endif // BITCOIN_UTIL_OVERFLOW_H
0
bitcoin/src
bitcoin/src/util/spanparsing.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_UTIL_SPANPARSING_H #define BITCOIN_UTIL_SPANPARSING_H #include <span.h> #include <string> #include <string_view> #include <vector> namespace spanparsing { /** Parse a constant. * * If sp's initial part matches str, sp is updated to skip that part, and true is returned. * Otherwise sp is unmodified and false is returned. */ bool Const(const std::string& str, Span<const char>& sp); /** Parse a function call. * * If sp's initial part matches str + "(", and sp ends with ")", sp is updated to be the * section between the braces, and true is returned. Otherwise sp is unmodified and false * is returned. */ bool Func(const std::string& str, Span<const char>& sp); /** Extract the expression that sp begins with. * * This function will return the initial part of sp, up to (but not including) the first * comma or closing brace, skipping ones that are surrounded by braces. So for example, * for "foo(bar(1),2),3" the initial part "foo(bar(1),2)" will be returned. sp will be * updated to skip the initial part that is returned. */ Span<const char> Expr(Span<const char>& sp); /** Split a string on any char found in separators, returning a vector. * * If sep does not occur in sp, a singleton with the entirety of sp is returned. * * Note that this function does not care about braces, so splitting * "foo(bar(1),2),3) on ',' will return {"foo(bar(1)", "2)", "3)"}. */ template <typename T = Span<const char>> std::vector<T> Split(const Span<const char>& sp, std::string_view separators) { std::vector<T> ret; auto it = sp.begin(); auto start = it; while (it != sp.end()) { if (separators.find(*it) != std::string::npos) { ret.emplace_back(start, it); start = it + 1; } ++it; } ret.emplace_back(start, it); return ret; } /** Split a string on every instance of sep, returning a vector. * * If sep does not occur in sp, a singleton with the entirety of sp is returned. * * Note that this function does not care about braces, so splitting * "foo(bar(1),2),3) on ',' will return {"foo(bar(1)", "2)", "3)"}. */ template <typename T = Span<const char>> std::vector<T> Split(const Span<const char>& sp, char sep) { return Split<T>(sp, std::string_view{&sep, 1}); } } // namespace spanparsing #endif // BITCOIN_UTIL_SPANPARSING_H
0
bitcoin/src
bitcoin/src/util/serfloat.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_UTIL_SERFLOAT_H #define BITCOIN_UTIL_SERFLOAT_H #include <cstdint> /* Encode a double using the IEEE 754 binary64 format. All NaNs are encoded as x86/ARM's * positive quiet NaN with payload 0. */ uint64_t EncodeDouble(double f) noexcept; /* Reverse operation of DecodeDouble. DecodeDouble(EncodeDouble(f))==f unless isnan(f). */ double DecodeDouble(uint64_t v) noexcept; #endif // BITCOIN_UTIL_SERFLOAT_H
0
bitcoin/src
bitcoin/src/util/ui_change_type.h
// Copyright (c) 2012-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_UTIL_UI_CHANGE_TYPE_H #define BITCOIN_UTIL_UI_CHANGE_TYPE_H /** General change type (added, updated, removed). */ enum ChangeType { CT_NEW, CT_UPDATED, CT_DELETED }; #endif // BITCOIN_UTIL_UI_CHANGE_TYPE_H
0
bitcoin/src
bitcoin/src/util/bytevectorhash.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 <crypto/siphash.h> #include <random.h> #include <util/bytevectorhash.h> #include <vector> ByteVectorHash::ByteVectorHash() : m_k0(GetRand<uint64_t>()), m_k1(GetRand<uint64_t>()) { } size_t ByteVectorHash::operator()(const std::vector<unsigned char>& input) const { return CSipHasher(m_k0, m_k1).Write(input).Finalize(); }
0
bitcoin/src
bitcoin/src/util/serfloat.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 <util/serfloat.h> #include <cmath> #include <limits> double DecodeDouble(uint64_t v) noexcept { static constexpr double NANVAL = std::numeric_limits<double>::quiet_NaN(); static constexpr double INFVAL = std::numeric_limits<double>::infinity(); double sign = 1.0; if (v & 0x8000000000000000) { sign = -1.0; v ^= 0x8000000000000000; } // Zero if (v == 0) return copysign(0.0, sign); // Infinity if (v == 0x7ff0000000000000) return copysign(INFVAL, sign); // Other numbers int exp = (v & 0x7FF0000000000000) >> 52; uint64_t man = v & 0xFFFFFFFFFFFFF; if (exp == 2047) { // NaN return NANVAL; } else if (exp == 0) { // Subnormal return copysign(ldexp((double)man, -1074), sign); } else { // Normal return copysign(ldexp((double)(man + 0x10000000000000), -1075 + exp), sign); } } uint64_t EncodeDouble(double f) noexcept { int cls = std::fpclassify(f); uint64_t sign = 0; if (copysign(1.0, f) == -1.0) { f = -f; sign = 0x8000000000000000; } // Zero if (cls == FP_ZERO) return sign; // Infinity if (cls == FP_INFINITE) return sign | 0x7ff0000000000000; // NaN if (cls == FP_NAN) return 0x7ff8000000000000; // Other numbers int exp; uint64_t man = std::round(std::frexp(f, &exp) * 9007199254740992.0); if (exp < -1021) { // Too small to represent, encode 0 if (exp < -1084) return sign; // Subnormal numbers return sign | (man >> (-1021 - exp)); } else { // Too big to represent, encode infinity if (exp > 1024) return sign | 0x7ff0000000000000; // Normal numbers return sign | (((uint64_t)(1022 + exp)) << 52) | (man & 0xFFFFFFFFFFFFF); } }
0
bitcoin/src
bitcoin/src/util/check.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 <util/check.h> #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <clientversion.h> #include <tinyformat.h> #include <cstdio> #include <cstdlib> #include <string> #include <string_view> std::string StrFormatInternalBug(std::string_view msg, std::string_view file, int line, std::string_view func) { return strprintf("Internal bug detected: %s\n%s:%d (%s)\n" "%s %s\n" "Please report this issue here: %s\n", msg, file, line, func, PACKAGE_NAME, FormatFullVersion(), PACKAGE_BUGREPORT); } NonFatalCheckError::NonFatalCheckError(std::string_view msg, std::string_view file, int line, std::string_view func) : std::runtime_error{StrFormatInternalBug(msg, file, line, func)} { } void assertion_fail(std::string_view file, int line, std::string_view func, std::string_view assertion) { auto str = strprintf("%s:%s %s: Assertion `%s' failed.\n", file, line, func, assertion); fwrite(str.data(), 1, str.size(), stderr); std::abort(); }
0
bitcoin/src
bitcoin/src/util/fees.cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-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. #include <util/fees.h> #include <policy/fees.h> #include <util/strencodings.h> #include <util/string.h> #include <map> #include <string> #include <vector> #include <utility> std::string StringForFeeReason(FeeReason reason) { static const std::map<FeeReason, std::string> fee_reason_strings = { {FeeReason::NONE, "None"}, {FeeReason::HALF_ESTIMATE, "Half Target 60% Threshold"}, {FeeReason::FULL_ESTIMATE, "Target 85% Threshold"}, {FeeReason::DOUBLE_ESTIMATE, "Double Target 95% Threshold"}, {FeeReason::CONSERVATIVE, "Conservative Double Target longer horizon"}, {FeeReason::MEMPOOL_MIN, "Mempool Min Fee"}, {FeeReason::PAYTXFEE, "PayTxFee set"}, {FeeReason::FALLBACK, "Fallback fee"}, {FeeReason::REQUIRED, "Minimum Required Fee"}, }; auto reason_string = fee_reason_strings.find(reason); if (reason_string == fee_reason_strings.end()) return "Unknown"; return reason_string->second; } const std::vector<std::pair<std::string, FeeEstimateMode>>& FeeModeMap() { static const std::vector<std::pair<std::string, FeeEstimateMode>> FEE_MODES = { {"unset", FeeEstimateMode::UNSET}, {"economical", FeeEstimateMode::ECONOMICAL}, {"conservative", FeeEstimateMode::CONSERVATIVE}, }; return FEE_MODES; } std::string FeeModes(const std::string& delimiter) { return Join(FeeModeMap(), delimiter, [&](const std::pair<std::string, FeeEstimateMode>& i) { return i.first; }); } std::string InvalidEstimateModeErrorMessage() { return "Invalid estimate_mode parameter, must be one of: \"" + FeeModes("\", \"") + "\""; } bool FeeModeFromString(const std::string& mode_string, FeeEstimateMode& fee_estimate_mode) { auto searchkey = ToUpper(mode_string); for (const auto& pair : FeeModeMap()) { if (ToUpper(pair.first) == searchkey) { fee_estimate_mode = pair.second; return true; } } return false; }
0
bitcoin/src
bitcoin/src/util/vector.h
// 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. #ifndef BITCOIN_UTIL_VECTOR_H #define BITCOIN_UTIL_VECTOR_H #include <functional> #include <initializer_list> #include <optional> #include <type_traits> #include <utility> #include <vector> /** Construct a vector with the specified elements. * * This is preferable over the list initializing constructor of std::vector: * - It automatically infers the element type from its arguments. * - If any arguments are rvalue references, they will be moved into the vector * (list initialization always copies). */ template<typename... Args> inline std::vector<typename std::common_type<Args...>::type> Vector(Args&&... args) { std::vector<typename std::common_type<Args...>::type> ret; ret.reserve(sizeof...(args)); // The line below uses the trick from https://www.experts-exchange.com/articles/32502/None-recursive-variadic-templates-with-std-initializer-list.html (void)std::initializer_list<int>{(ret.emplace_back(std::forward<Args>(args)), 0)...}; return ret; } /** Concatenate two vectors, moving elements. */ template<typename V> inline V Cat(V v1, V&& v2) { v1.reserve(v1.size() + v2.size()); for (auto& arg : v2) { v1.push_back(std::move(arg)); } return v1; } /** Concatenate two vectors. */ template<typename V> inline V Cat(V v1, const V& v2) { v1.reserve(v1.size() + v2.size()); for (const auto& arg : v2) { v1.push_back(arg); } return v1; } /** Clear a vector (or std::deque) and release its allocated memory. */ template<typename V> inline void ClearShrink(V& v) noexcept { // There are various ways to clear a vector and release its memory: // // 1. V{}.swap(v) // 2. v = V{} // 3. v = {}; v.shrink_to_fit(); // 4. v.clear(); v.shrink_to_fit(); // // (2) does not appear to release memory in glibc debug mode, even if v.shrink_to_fit() // follows. (3) and (4) rely on std::vector::shrink_to_fit, which is only a non-binding // request. Therefore, we use method (1). V{}.swap(v); } template<typename V, typename L> inline std::optional<V> FindFirst(const std::vector<V>& vec, const L fnc) { for (const auto& el : vec) { if (fnc(el)) { return el; } } return std::nullopt; } #endif // BITCOIN_UTIL_VECTOR_H
0
bitcoin/src
bitcoin/src/util/exception.h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2023 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_UTIL_EXCEPTION_H #define BITCOIN_UTIL_EXCEPTION_H #include <exception> #include <string_view> void PrintExceptionContinue(const std::exception* pex, std::string_view thread_name); #endif // BITCOIN_UTIL_EXCEPTION_H
0
bitcoin/src
bitcoin/src/util/signalinterrupt.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 <util/signalinterrupt.h> #ifdef WIN32 #include <mutex> #else #include <util/tokenpipe.h> #endif #include <ios> #include <optional> namespace util { SignalInterrupt::SignalInterrupt() : m_flag{false} { #ifndef WIN32 std::optional<TokenPipe> pipe = TokenPipe::Make(); if (!pipe) throw std::ios_base::failure("Could not create TokenPipe"); m_pipe_r = pipe->TakeReadEnd(); m_pipe_w = pipe->TakeWriteEnd(); #endif } SignalInterrupt::operator bool() const { return m_flag; } bool SignalInterrupt::reset() { // Cancel existing interrupt by waiting for it, this will reset condition flags and remove // the token from the pipe. if (*this && !wait()) return false; m_flag = false; return true; } bool SignalInterrupt::operator()() { #ifdef WIN32 std::unique_lock<std::mutex> lk(m_mutex); m_flag = true; m_cv.notify_one(); #else // This must be reentrant and safe for calling in a signal handler, so using a condition variable is not safe. // Make sure that the token is only written once even if multiple threads call this concurrently or in // case of a reentrant signal. if (!m_flag.exchange(true)) { // Write an arbitrary byte to the write end of the pipe. int res = m_pipe_w.TokenWrite('x'); if (res != 0) { return false; } } #endif return true; } bool SignalInterrupt::wait() { #ifdef WIN32 std::unique_lock<std::mutex> lk(m_mutex); m_cv.wait(lk, [this] { return m_flag.load(); }); #else int res = m_pipe_r.TokenRead(); if (res != 'x') { return false; } #endif return true; } } // namespace util
0
bitcoin/src
bitcoin/src/util/asmap.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 <util/asmap.h> #include <clientversion.h> #include <crypto/common.h> #include <logging.h> #include <serialize.h> #include <streams.h> #include <util/fs.h> #include <algorithm> #include <cassert> #include <cstdio> #include <utility> #include <vector> namespace { constexpr uint32_t INVALID = 0xFFFFFFFF; uint32_t DecodeBits(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos, uint8_t minval, const std::vector<uint8_t> &bit_sizes) { uint32_t val = minval; bool bit; for (std::vector<uint8_t>::const_iterator bit_sizes_it = bit_sizes.begin(); bit_sizes_it != bit_sizes.end(); ++bit_sizes_it) { if (bit_sizes_it + 1 != bit_sizes.end()) { if (bitpos == endpos) break; bit = *bitpos; bitpos++; } else { bit = 0; } if (bit) { val += (1 << *bit_sizes_it); } else { for (int b = 0; b < *bit_sizes_it; b++) { if (bitpos == endpos) return INVALID; // Reached EOF in mantissa bit = *bitpos; bitpos++; val += bit << (*bit_sizes_it - 1 - b); } return val; } } return INVALID; // Reached EOF in exponent } enum class Instruction : uint32_t { RETURN = 0, JUMP = 1, MATCH = 2, DEFAULT = 3, }; const std::vector<uint8_t> TYPE_BIT_SIZES{0, 0, 1}; Instruction DecodeType(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos) { return Instruction(DecodeBits(bitpos, endpos, 0, TYPE_BIT_SIZES)); } const std::vector<uint8_t> ASN_BIT_SIZES{15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; uint32_t DecodeASN(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos) { return DecodeBits(bitpos, endpos, 1, ASN_BIT_SIZES); } const std::vector<uint8_t> MATCH_BIT_SIZES{1, 2, 3, 4, 5, 6, 7, 8}; uint32_t DecodeMatch(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos) { return DecodeBits(bitpos, endpos, 2, MATCH_BIT_SIZES); } const std::vector<uint8_t> JUMP_BIT_SIZES{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}; uint32_t DecodeJump(std::vector<bool>::const_iterator& bitpos, const std::vector<bool>::const_iterator& endpos) { return DecodeBits(bitpos, endpos, 17, JUMP_BIT_SIZES); } } uint32_t Interpret(const std::vector<bool> &asmap, const std::vector<bool> &ip) { std::vector<bool>::const_iterator pos = asmap.begin(); const std::vector<bool>::const_iterator endpos = asmap.end(); uint8_t bits = ip.size(); uint32_t default_asn = 0; uint32_t jump, match, matchlen; Instruction opcode; while (pos != endpos) { opcode = DecodeType(pos, endpos); if (opcode == Instruction::RETURN) { default_asn = DecodeASN(pos, endpos); if (default_asn == INVALID) break; // ASN straddles EOF return default_asn; } else if (opcode == Instruction::JUMP) { jump = DecodeJump(pos, endpos); if (jump == INVALID) break; // Jump offset straddles EOF if (bits == 0) break; // No input bits left if (int64_t{jump} >= int64_t{endpos - pos}) break; // Jumping past EOF if (ip[ip.size() - bits]) { pos += jump; } bits--; } else if (opcode == Instruction::MATCH) { match = DecodeMatch(pos, endpos); if (match == INVALID) break; // Match bits straddle EOF matchlen = CountBits(match) - 1; if (bits < matchlen) break; // Not enough input bits for (uint32_t bit = 0; bit < matchlen; bit++) { if ((ip[ip.size() - bits]) != ((match >> (matchlen - 1 - bit)) & 1)) { return default_asn; } bits--; } } else if (opcode == Instruction::DEFAULT) { default_asn = DecodeASN(pos, endpos); if (default_asn == INVALID) break; // ASN straddles EOF } else { break; // Instruction straddles EOF } } assert(false); // Reached EOF without RETURN, or aborted (see any of the breaks above) - should have been caught by SanityCheckASMap below return 0; // 0 is not a valid ASN } bool SanityCheckASMap(const std::vector<bool>& asmap, int bits) { const std::vector<bool>::const_iterator begin = asmap.begin(), endpos = asmap.end(); std::vector<bool>::const_iterator pos = begin; std::vector<std::pair<uint32_t, int>> jumps; // All future positions we may jump to (bit offset in asmap -> bits to consume left) jumps.reserve(bits); Instruction prevopcode = Instruction::JUMP; bool had_incomplete_match = false; while (pos != endpos) { uint32_t offset = pos - begin; if (!jumps.empty() && offset >= jumps.back().first) return false; // There was a jump into the middle of the previous instruction Instruction opcode = DecodeType(pos, endpos); if (opcode == Instruction::RETURN) { if (prevopcode == Instruction::DEFAULT) return false; // There should not be any RETURN immediately after a DEFAULT (could be combined into just RETURN) uint32_t asn = DecodeASN(pos, endpos); if (asn == INVALID) return false; // ASN straddles EOF if (jumps.empty()) { // Nothing to execute anymore if (endpos - pos > 7) return false; // Excessive padding while (pos != endpos) { if (*pos) return false; // Nonzero padding bit ++pos; } return true; // Sanely reached EOF } else { // Continue by pretending we jumped to the next instruction offset = pos - begin; if (offset != jumps.back().first) return false; // Unreachable code bits = jumps.back().second; // Restore the number of bits we would have had left after this jump jumps.pop_back(); prevopcode = Instruction::JUMP; } } else if (opcode == Instruction::JUMP) { uint32_t jump = DecodeJump(pos, endpos); if (jump == INVALID) return false; // Jump offset straddles EOF if (int64_t{jump} > int64_t{endpos - pos}) return false; // Jump out of range if (bits == 0) return false; // Consuming bits past the end of the input --bits; uint32_t jump_offset = pos - begin + jump; if (!jumps.empty() && jump_offset >= jumps.back().first) return false; // Intersecting jumps jumps.emplace_back(jump_offset, bits); prevopcode = Instruction::JUMP; } else if (opcode == Instruction::MATCH) { uint32_t match = DecodeMatch(pos, endpos); if (match == INVALID) return false; // Match bits straddle EOF int matchlen = CountBits(match) - 1; if (prevopcode != Instruction::MATCH) had_incomplete_match = false; if (matchlen < 8 && had_incomplete_match) return false; // Within a sequence of matches only at most one should be incomplete had_incomplete_match = (matchlen < 8); if (bits < matchlen) return false; // Consuming bits past the end of the input bits -= matchlen; prevopcode = Instruction::MATCH; } else if (opcode == Instruction::DEFAULT) { if (prevopcode == Instruction::DEFAULT) return false; // There should not be two successive DEFAULTs (they could be combined into one) uint32_t asn = DecodeASN(pos, endpos); if (asn == INVALID) return false; // ASN straddles EOF prevopcode = Instruction::DEFAULT; } else { return false; // Instruction straddles EOF } } return false; // Reached EOF without RETURN instruction } std::vector<bool> DecodeAsmap(fs::path path) { std::vector<bool> bits; FILE *filestr = fsbridge::fopen(path, "rb"); AutoFile file{filestr}; if (file.IsNull()) { LogPrintf("Failed to open asmap file from disk\n"); return bits; } fseek(filestr, 0, SEEK_END); int length = ftell(filestr); LogPrintf("Opened asmap file %s (%d bytes) from disk\n", fs::quoted(fs::PathToString(path)), length); fseek(filestr, 0, SEEK_SET); uint8_t cur_byte; for (int i = 0; i < length; ++i) { file >> cur_byte; for (int bit = 0; bit < 8; ++bit) { bits.push_back((cur_byte >> bit) & 1); } } if (!SanityCheckASMap(bits, 128)) { LogPrintf("Sanity check of asmap file %s failed\n", fs::quoted(fs::PathToString(path))); return {}; } return bits; }
0
bitcoin/src
bitcoin/src/util/any.h
// Copyright (c) 2023 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_UTIL_ANY_H #define BITCOIN_UTIL_ANY_H #include <any> namespace util { /** * Helper function to access the contained object of a std::any instance. * Returns a pointer to the object if passed instance has a value and the type * matches, nullptr otherwise. */ template<typename T> T* AnyPtr(const std::any& any) noexcept { T* const* ptr = std::any_cast<T*>(&any); return ptr ? *ptr : nullptr; } } // namespace util #endif // BITCOIN_UTIL_ANY_H
0
bitcoin/src
bitcoin/src/util/fs.h
// Copyright (c) 2017-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. #ifndef BITCOIN_UTIL_FS_H #define BITCOIN_UTIL_FS_H #include <tinyformat.h> #include <cstdio> #include <filesystem> // IWYU pragma: export #include <functional> #include <iomanip> #include <ios> #include <ostream> #include <string> #include <system_error> #include <type_traits> #include <utility> /** Filesystem operations and types */ namespace fs { using namespace std::filesystem; /** * Path class wrapper to block calls to the fs::path(std::string) implicit * constructor and the fs::path::string() method, which have unsafe and * unpredictable behavior on Windows (see implementation note in * \ref PathToString for details) */ class path : public std::filesystem::path { public: using std::filesystem::path::path; // Allow path objects arguments for compatibility. path(std::filesystem::path path) : std::filesystem::path::path(std::move(path)) {} path& operator=(std::filesystem::path path) { std::filesystem::path::operator=(std::move(path)); return *this; } path& operator/=(const std::filesystem::path& path) { std::filesystem::path::operator/=(path); return *this; } // Allow literal string arguments, which are safe as long as the literals are ASCII. path(const char* c) : std::filesystem::path(c) {} path& operator=(const char* c) { std::filesystem::path::operator=(c); return *this; } path& operator/=(const char* c) { std::filesystem::path::operator/=(c); return *this; } path& append(const char* c) { std::filesystem::path::append(c); return *this; } // Disallow std::string arguments to avoid locale-dependent decoding on windows. path(std::string) = delete; path& operator=(std::string) = delete; path& operator/=(std::string) = delete; path& append(std::string) = delete; // Disallow std::string conversion method to avoid locale-dependent encoding on windows. std::string string() const = delete; /** * Return a UTF-8 representation of the path as a std::string, for * compatibility with code using std::string. For code using the newer * std::u8string type, it is more efficient to call the inherited * std::filesystem::path::u8string method instead. */ std::string utf8string() const { const std::u8string& utf8_str{std::filesystem::path::u8string()}; return std::string{utf8_str.begin(), utf8_str.end()}; } // Required for path overloads in <fstream>. // See https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=96e0367ead5d8dcac3bec2865582e76e2fbab190 path& make_preferred() { std::filesystem::path::make_preferred(); return *this; } path filename() const { return std::filesystem::path::filename(); } }; static inline path u8path(const std::string& utf8_str) { return std::filesystem::path(std::u8string{utf8_str.begin(), utf8_str.end()}); } // Disallow implicit std::string conversion for absolute to avoid // locale-dependent encoding on windows. static inline path absolute(const path& p) { return std::filesystem::absolute(p); } // Disallow implicit std::string conversion for exists to avoid // locale-dependent encoding on windows. static inline bool exists(const path& p) { return std::filesystem::exists(p); } // Allow explicit quoted stream I/O. static inline auto quoted(const std::string& s) { return std::quoted(s, '"', '&'); } // Allow safe path append operations. static inline path operator/(path p1, const path& p2) { p1 /= p2; return p1; } static inline path operator/(path p1, const char* p2) { p1 /= p2; return p1; } static inline path operator+(path p1, const char* p2) { p1 += p2; return p1; } static inline path operator+(path p1, path::value_type p2) { p1 += p2; return p1; } // Disallow unsafe path append operations. template<typename T> static inline path operator/(path p1, T p2) = delete; template<typename T> static inline path operator+(path p1, T p2) = delete; // Disallow implicit std::string conversion for copy_file // to avoid locale-dependent encoding on Windows. static inline bool copy_file(const path& from, const path& to, copy_options options) { return std::filesystem::copy_file(from, to, options); } /** * Convert path object to a byte string. On POSIX, paths natively are byte * strings, so this is trivial. On Windows, paths natively are Unicode, so an * encoding step is necessary. The inverse of \ref PathToString is \ref * PathFromString. The strings returned and parsed by these functions can be * used to call POSIX APIs, and for roundtrip conversion, logging, and * debugging. * * Because \ref PathToString and \ref PathFromString functions don't specify an * encoding, they are meant to be used internally, not externally. They are not * appropriate to use in applications requiring UTF-8, where * fs::path::u8string() / fs::path::utf8string() and fs::u8path() methods should be used instead. Other * applications could require still different encodings. For example, JSON, XML, * or URI applications might prefer to use higher-level escapes (\uXXXX or * &XXXX; or %XX) instead of multibyte encoding. Rust, Python, Java applications * may require encoding paths with their respective UTF-8 derivatives WTF-8, * PEP-383, and CESU-8 (see https://en.wikipedia.org/wiki/UTF-8#Derivatives). */ static inline std::string PathToString(const path& path) { // Implementation note: On Windows, the std::filesystem::path(string) // constructor and std::filesystem::path::string() method are not safe to // use here, because these methods encode the path using C++'s narrow // multibyte encoding, which on Windows corresponds to the current "code // page", which is unpredictable and typically not able to represent all // valid paths. So fs::path::utf8string() and // fs::u8path() functions are used instead on Windows. On // POSIX, u8string/utf8string/u8path functions are not safe to use because paths are // not always valid UTF-8, so plain string methods which do not transform // the path there are used. #ifdef WIN32 return path.utf8string(); #else static_assert(std::is_same<path::string_type, std::string>::value, "PathToString not implemented on this platform"); return path.std::filesystem::path::string(); #endif } /** * Convert byte string to path object. Inverse of \ref PathToString. */ static inline path PathFromString(const std::string& string) { #ifdef WIN32 return u8path(string); #else return std::filesystem::path(string); #endif } /** * Create directory (and if necessary its parents), unless the leaf directory * already exists or is a symlink to an existing directory. * This is a temporary workaround for an issue in libstdc++ that has been fixed * upstream [PR101510]. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101510 */ static inline bool create_directories(const std::filesystem::path& p) { if (std::filesystem::is_symlink(p) && std::filesystem::is_directory(p)) { return false; } return std::filesystem::create_directories(p); } /** * This variant is not used. Delete it to prevent it from accidentally working * around the workaround. If it is needed, add a workaround in the same pattern * as above. */ bool create_directories(const std::filesystem::path& p, std::error_code& ec) = delete; } // namespace fs /** Bridge operations to C stdio */ namespace fsbridge { using FopenFn = std::function<FILE*(const fs::path&, const char*)>; FILE *fopen(const fs::path& p, const char *mode); /** * Helper function for joining two paths * * @param[in] base Base path * @param[in] path Path to combine with base * @returns path unchanged if it is an absolute path, otherwise returns base joined with path. Returns base unchanged if path is empty. * @pre Base path must be absolute * @post Returned path will always be absolute */ fs::path AbsPathJoin(const fs::path& base, const fs::path& path); class FileLock { public: FileLock() = delete; FileLock(const FileLock&) = delete; FileLock(FileLock&&) = delete; explicit FileLock(const fs::path& file); ~FileLock(); bool TryLock(); std::string GetReason() { return reason; } private: std::string reason; #ifndef WIN32 int fd = -1; #else void* hFile = (void*)-1; // INVALID_HANDLE_VALUE #endif }; std::string get_filesystem_error_message(const fs::filesystem_error& e); }; // Disallow path operator<< formatting in tinyformat to avoid locale-dependent // encoding on windows. namespace tinyformat { template<> inline void formatValue(std::ostream&, const char*, const char*, int, const std::filesystem::path&) = delete; template<> inline void formatValue(std::ostream&, const char*, const char*, int, const fs::path&) = delete; } // namespace tinyformat #endif // BITCOIN_UTIL_FS_H
0
bitcoin/src
bitcoin/src/util/time.cpp
// Copyright (c) 2009-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. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <compat/compat.h> #include <tinyformat.h> #include <util/time.h> #include <util/check.h> #include <atomic> #include <chrono> #include <ctime> #include <locale> #include <thread> #include <sstream> #include <string> void UninterruptibleSleep(const std::chrono::microseconds& n) { std::this_thread::sleep_for(n); } static std::atomic<int64_t> nMockTime(0); //!< For testing bool ChronoSanityCheck() { // std::chrono::system_clock.time_since_epoch and time_t(0) are not guaranteed // to use the Unix epoch timestamp, prior to C++20, but in practice they almost // certainly will. Any differing behavior will be assumed to be an error, unless // certain platforms prove to consistently deviate, at which point we'll cope // with it by adding offsets. // Create a new clock from time_t(0) and make sure that it represents 0 // seconds from the system_clock's time_since_epoch. Then convert that back // to a time_t and verify that it's the same as before. const time_t time_t_epoch{}; auto clock = std::chrono::system_clock::from_time_t(time_t_epoch); if (std::chrono::duration_cast<std::chrono::seconds>(clock.time_since_epoch()).count() != 0) { return false; } time_t time_val = std::chrono::system_clock::to_time_t(clock); if (time_val != time_t_epoch) { return false; } // Check that the above zero time is actually equal to the known unix timestamp. struct tm epoch; #ifdef HAVE_GMTIME_R if (gmtime_r(&time_val, &epoch) == nullptr) { #else if (gmtime_s(&epoch, &time_val) != 0) { #endif return false; } if ((epoch.tm_sec != 0) || (epoch.tm_min != 0) || (epoch.tm_hour != 0) || (epoch.tm_mday != 1) || (epoch.tm_mon != 0) || (epoch.tm_year != 70)) { return false; } return true; } NodeClock::time_point NodeClock::now() noexcept { const std::chrono::seconds mocktime{nMockTime.load(std::memory_order_relaxed)}; const auto ret{ mocktime.count() ? mocktime : std::chrono::system_clock::now().time_since_epoch()}; assert(ret > 0s); return time_point{ret}; }; void SetMockTime(int64_t nMockTimeIn) { Assert(nMockTimeIn >= 0); nMockTime.store(nMockTimeIn, std::memory_order_relaxed); } void SetMockTime(std::chrono::seconds mock_time_in) { nMockTime.store(mock_time_in.count(), std::memory_order_relaxed); } std::chrono::seconds GetMockTime() { return std::chrono::seconds(nMockTime.load(std::memory_order_relaxed)); } int64_t GetTime() { return GetTime<std::chrono::seconds>().count(); } std::string FormatISO8601DateTime(int64_t nTime) { struct tm ts; time_t time_val = nTime; #ifdef HAVE_GMTIME_R if (gmtime_r(&time_val, &ts) == nullptr) { #else if (gmtime_s(&ts, &time_val) != 0) { #endif return {}; } return strprintf("%04i-%02i-%02iT%02i:%02i:%02iZ", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec); } std::string FormatISO8601Date(int64_t nTime) { struct tm ts; time_t time_val = nTime; #ifdef HAVE_GMTIME_R if (gmtime_r(&time_val, &ts) == nullptr) { #else if (gmtime_s(&ts, &time_val) != 0) { #endif return {}; } return strprintf("%04i-%02i-%02i", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday); } struct timeval MillisToTimeval(int64_t nTimeout) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; return timeout; } struct timeval MillisToTimeval(std::chrono::milliseconds ms) { return MillisToTimeval(count_milliseconds(ms)); }
0
bitcoin/src
bitcoin/src/util/string.h
// 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. #ifndef BITCOIN_UTIL_STRING_H #define BITCOIN_UTIL_STRING_H #include <util/spanparsing.h> #include <array> #include <cstdint> #include <cstring> #include <locale> #include <sstream> #include <string> // IWYU pragma: export #include <string_view> // IWYU pragma: export #include <vector> void ReplaceAll(std::string& in_out, const std::string& search, const std::string& substitute); [[nodiscard]] inline std::vector<std::string> SplitString(std::string_view str, char sep) { return spanparsing::Split<std::string>(str, sep); } [[nodiscard]] inline std::vector<std::string> SplitString(std::string_view str, std::string_view separators) { return spanparsing::Split<std::string>(str, separators); } [[nodiscard]] inline std::string_view TrimStringView(std::string_view str, std::string_view pattern = " \f\n\r\t\v") { std::string::size_type front = str.find_first_not_of(pattern); if (front == std::string::npos) { return {}; } std::string::size_type end = str.find_last_not_of(pattern); return str.substr(front, end - front + 1); } [[nodiscard]] inline std::string TrimString(std::string_view str, std::string_view pattern = " \f\n\r\t\v") { return std::string(TrimStringView(str, pattern)); } [[nodiscard]] inline std::string_view RemovePrefixView(std::string_view str, std::string_view prefix) { if (str.substr(0, prefix.size()) == prefix) { return str.substr(prefix.size()); } return str; } [[nodiscard]] inline std::string RemovePrefix(std::string_view str, std::string_view prefix) { return std::string(RemovePrefixView(str, prefix)); } /** * Join all container items. Typically used to concatenate strings but accepts * containers with elements of any type. * * @param container The items to join * @param separator The separator * @param unary_op Apply this operator to each item */ template <typename C, typename S, typename UnaryOp> auto Join(const C& container, const S& separator, UnaryOp unary_op) { decltype(unary_op(*container.begin())) ret; bool first{true}; for (const auto& item : container) { if (!first) ret += separator; ret += unary_op(item); first = false; } return ret; } template <typename C, typename S> auto Join(const C& container, const S& separator) { return Join(container, separator, [](const auto& i) { return i; }); } /** * Create an unordered multi-line list of items. */ inline std::string MakeUnorderedList(const std::vector<std::string>& items) { return Join(items, "\n", [](const std::string& item) { return "- " + item; }); } /** * Check if a string does not contain any embedded NUL (\0) characters */ [[nodiscard]] inline bool ContainsNoNUL(std::string_view str) noexcept { for (auto c : str) { if (c == 0) return false; } return true; } /** * Locale-independent version of std::to_string */ template <typename T> std::string ToString(const T& t) { std::ostringstream oss; oss.imbue(std::locale::classic()); oss << t; return oss.str(); } /** * Check whether a container begins with the given prefix. */ template <typename T1, size_t PREFIX_LEN> [[nodiscard]] inline bool HasPrefix(const T1& obj, const std::array<uint8_t, PREFIX_LEN>& prefix) { return obj.size() >= PREFIX_LEN && std::equal(std::begin(prefix), std::end(prefix), std::begin(obj)); } #endif // BITCOIN_UTIL_STRING_H
0
bitcoin/src
bitcoin/src/qt/walletframe.h
// Copyright (c) 2011-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_QT_WALLETFRAME_H #define BITCOIN_QT_WALLETFRAME_H #include <QFrame> #include <QMap> class ClientModel; class PlatformStyle; class SendCoinsRecipient; class WalletModel; class WalletView; QT_BEGIN_NAMESPACE class QStackedWidget; QT_END_NAMESPACE /** * A container for embedding all wallet-related * controls into BitcoinGUI. The purpose of this class is to allow future * refinements of the wallet controls with minimal need for further * modifications to BitcoinGUI, thus greatly simplifying merges while * reducing the risk of breaking top-level stuff. */ class WalletFrame : public QFrame { Q_OBJECT public: explicit WalletFrame(const PlatformStyle* platformStyle, QWidget* parent); ~WalletFrame(); void setClientModel(ClientModel *clientModel); bool addView(WalletView* walletView); void setCurrentWallet(WalletModel* wallet_model); void removeWallet(WalletModel* wallet_model); void removeAllWallets(); bool handlePaymentRequest(const SendCoinsRecipient& recipient); void showOutOfSyncWarning(bool fShow); QSize sizeHint() const override { return m_size_hint; } Q_SIGNALS: void createWalletButtonClicked(); void message(const QString& title, const QString& message, unsigned int style); void currentWalletSet(); private: QStackedWidget *walletStack; ClientModel *clientModel; QMap<WalletModel*, WalletView*> mapWalletViews; bool bOutOfSync; const PlatformStyle *platformStyle; const QSize m_size_hint; public: WalletView* currentWalletView() const; WalletModel* currentWalletModel() const; public Q_SLOTS: /** Switch to overview (home) page */ void gotoOverviewPage(); /** Switch to history (transactions) page */ void gotoHistoryPage(); /** Switch to receive coins page */ void gotoReceiveCoinsPage(); /** Switch to send coins page */ void gotoSendCoinsPage(QString addr = ""); /** Show Sign/Verify Message dialog and switch to sign message tab */ void gotoSignMessageTab(QString addr = ""); /** Show Sign/Verify Message dialog and switch to verify message tab */ void gotoVerifyMessageTab(QString addr = ""); /** Load Partially Signed Bitcoin Transaction */ void gotoLoadPSBT(bool from_clipboard = false); /** Encrypt the wallet */ void encryptWallet(); /** Backup the wallet */ void backupWallet(); /** Change encrypted wallet passphrase */ void changePassphrase(); /** Ask for passphrase to unlock wallet temporarily */ void unlockWallet(); /** Show used sending addresses */ void usedSendingAddresses(); /** Show used receiving addresses */ void usedReceivingAddresses(); }; #endif // BITCOIN_QT_WALLETFRAME_H
0
bitcoin/src
bitcoin/src/qt/bitcoinunits.h
// Copyright (c) 2011-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_QT_BITCOINUNITS_H #define BITCOIN_QT_BITCOINUNITS_H #include <consensus/amount.h> #include <QAbstractListModel> #include <QDataStream> #include <QString> // U+2009 THIN SPACE = UTF-8 E2 80 89 #define REAL_THIN_SP_CP 0x2009 #define REAL_THIN_SP_UTF8 "\xE2\x80\x89" // QMessageBox seems to have a bug whereby it doesn't display thin/hair spaces // correctly. Workaround is to display a space in a small font. If you // change this, please test that it doesn't cause the parent span to start // wrapping. #define HTML_HACK_SP "<span style='white-space: nowrap; font-size: 6pt'> </span>" // Define THIN_SP_* variables to be our preferred type of thin space #define THIN_SP_CP REAL_THIN_SP_CP #define THIN_SP_UTF8 REAL_THIN_SP_UTF8 #define THIN_SP_HTML HTML_HACK_SP /** Bitcoin unit definitions. Encapsulates parsing and formatting and serves as list model for drop-down selection boxes. */ class BitcoinUnits: public QAbstractListModel { Q_OBJECT public: explicit BitcoinUnits(QObject *parent); /** Bitcoin units. @note Source: https://en.bitcoin.it/wiki/Units . Please add only sensible ones */ enum class Unit { BTC, mBTC, uBTC, SAT }; Q_ENUM(Unit) enum class SeparatorStyle { NEVER, STANDARD, ALWAYS }; //! @name Static API //! Unit conversion and formatting ///@{ //! Get list of units, for drop-down box static QList<Unit> availableUnits(); //! Long name static QString longName(Unit unit); //! Short name static QString shortName(Unit unit); //! Longer description static QString description(Unit unit); //! Number of Satoshis (1e-8) per unit static qint64 factor(Unit unit); //! Number of decimals left static int decimals(Unit unit); //! Format as string static QString format(Unit unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = SeparatorStyle::STANDARD, bool justify = false); //! Format as string (with unit) static QString formatWithUnit(Unit unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = SeparatorStyle::STANDARD); //! Format as HTML string (with unit) static QString formatHtmlWithUnit(Unit unit, const CAmount& amount, bool plussign = false, SeparatorStyle separators = SeparatorStyle::STANDARD); //! Format as string (with unit) of fixed length to preserve privacy, if it is set. static QString formatWithPrivacy(Unit unit, const CAmount& amount, SeparatorStyle separators, bool privacy); //! Parse string to coin amount static bool parse(Unit unit, const QString& value, CAmount* val_out); //! Gets title for amount column including current display unit if optionsModel reference available */ static QString getAmountColumnTitle(Unit unit); ///@} //! @name AbstractListModel implementation //! List model for unit drop-down selection box. ///@{ enum RoleIndex { /** Unit identifier */ UnitRole = Qt::UserRole }; int rowCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; ///@} static QString removeSpaces(QString text) { text.remove(' '); text.remove(QChar(THIN_SP_CP)); return text; } //! Return maximum number of base units (Satoshis) static CAmount maxMoney(); private: QList<Unit> unitlist; }; typedef BitcoinUnits::Unit BitcoinUnit; QDataStream& operator<<(QDataStream& out, const BitcoinUnit& unit); QDataStream& operator>>(QDataStream& in, BitcoinUnit& unit); #endif // BITCOIN_QT_BITCOINUNITS_H
0
bitcoin/src
bitcoin/src/qt/modaloverlay.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_QT_MODALOVERLAY_H #define BITCOIN_QT_MODALOVERLAY_H #include <QDateTime> #include <QPropertyAnimation> #include <QWidget> //! The required delta of headers to the estimated number of available headers until we show the IBD progress static constexpr int HEADER_HEIGHT_DELTA_SYNC = 24; namespace Ui { class ModalOverlay; } /** Modal overlay to display information about the chain-sync state */ class ModalOverlay : public QWidget { Q_OBJECT public: explicit ModalOverlay(bool enable_wallet, QWidget *parent); ~ModalOverlay(); void tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress); void setKnownBestHeight(int count, const QDateTime& blockDate, bool presync); // will show or hide the modal layer void showHide(bool hide = false, bool userRequested = false); bool isLayerVisible() const { return layerIsVisible; } public Q_SLOTS: void toggleVisibility(); void closeClicked(); Q_SIGNALS: void triggered(bool hidden); protected: bool eventFilter(QObject * obj, QEvent * ev) override; bool event(QEvent* ev) override; private: Ui::ModalOverlay *ui; int bestHeaderHeight{0}; // best known height (based on the headers) QDateTime bestHeaderDate; QVector<QPair<qint64, double> > blockProcessTime; bool layerIsVisible{false}; bool userClosed{false}; QPropertyAnimation m_animation; void UpdateHeaderSyncLabel(); void UpdateHeaderPresyncLabel(int height, const QDateTime& blockDate); }; #endif // BITCOIN_QT_MODALOVERLAY_H
0
bitcoin/src
bitcoin/src/qt/qvalidatedlineedit.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 <qt/qvalidatedlineedit.h> #include <qt/bitcoinaddressvalidator.h> #include <qt/guiconstants.h> QValidatedLineEdit::QValidatedLineEdit(QWidget* parent) : QLineEdit(parent) { connect(this, &QValidatedLineEdit::textChanged, this, &QValidatedLineEdit::markValid); } void QValidatedLineEdit::setText(const QString& text) { QLineEdit::setText(text); checkValidity(); } void QValidatedLineEdit::setValid(bool _valid) { if(_valid == this->valid) { return; } if(_valid) { setStyleSheet(""); } else { setStyleSheet("QValidatedLineEdit { " STYLE_INVALID "}"); } this->valid = _valid; } void QValidatedLineEdit::focusInEvent(QFocusEvent *evt) { // Clear invalid flag on focus setValid(true); QLineEdit::focusInEvent(evt); } void QValidatedLineEdit::focusOutEvent(QFocusEvent *evt) { checkValidity(); QLineEdit::focusOutEvent(evt); } void QValidatedLineEdit::markValid() { // As long as a user is typing ensure we display state as valid setValid(true); } void QValidatedLineEdit::clear() { setValid(true); QLineEdit::clear(); } void QValidatedLineEdit::setEnabled(bool enabled) { if (!enabled) { // A disabled QValidatedLineEdit should be marked valid setValid(true); } else { // Recheck validity when QValidatedLineEdit gets enabled checkValidity(); } QLineEdit::setEnabled(enabled); } void QValidatedLineEdit::checkValidity() { if (text().isEmpty()) { setValid(true); } else if (hasAcceptableInput()) { setValid(true); // Check contents on focus out if (checkValidator) { QString address = text(); int pos = 0; if (checkValidator->validate(address, pos) == QValidator::Acceptable) setValid(true); else setValid(false); } } else setValid(false); Q_EMIT validationDidChange(this); } void QValidatedLineEdit::setCheckValidator(const QValidator *v) { checkValidator = v; checkValidity(); } bool QValidatedLineEdit::isValid() { // use checkValidator in case the QValidatedLineEdit is disabled if (checkValidator) { QString address = text(); int pos = 0; if (checkValidator->validate(address, pos) == QValidator::Acceptable) return true; } return valid; }
0
bitcoin/src
bitcoin/src/qt/bitcoin.qrc
<!DOCTYPE RCC><RCC version="1.0"> <qresource prefix="/icons"> <file alias="bitcoin">res/icons/bitcoin.png</file> <file alias="address-book">res/icons/address-book.png</file> <file alias="send">res/icons/send.png</file> <file alias="connect_0">res/icons/connect0.png</file> <file alias="connect_1">res/icons/connect1.png</file> <file alias="connect_2">res/icons/connect2.png</file> <file alias="connect_3">res/icons/connect3.png</file> <file alias="connect_4">res/icons/connect4.png</file> <file alias="transaction_0">res/icons/transaction0.png</file> <file alias="transaction_confirmed">res/icons/transaction2.png</file> <file alias="transaction_conflicted">res/icons/transaction_conflicted.png</file> <file alias="transaction_1">res/icons/clock1.png</file> <file alias="transaction_2">res/icons/clock2.png</file> <file alias="transaction_3">res/icons/clock3.png</file> <file alias="transaction_4">res/icons/clock4.png</file> <file alias="transaction_5">res/icons/clock5.png</file> <file alias="eye">res/icons/eye.png</file> <file alias="eye_minus">res/icons/eye_minus.png</file> <file alias="eye_plus">res/icons/eye_plus.png</file> <file alias="receiving_addresses">res/icons/receive.png</file> <file alias="editpaste">res/icons/editpaste.png</file> <file alias="editcopy">res/icons/editcopy.png</file> <file alias="add">res/icons/add.png</file> <file alias="edit">res/icons/edit.png</file> <file alias="history">res/icons/history.png</file> <file alias="overview">res/icons/overview.png</file> <file alias="export">res/icons/export.png</file> <file alias="synced">res/icons/synced.png</file> <file alias="remove">res/icons/remove.png</file> <file alias="tx_mined">res/icons/tx_mined.png</file> <file alias="tx_input">res/icons/tx_input.png</file> <file alias="tx_output">res/icons/tx_output.png</file> <file alias="tx_inout">res/icons/tx_inout.png</file> <file alias="lock_closed">res/icons/lock_closed.png</file> <file alias="lock_open">res/icons/lock_open.png</file> <file alias="warning">res/icons/warning.png</file> <file alias="fontbigger">res/icons/fontbigger.png</file> <file alias="fontsmaller">res/icons/fontsmaller.png</file> <file alias="prompticon">res/icons/chevron.png</file> <file alias="transaction_abandoned">res/icons/transaction_abandoned.png</file> <file alias="hd_enabled">res/icons/hd_enabled.png</file> <file alias="hd_disabled">res/icons/hd_disabled.png</file> <file alias="network_disabled">res/icons/network_disabled.png</file> <file alias="proxy">res/icons/proxy.png</file> </qresource> <qresource prefix="/animation"> <file alias="spinner-000">res/animation/spinner-000.png</file> <file alias="spinner-001">res/animation/spinner-001.png</file> <file alias="spinner-002">res/animation/spinner-002.png</file> <file alias="spinner-003">res/animation/spinner-003.png</file> <file alias="spinner-004">res/animation/spinner-004.png</file> <file alias="spinner-005">res/animation/spinner-005.png</file> <file alias="spinner-006">res/animation/spinner-006.png</file> <file alias="spinner-007">res/animation/spinner-007.png</file> <file alias="spinner-008">res/animation/spinner-008.png</file> <file alias="spinner-009">res/animation/spinner-009.png</file> <file alias="spinner-010">res/animation/spinner-010.png</file> <file alias="spinner-011">res/animation/spinner-011.png</file> <file alias="spinner-012">res/animation/spinner-012.png</file> <file alias="spinner-013">res/animation/spinner-013.png</file> <file alias="spinner-014">res/animation/spinner-014.png</file> <file alias="spinner-015">res/animation/spinner-015.png</file> <file alias="spinner-016">res/animation/spinner-016.png</file> <file alias="spinner-017">res/animation/spinner-017.png</file> <file alias="spinner-018">res/animation/spinner-018.png</file> <file alias="spinner-019">res/animation/spinner-019.png</file> <file alias="spinner-020">res/animation/spinner-020.png</file> <file alias="spinner-021">res/animation/spinner-021.png</file> <file alias="spinner-022">res/animation/spinner-022.png</file> <file alias="spinner-023">res/animation/spinner-023.png</file> <file alias="spinner-024">res/animation/spinner-024.png</file> <file alias="spinner-025">res/animation/spinner-025.png</file> <file alias="spinner-026">res/animation/spinner-026.png</file> <file alias="spinner-027">res/animation/spinner-027.png</file> <file alias="spinner-028">res/animation/spinner-028.png</file> <file alias="spinner-029">res/animation/spinner-029.png</file> <file alias="spinner-030">res/animation/spinner-030.png</file> <file alias="spinner-031">res/animation/spinner-031.png</file> <file alias="spinner-032">res/animation/spinner-032.png</file> <file alias="spinner-033">res/animation/spinner-033.png</file> <file alias="spinner-034">res/animation/spinner-034.png</file> <file alias="spinner-035">res/animation/spinner-035.png</file> </qresource> <qresource prefix="/fonts"> <file alias="monospace">res/fonts/RobotoMono-Bold.ttf</file> </qresource> </RCC>
0
bitcoin/src
bitcoin/src/qt/recentrequeststablemodel.h
// Copyright (c) 2011-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_QT_RECENTREQUESTSTABLEMODEL_H #define BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H #include <qt/sendcoinsrecipient.h> #include <string> #include <QAbstractTableModel> #include <QStringList> #include <QDateTime> class WalletModel; class RecentRequestEntry { public: RecentRequestEntry() : nVersion(RecentRequestEntry::CURRENT_VERSION) {} static const int CURRENT_VERSION = 1; int nVersion; int64_t id{0}; QDateTime date; SendCoinsRecipient recipient; SERIALIZE_METHODS(RecentRequestEntry, obj) { unsigned int date_timet; SER_WRITE(obj, date_timet = obj.date.toSecsSinceEpoch()); READWRITE(obj.nVersion, obj.id, date_timet, obj.recipient); SER_READ(obj, obj.date = QDateTime::fromSecsSinceEpoch(date_timet)); } }; class RecentRequestEntryLessThan { public: RecentRequestEntryLessThan(int nColumn, Qt::SortOrder fOrder): column(nColumn), order(fOrder) {} bool operator()(const RecentRequestEntry& left, const RecentRequestEntry& right) const; private: int column; Qt::SortOrder order; }; /** Model for list of recently generated payment requests / bitcoin: URIs. * Part of wallet model. */ class RecentRequestsTableModel: public QAbstractTableModel { Q_OBJECT public: explicit RecentRequestsTableModel(WalletModel *parent); ~RecentRequestsTableModel(); enum ColumnIndex { Date = 0, Label = 1, Message = 2, Amount = 3, NUMBER_OF_COLUMNS }; /** @name Methods overridden from QAbstractTableModel @{*/ int rowCount(const QModelIndex &parent) const override; int columnCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; bool setData(const QModelIndex &index, const QVariant &value, int role) override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; Qt::ItemFlags flags(const QModelIndex &index) const override; void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) override; /*@}*/ const RecentRequestEntry &entry(int row) const { return list[row]; } void addNewRequest(const SendCoinsRecipient &recipient); void addNewRequest(const std::string &recipient); void addNewRequest(RecentRequestEntry &recipient); public Q_SLOTS: void updateDisplayUnit(); private: WalletModel *walletModel; QStringList columns; QList<RecentRequestEntry> list; int64_t nReceiveRequestsMaxId{0}; /** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */ void updateAmountColumnTitle(); /** Gets title for amount column including current display unit if optionsModel reference available. */ QString getAmountTitle(); }; #endif // BITCOIN_QT_RECENTREQUESTSTABLEMODEL_H
0
bitcoin/src
bitcoin/src/qt/walletmodeltransaction.cpp
// Copyright (c) 2011-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. #ifdef HAVE_CONFIG_H #include <config/bitcoin-config.h> #endif #include <qt/walletmodeltransaction.h> #include <policy/policy.h> WalletModelTransaction::WalletModelTransaction(const QList<SendCoinsRecipient>& _recipients) : recipients(_recipients) { } QList<SendCoinsRecipient> WalletModelTransaction::getRecipients() const { return recipients; } CTransactionRef& WalletModelTransaction::getWtx() { return wtx; } void WalletModelTransaction::setWtx(const CTransactionRef& newTx) { wtx = newTx; } unsigned int WalletModelTransaction::getTransactionSize() { return wtx ? GetVirtualTransactionSize(*wtx) : 0; } CAmount WalletModelTransaction::getTransactionFee() const { return fee; } void WalletModelTransaction::setTransactionFee(const CAmount& newFee) { fee = newFee; } void WalletModelTransaction::reassignAmounts(int nChangePosRet) { const CTransaction* walletTransaction = wtx.get(); int i = 0; for (QList<SendCoinsRecipient>::iterator it = recipients.begin(); it != recipients.end(); ++it) { SendCoinsRecipient& rcp = (*it); { if (i == nChangePosRet) i++; rcp.amount = walletTransaction->vout[i].nValue; i++; } } } CAmount WalletModelTransaction::getTotalTransactionAmount() const { CAmount totalTransactionAmount = 0; for (const SendCoinsRecipient &rcp : recipients) { totalTransactionAmount += rcp.amount; } return totalTransactionAmount; }
0
bitcoin/src
bitcoin/src/qt/optionsdialog.h
// 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. #ifndef BITCOIN_QT_OPTIONSDIALOG_H #define BITCOIN_QT_OPTIONSDIALOG_H #include <QDialog> #include <QValidator> class ClientModel; class OptionsModel; class QValidatedLineEdit; QT_BEGIN_NAMESPACE class QDataWidgetMapper; QT_END_NAMESPACE namespace Ui { class OptionsDialog; } /** Proxy address widget validator, checks for a valid proxy address. */ class ProxyAddressValidator : public QValidator { Q_OBJECT public: explicit ProxyAddressValidator(QObject *parent); State validate(QString &input, int &pos) const override; }; /** Preferences dialog. */ class OptionsDialog : public QDialog { Q_OBJECT public: explicit OptionsDialog(QWidget *parent, bool enableWallet); ~OptionsDialog(); enum Tab { TAB_MAIN, TAB_NETWORK, }; void setClientModel(ClientModel* client_model); void setModel(OptionsModel *model); void setMapper(); void setCurrentTab(OptionsDialog::Tab tab); private Q_SLOTS: /* set OK button state (enabled / disabled) */ void setOkButtonState(bool fState); void on_resetButton_clicked(); void on_openBitcoinConfButton_clicked(); void on_okButton_clicked(); void on_cancelButton_clicked(); void on_showTrayIcon_stateChanged(int state); void togglePruneWarning(bool enabled); void showRestartWarning(bool fPersistent = false); void clearStatusLabel(); void updateProxyValidationState(); /* query the networks, for which the default proxy is used */ void updateDefaultProxyNets(); Q_SIGNALS: void proxyIpChecks(QValidatedLineEdit *pUiProxyIp, uint16_t nProxyPort); void quitOnReset(); private: Ui::OptionsDialog *ui; ClientModel* m_client_model{nullptr}; OptionsModel* model{nullptr}; QDataWidgetMapper* mapper{nullptr}; }; #endif // BITCOIN_QT_OPTIONSDIALOG_H
0
bitcoin/src
bitcoin/src/qt/qrimagewidget.h
// Copyright (c) 2011-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_QT_QRIMAGEWIDGET_H #define BITCOIN_QT_QRIMAGEWIDGET_H #include <QImage> #include <QLabel> /* Maximum allowed URI length */ static const int MAX_URI_LENGTH = 255; /* Size of exported QR Code image */ static constexpr int QR_IMAGE_SIZE = 300; static constexpr int QR_IMAGE_TEXT_MARGIN = 10; static constexpr int QR_IMAGE_MARGIN = 2 * QR_IMAGE_TEXT_MARGIN; QT_BEGIN_NAMESPACE class QMenu; QT_END_NAMESPACE /* Label widget for QR code. This image can be dragged, dropped, copied and saved * to disk. */ class QRImageWidget : public QLabel { Q_OBJECT public: explicit QRImageWidget(QWidget *parent = nullptr); bool setQR(const QString& data, const QString& text = ""); QImage exportImage(); public Q_SLOTS: void saveImage(); void copyImage(); protected: virtual void mousePressEvent(QMouseEvent *event) override; virtual void contextMenuEvent(QContextMenuEvent *event) override; private: QMenu* contextMenu{nullptr}; }; #endif // BITCOIN_QT_QRIMAGEWIDGET_H
0
bitcoin/src
bitcoin/src/qt/rpcconsole.h
// 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. #ifndef BITCOIN_QT_RPCCONSOLE_H #define BITCOIN_QT_RPCCONSOLE_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/clientmodel.h> #include <qt/guiutil.h> #include <qt/peertablemodel.h> #include <net.h> #include <QByteArray> #include <QCompleter> #include <QThread> #include <QWidget> class PlatformStyle; class RPCExecutor; class RPCTimerInterface; class WalletModel; namespace interfaces { class Node; } namespace Ui { class RPCConsole; } QT_BEGIN_NAMESPACE class QDateTime; class QMenu; class QItemSelection; QT_END_NAMESPACE /** Local Bitcoin RPC console. */ class RPCConsole: public QWidget { Q_OBJECT public: explicit RPCConsole(interfaces::Node& node, const PlatformStyle *platformStyle, QWidget *parent); ~RPCConsole(); static bool RPCParseCommandLine(interfaces::Node* node, std::string &strResult, const std::string &strCommand, bool fExecute, std::string * const pstrFilteredOut = nullptr, const WalletModel* wallet_model = nullptr); static bool RPCExecuteCommandLine(interfaces::Node& node, std::string &strResult, const std::string &strCommand, std::string * const pstrFilteredOut = nullptr, const WalletModel* wallet_model = nullptr) { return RPCParseCommandLine(&node, strResult, strCommand, true, pstrFilteredOut, wallet_model); } void setClientModel(ClientModel *model = nullptr, int bestblock_height = 0, int64_t bestblock_date = 0, double verification_progress = 0.0); #ifdef ENABLE_WALLET void addWallet(WalletModel* const walletModel); void removeWallet(WalletModel* const walletModel); #endif // ENABLE_WALLET enum MessageClass { MC_ERROR, MC_DEBUG, CMD_REQUEST, CMD_REPLY, CMD_ERROR }; enum class TabTypes { INFO, CONSOLE, GRAPH, PEERS }; std::vector<TabTypes> tabs() const { return {TabTypes::INFO, TabTypes::CONSOLE, TabTypes::GRAPH, TabTypes::PEERS}; } QString tabTitle(TabTypes tab_type) const; QKeySequence tabShortcut(TabTypes tab_type) const; protected: virtual bool eventFilter(QObject* obj, QEvent *event) override; void keyPressEvent(QKeyEvent *) override; void changeEvent(QEvent* e) override; private Q_SLOTS: void on_lineEdit_returnPressed(); void on_tabWidget_currentChanged(int index); /** open the debug.log from the current datadir */ void on_openDebugLogfileButton_clicked(); /** change the time range of the network traffic graph */ void on_sldGraphRange_valueChanged(int value); /** update traffic statistics */ void updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut); void resizeEvent(QResizeEvent *event) override; void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; /** Show custom context menu on Peers tab */ void showPeersTableContextMenu(const QPoint& point); /** Show custom context menu on Bans tab */ void showBanTableContextMenu(const QPoint& point); /** Hides ban table if no bans are present */ void showOrHideBanTableIfRequired(); /** clear the selected node */ void clearSelectedNode(); /** show detailed information on ui about selected node */ void updateDetailWidget(); public Q_SLOTS: void clear(bool keep_prompt = false); void fontBigger(); void fontSmaller(); void setFontSize(int newSize); /** Append the message to the message widget */ void message(int category, const QString &msg) { message(category, msg, false); } void message(int category, const QString &message, bool html); /** Set number of connections shown in the UI */ void setNumConnections(int count); /** Set network state shown in the UI */ void setNetworkActive(bool networkActive); /** Set number of blocks and last block date shown in the UI */ void setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, SyncType synctype); /** Set size (number of transactions and memory usage) of the mempool in the UI */ void setMempoolSize(long numberOfTxs, size_t dynUsage); /** Go forward or back in history */ void browseHistory(int offset); /** Scroll console view to end */ void scrollToEnd(); /** Disconnect a selected node on the Peers tab */ void disconnectSelectedNode(); /** Ban a selected node on the Peers tab */ void banSelectedNode(int bantime); /** Unban a selected node on the Bans tab */ void unbanSelectedNode(); /** set which tab has the focus (is visible) */ void setTabFocus(enum TabTypes tabType); #ifdef ENABLE_WALLET /** Set the current (ie - active) wallet */ void setCurrentWallet(WalletModel* const wallet_model); #endif // ENABLE_WALLET private: struct TranslatedStrings { const QString yes{tr("Yes")}, no{tr("No")}, to{tr("To")}, from{tr("From")}, ban_for{tr("Ban for")}, na{tr("N/A")}, unknown{tr("Unknown")}; } const ts; void startExecutor(); void setTrafficGraphRange(int mins); enum ColumnWidths { ADDRESS_COLUMN_WIDTH = 200, SUBVERSION_COLUMN_WIDTH = 150, PING_COLUMN_WIDTH = 80, BANSUBNET_COLUMN_WIDTH = 200, BANTIME_COLUMN_WIDTH = 250 }; interfaces::Node& m_node; Ui::RPCConsole* const ui; ClientModel *clientModel = nullptr; QStringList history; int historyPtr = 0; QString cmdBeforeBrowsing; QList<NodeId> cachedNodeids; const PlatformStyle* const platformStyle; RPCTimerInterface *rpcTimerInterface = nullptr; QMenu *peersTableContextMenu = nullptr; QMenu *banTableContextMenu = nullptr; int consoleFontSize = 0; QCompleter *autoCompleter = nullptr; QThread thread; RPCExecutor* m_executor{nullptr}; WalletModel* m_last_wallet_model{nullptr}; bool m_is_executing{false}; QByteArray m_peer_widget_header_state; QByteArray m_banlist_widget_header_state; /** Update UI with latest network info from model. */ void updateNetworkState(); /** Helper for the output of a time duration field. Inputs are UNIX epoch times. */ QString TimeDurationField(std::chrono::seconds time_now, std::chrono::seconds time_at_event) const { return time_at_event.count() ? GUIUtil::formatDurationStr(time_now - time_at_event) : tr("Never"); } private Q_SLOTS: void updateAlerts(const QString& warnings); }; #endif // BITCOIN_QT_RPCCONSOLE_H
0
bitcoin/src
bitcoin/src/qt/csvmodelwriter.h
// Copyright (c) 2011-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_QT_CSVMODELWRITER_H #define BITCOIN_QT_CSVMODELWRITER_H #include <QList> #include <QObject> QT_BEGIN_NAMESPACE class QAbstractItemModel; QT_END_NAMESPACE /** Export a Qt table model to a CSV file. This is useful for analyzing or post-processing the data in a spreadsheet. */ class CSVModelWriter : public QObject { Q_OBJECT public: explicit CSVModelWriter(const QString &filename, QObject *parent = nullptr); void setModel(const QAbstractItemModel *model); void addColumn(const QString &title, int column, int role=Qt::EditRole); /** Perform export of the model to CSV. @returns true on success, false otherwise */ bool write(); private: QString filename; const QAbstractItemModel* model{nullptr}; struct Column { QString title; int column; int role; }; QList<Column> columns; }; #endif // BITCOIN_QT_CSVMODELWRITER_H
0
bitcoin/src
bitcoin/src/qt/modaloverlay.cpp
// 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. #include <qt/modaloverlay.h> #include <qt/forms/ui_modaloverlay.h> #include <chainparams.h> #include <qt/guiutil.h> #include <QEasingCurve> #include <QPropertyAnimation> #include <QResizeEvent> ModalOverlay::ModalOverlay(bool enable_wallet, QWidget* parent) : QWidget(parent), ui(new Ui::ModalOverlay), bestHeaderDate(QDateTime()) { ui->setupUi(this); connect(ui->closeButton, &QPushButton::clicked, this, &ModalOverlay::closeClicked); if (parent) { parent->installEventFilter(this); raise(); } blockProcessTime.clear(); setVisible(false); if (!enable_wallet) { ui->infoText->setVisible(false); ui->infoTextStrong->setText(tr("%1 is currently syncing. It will download headers and blocks from peers and validate them until reaching the tip of the block chain.").arg(PACKAGE_NAME)); } m_animation.setTargetObject(this); m_animation.setPropertyName("pos"); m_animation.setDuration(300 /* ms */); m_animation.setEasingCurve(QEasingCurve::OutQuad); } ModalOverlay::~ModalOverlay() { delete ui; } bool ModalOverlay::eventFilter(QObject * obj, QEvent * ev) { if (obj == parent()) { if (ev->type() == QEvent::Resize) { QResizeEvent * rev = static_cast<QResizeEvent*>(ev); resize(rev->size()); if (!layerIsVisible) setGeometry(0, height(), width(), height()); if (m_animation.endValue().toPoint().y() > 0) { m_animation.setEndValue(QPoint(0, height())); } } else if (ev->type() == QEvent::ChildAdded) { raise(); } } return QWidget::eventFilter(obj, ev); } //! Tracks parent widget changes bool ModalOverlay::event(QEvent* ev) { if (ev->type() == QEvent::ParentAboutToChange) { if (parent()) parent()->removeEventFilter(this); } else if (ev->type() == QEvent::ParentChange) { if (parent()) { parent()->installEventFilter(this); raise(); } } return QWidget::event(ev); } void ModalOverlay::setKnownBestHeight(int count, const QDateTime& blockDate, bool presync) { if (!presync && count > bestHeaderHeight) { bestHeaderHeight = count; bestHeaderDate = blockDate; UpdateHeaderSyncLabel(); } if (presync) { UpdateHeaderPresyncLabel(count, blockDate); } } void ModalOverlay::tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress) { QDateTime currentDate = QDateTime::currentDateTime(); // keep a vector of samples of verification progress at height blockProcessTime.push_front(qMakePair(currentDate.toMSecsSinceEpoch(), nVerificationProgress)); // show progress speed if we have more than one sample if (blockProcessTime.size() >= 2) { double progressDelta = 0; double progressPerHour = 0; qint64 timeDelta = 0; qint64 remainingMSecs = 0; double remainingProgress = 1.0 - nVerificationProgress; for (int i = 1; i < blockProcessTime.size(); i++) { QPair<qint64, double> sample = blockProcessTime[i]; // take first sample after 500 seconds or last available one if (sample.first < (currentDate.toMSecsSinceEpoch() - 500 * 1000) || i == blockProcessTime.size() - 1) { progressDelta = blockProcessTime[0].second - sample.second; timeDelta = blockProcessTime[0].first - sample.first; progressPerHour = (progressDelta > 0) ? progressDelta / (double)timeDelta * 1000 * 3600 : 0; remainingMSecs = (progressDelta > 0) ? remainingProgress / progressDelta * timeDelta : -1; break; } } // show progress increase per hour ui->progressIncreasePerH->setText(QString::number(progressPerHour * 100, 'f', 2)+"%"); // show expected remaining time if(remainingMSecs >= 0) { ui->expectedTimeLeft->setText(GUIUtil::formatNiceTimeOffset(remainingMSecs / 1000.0)); } else { ui->expectedTimeLeft->setText(QObject::tr("unknown")); } static const int MAX_SAMPLES = 5000; if (blockProcessTime.count() > MAX_SAMPLES) { blockProcessTime.remove(MAX_SAMPLES, blockProcessTime.count() - MAX_SAMPLES); } } // show the last block date ui->newestBlockDate->setText(blockDate.toString()); // show the percentage done according to nVerificationProgress ui->percentageProgress->setText(QString::number(nVerificationProgress*100, 'f', 2)+"%"); if (!bestHeaderDate.isValid()) // not syncing return; // estimate the number of headers left based on nPowTargetSpacing // and check if the gui is not aware of the best header (happens rarely) int estimateNumHeadersLeft = bestHeaderDate.secsTo(currentDate) / Params().GetConsensus().nPowTargetSpacing; bool hasBestHeader = bestHeaderHeight >= count; // show remaining number of blocks if (estimateNumHeadersLeft < HEADER_HEIGHT_DELTA_SYNC && hasBestHeader) { ui->numberOfBlocksLeft->setText(QString::number(bestHeaderHeight - count)); } else { UpdateHeaderSyncLabel(); ui->expectedTimeLeft->setText(tr("Unknown…")); } } void ModalOverlay::UpdateHeaderSyncLabel() { int est_headers_left = bestHeaderDate.secsTo(QDateTime::currentDateTime()) / Params().GetConsensus().nPowTargetSpacing; ui->numberOfBlocksLeft->setText(tr("Unknown. Syncing Headers (%1, %2%)…").arg(bestHeaderHeight).arg(QString::number(100.0 / (bestHeaderHeight + est_headers_left) * bestHeaderHeight, 'f', 1))); } void ModalOverlay::UpdateHeaderPresyncLabel(int height, const QDateTime& blockDate) { int est_headers_left = blockDate.secsTo(QDateTime::currentDateTime()) / Params().GetConsensus().nPowTargetSpacing; ui->numberOfBlocksLeft->setText(tr("Unknown. Pre-syncing Headers (%1, %2%)…").arg(height).arg(QString::number(100.0 / (height + est_headers_left) * height, 'f', 1))); } void ModalOverlay::toggleVisibility() { showHide(layerIsVisible, true); if (!layerIsVisible) userClosed = true; } void ModalOverlay::showHide(bool hide, bool userRequested) { if ( (layerIsVisible && !hide) || (!layerIsVisible && hide) || (!hide && userClosed && !userRequested)) return; Q_EMIT triggered(hide); if (!isVisible() && !hide) setVisible(true); m_animation.setStartValue(QPoint(0, hide ? 0 : height())); // The eventFilter() updates the endValue if it is required for QEvent::Resize. m_animation.setEndValue(QPoint(0, hide ? height() : 0)); m_animation.start(QAbstractAnimation::KeepWhenStopped); layerIsVisible = !hide; } void ModalOverlay::closeClicked() { showHide(true); userClosed = true; }
0
bitcoin/src
bitcoin/src/qt/sendcoinsrecipient.h
// Copyright (c) 2011-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_QT_SENDCOINSRECIPIENT_H #define BITCOIN_QT_SENDCOINSRECIPIENT_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <consensus/amount.h> #include <serialize.h> #include <string> #include <QString> class SendCoinsRecipient { public: explicit SendCoinsRecipient() : amount(0), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) { } explicit SendCoinsRecipient(const QString &addr, const QString &_label, const CAmount& _amount, const QString &_message): address(addr), label(_label), amount(_amount), message(_message), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) {} // If from an unauthenticated payment request, this is used for storing // the addresses, e.g. address-A<br />address-B<br />address-C. // Info: As we don't need to process addresses in here when using // payment requests, we can abuse it for displaying an address list. // Todo: This is a hack, should be replaced with a cleaner solution! QString address; QString label; CAmount amount; // If from a payment request, this is used for storing the memo QString message; // Keep the payment request around as a serialized string to ensure // load/store is lossless. std::string sPaymentRequest; // Empty if no authentication or invalid signature/cert/etc. QString authenticatedMerchant; bool fSubtractFeeFromAmount; // memory only static const int CURRENT_VERSION = 1; int nVersion; SERIALIZE_METHODS(SendCoinsRecipient, obj) { std::string address_str, label_str, message_str, auth_merchant_str; SER_WRITE(obj, address_str = obj.address.toStdString()); SER_WRITE(obj, label_str = obj.label.toStdString()); SER_WRITE(obj, message_str = obj.message.toStdString()); SER_WRITE(obj, auth_merchant_str = obj.authenticatedMerchant.toStdString()); READWRITE(obj.nVersion, address_str, label_str, obj.amount, message_str, obj.sPaymentRequest, auth_merchant_str); SER_READ(obj, obj.address = QString::fromStdString(address_str)); SER_READ(obj, obj.label = QString::fromStdString(label_str)); SER_READ(obj, obj.message = QString::fromStdString(message_str)); SER_READ(obj, obj.authenticatedMerchant = QString::fromStdString(auth_merchant_str)); } }; #endif // BITCOIN_QT_SENDCOINSRECIPIENT_H
0
bitcoin/src
bitcoin/src/qt/clientmodel.h
// 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. #ifndef BITCOIN_QT_CLIENTMODEL_H #define BITCOIN_QT_CLIENTMODEL_H #include <QObject> #include <QDateTime> #include <atomic> #include <memory> #include <sync.h> #include <uint256.h> class BanTableModel; class CBlockIndex; class OptionsModel; class PeerTableModel; class PeerTableSortProxy; enum class SynchronizationState; namespace interfaces { class Handler; class Node; struct BlockTip; } QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE enum class BlockSource { NONE, DISK, NETWORK, }; enum class SyncType { HEADER_PRESYNC, HEADER_SYNC, BLOCK_SYNC }; enum NumConnections { CONNECTIONS_NONE = 0, CONNECTIONS_IN = (1U << 0), CONNECTIONS_OUT = (1U << 1), CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT), }; /** Model for Bitcoin network client. */ class ClientModel : public QObject { Q_OBJECT public: explicit ClientModel(interfaces::Node& node, OptionsModel *optionsModel, QObject *parent = nullptr); ~ClientModel(); interfaces::Node& node() const { return m_node; } OptionsModel *getOptionsModel(); PeerTableModel *getPeerTableModel(); PeerTableSortProxy* peerTableSortProxy(); BanTableModel *getBanTableModel(); //! Return number of connections, default is in- and outbound (total) int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const; int getNumBlocks() const; uint256 getBestBlockHash() EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex); int getHeaderTipHeight() const; int64_t getHeaderTipTime() const; //! Returns the block source of the current importing/syncing state BlockSource getBlockSource() const; //! Return warnings to be displayed in status bar QString getStatusBarWarnings() const; QString formatFullVersion() const; QString formatSubVersion() const; bool isReleaseVersion() const; QString formatClientStartupTime() const; QString dataDir() const; QString blocksDir() const; bool getProxyInfo(std::string& ip_port) const; // caches for the best header: hash, number of blocks and block time mutable std::atomic<int> cachedBestHeaderHeight; mutable std::atomic<int64_t> cachedBestHeaderTime; mutable std::atomic<int> m_cached_num_blocks{-1}; Mutex m_cached_tip_mutex; uint256 m_cached_tip_blocks GUARDED_BY(m_cached_tip_mutex){}; private: interfaces::Node& m_node; std::unique_ptr<interfaces::Handler> m_handler_show_progress; std::unique_ptr<interfaces::Handler> m_handler_notify_num_connections_changed; std::unique_ptr<interfaces::Handler> m_handler_notify_network_active_changed; std::unique_ptr<interfaces::Handler> m_handler_notify_alert_changed; std::unique_ptr<interfaces::Handler> m_handler_banned_list_changed; std::unique_ptr<interfaces::Handler> m_handler_notify_block_tip; std::unique_ptr<interfaces::Handler> m_handler_notify_header_tip; OptionsModel *optionsModel; PeerTableModel* peerTableModel{nullptr}; PeerTableSortProxy* m_peer_table_sort_proxy{nullptr}; BanTableModel* banTableModel{nullptr}; //! A thread to interact with m_node asynchronously QThread* const m_thread; void TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype) EXCLUSIVE_LOCKS_REQUIRED(!m_cached_tip_mutex); void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); Q_SIGNALS: void numConnectionsChanged(int count); void numBlocksChanged(int count, const QDateTime& blockDate, double nVerificationProgress, SyncType header, SynchronizationState sync_state); void mempoolSizeChanged(long count, size_t mempoolSizeInBytes); void networkActiveChanged(bool networkActive); void alertsChanged(const QString &warnings); void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut); //! Fired when a message should be reported to the user void message(const QString &title, const QString &message, unsigned int style); // Show progress dialog e.g. for verifychain void showProgress(const QString &title, int nProgress); }; #endif // BITCOIN_QT_CLIENTMODEL_H
0
bitcoin/src
bitcoin/src/qt/signverifymessagedialog.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 <qt/signverifymessagedialog.h> #include <qt/forms/ui_signverifymessagedialog.h> #include <qt/addressbookpage.h> #include <qt/guiutil.h> #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <key_io.h> #include <util/message.h> // For MessageSign(), MessageVerify() #include <wallet/wallet.h> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(const PlatformStyle *_platformStyle, QWidget *parent) : QDialog(parent, GUIUtil::dialog_flags), ui(new Ui::SignVerifyMessageDialog), platformStyle(_platformStyle) { ui->setupUi(this); ui->addressBookButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/address-book")); ui->pasteButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/editpaste")); ui->copySignatureButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy")); ui->signMessageButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/edit")); ui->clearButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->addressBookButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/address-book")); ui->verifyMessageButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/transaction_0")); ui->clearButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::fixedPitchFont()); ui->signatureIn_VM->setFont(GUIUtil::fixedPitchFont()); GUIUtil::handleCloseWindowShortcut(this); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *_model) { this->model = _model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { model->refresh(/*pk_hash_only=*/true); AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { if (!model) return; /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CTxDestination destination = DecodeDestination(ui->addressIn_SM->text().toStdString()); if (!IsValidDestination(destination)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } const PKHash* pkhash = std::get_if<PKHash>(&destination); if (!pkhash) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } const std::string& message = ui->messageIn_SM->document()->toPlainText().toStdString(); std::string signature; SigningResult res = model->wallet().signMessage(message, *pkhash, signature); QString error; switch (res) { case SigningResult::OK: error = tr("No error"); break; case SigningResult::PRIVATE_KEY_NOT_AVAILABLE: error = tr("Private key for the entered address is not available."); break; case SigningResult::SIGNING_FAILED: error = tr("Message signing failed."); break; // no default case, so the compiler can warn about missing cases } if (res != SigningResult::OK) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + error + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(signature)); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { GUIUtil::setClipboard(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { const std::string& address = ui->addressIn_VM->text().toStdString(); const std::string& signature = ui->signatureIn_VM->text().toStdString(); const std::string& message = ui->messageIn_VM->document()->toPlainText().toStdString(); const auto result = MessageVerify(address, signature, message); if (result == MessageVerificationResult::OK) { ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); } else { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); } switch (result) { case MessageVerificationResult::OK: ui->statusLabel_VM->setText( QString("<nobr>") + tr("Message verified.") + QString("</nobr>") ); return; case MessageVerificationResult::ERR_INVALID_ADDRESS: ui->statusLabel_VM->setText( tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.") ); return; case MessageVerificationResult::ERR_ADDRESS_NO_KEY: ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setText( tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.") ); return; case MessageVerificationResult::ERR_MALFORMED_SIGNATURE: ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setText( tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.") ); return; case MessageVerificationResult::ERR_PUBKEY_NOT_RECOVERED: ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setText( tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.") ); return; case MessageVerificationResult::ERR_NOT_SIGNED: ui->statusLabel_VM->setText( QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>") ); return; } } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); } void SignVerifyMessageDialog::changeEvent(QEvent* e) { if (e->type() == QEvent::PaletteChange) { ui->addressBookButton_SM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/address-book"))); ui->pasteButton_SM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/editpaste"))); ui->copySignatureButton_SM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/editcopy"))); ui->signMessageButton_SM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/edit"))); ui->clearButton_SM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove"))); ui->addressBookButton_VM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/address-book"))); ui->verifyMessageButton_VM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/transaction_0"))); ui->clearButton_VM->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove"))); } QDialog::changeEvent(e); }
0
bitcoin/src
bitcoin/src/qt/bitcoin_locale.qrc
<!DOCTYPE RCC><RCC version="1.0"> <qresource prefix="/translations"> <file alias="am">locale/bitcoin_am.qm</file> <file alias="ar">locale/bitcoin_ar.qm</file> <file alias="az">locale/bitcoin_az.qm</file> <file alias="az@latin">locale/[email protected]</file> <file alias="be">locale/bitcoin_be.qm</file> <file alias="bg">locale/bitcoin_bg.qm</file> <file alias="bn">locale/bitcoin_bn.qm</file> <file alias="br">locale/bitcoin_br.qm</file> <file alias="bs">locale/bitcoin_bs.qm</file> <file alias="ca">locale/bitcoin_ca.qm</file> <file alias="cmn">locale/bitcoin_cmn.qm</file> <file alias="cs">locale/bitcoin_cs.qm</file> <file alias="cy">locale/bitcoin_cy.qm</file> <file alias="da">locale/bitcoin_da.qm</file> <file alias="de">locale/bitcoin_de.qm</file> <file alias="de_AT">locale/bitcoin_de_AT.qm</file> <file alias="de_CH">locale/bitcoin_de_CH.qm</file> <file alias="el">locale/bitcoin_el.qm</file> <file alias="en">locale/bitcoin_en.qm</file> <file alias="eo">locale/bitcoin_eo.qm</file> <file alias="es">locale/bitcoin_es.qm</file> <file alias="es_CL">locale/bitcoin_es_CL.qm</file> <file alias="es_CO">locale/bitcoin_es_CO.qm</file> <file alias="es_DO">locale/bitcoin_es_DO.qm</file> <file alias="es_MX">locale/bitcoin_es_MX.qm</file> <file alias="es_SV">locale/bitcoin_es_SV.qm</file> <file alias="es_VE">locale/bitcoin_es_VE.qm</file> <file alias="et">locale/bitcoin_et.qm</file> <file alias="eu">locale/bitcoin_eu.qm</file> <file alias="fa">locale/bitcoin_fa.qm</file> <file alias="fi">locale/bitcoin_fi.qm</file> <file alias="fil">locale/bitcoin_fil.qm</file> <file alias="fr">locale/bitcoin_fr.qm</file> <file alias="fr_CM">locale/bitcoin_fr_CM.qm</file> <file alias="fr_LU">locale/bitcoin_fr_LU.qm</file> <file alias="ga">locale/bitcoin_ga.qm</file> <file alias="ga_IE">locale/bitcoin_ga_IE.qm</file> <file alias="gd">locale/bitcoin_gd.qm</file> <file alias="gl">locale/bitcoin_gl.qm</file> <file alias="gl_ES">locale/bitcoin_gl_ES.qm</file> <file alias="gu">locale/bitcoin_gu.qm</file> <file alias="ha">locale/bitcoin_ha.qm</file> <file alias="hak">locale/bitcoin_hak.qm</file> <file alias="he">locale/bitcoin_he.qm</file> <file alias="hi">locale/bitcoin_hi.qm</file> <file alias="hr">locale/bitcoin_hr.qm</file> <file alias="hu">locale/bitcoin_hu.qm</file> <file alias="id">locale/bitcoin_id.qm</file> <file alias="is">locale/bitcoin_is.qm</file> <file alias="it">locale/bitcoin_it.qm</file> <file alias="ja">locale/bitcoin_ja.qm</file> <file alias="ka">locale/bitcoin_ka.qm</file> <file alias="kk">locale/bitcoin_kk.qm</file> <file alias="kl">locale/bitcoin_kl.qm</file> <file alias="km">locale/bitcoin_km.qm</file> <file alias="kn">locale/bitcoin_kn.qm</file> <file alias="ko">locale/bitcoin_ko.qm</file> <file alias="ku">locale/bitcoin_ku.qm</file> <file alias="ku_IQ">locale/bitcoin_ku_IQ.qm</file> <file alias="ky">locale/bitcoin_ky.qm</file> <file alias="la">locale/bitcoin_la.qm</file> <file alias="lt">locale/bitcoin_lt.qm</file> <file alias="lv">locale/bitcoin_lv.qm</file> <file alias="mg">locale/bitcoin_mg.qm</file> <file alias="mk">locale/bitcoin_mk.qm</file> <file alias="ml">locale/bitcoin_ml.qm</file> <file alias="mn">locale/bitcoin_mn.qm</file> <file alias="mr">locale/bitcoin_mr.qm</file> <file alias="mr_IN">locale/bitcoin_mr_IN.qm</file> <file alias="ms">locale/bitcoin_ms.qm</file> <file alias="my">locale/bitcoin_my.qm</file> <file alias="nb">locale/bitcoin_nb.qm</file> <file alias="ne">locale/bitcoin_ne.qm</file> <file alias="nl">locale/bitcoin_nl.qm</file> <file alias="no">locale/bitcoin_no.qm</file> <file alias="pa">locale/bitcoin_pa.qm</file> <file alias="pam">locale/bitcoin_pam.qm</file> <file alias="pl">locale/bitcoin_pl.qm</file> <file alias="pt">locale/bitcoin_pt.qm</file> <file alias="pt@qtfiletype">locale/[email protected]</file> <file alias="pt_BR">locale/bitcoin_pt_BR.qm</file> <file alias="ro">locale/bitcoin_ro.qm</file> <file alias="ru">locale/bitcoin_ru.qm</file> <file alias="sc">locale/bitcoin_sc.qm</file> <file alias="si">locale/bitcoin_si.qm</file> <file alias="sk">locale/bitcoin_sk.qm</file> <file alias="sl">locale/bitcoin_sl.qm</file> <file alias="sn">locale/bitcoin_sn.qm</file> <file alias="so">locale/bitcoin_so.qm</file> <file alias="sq">locale/bitcoin_sq.qm</file> <file alias="sr">locale/bitcoin_sr.qm</file> <file alias="sr@ijekavianlatin">locale/[email protected]</file> <file alias="sr@latin">locale/[email protected]</file> <file alias="sv">locale/bitcoin_sv.qm</file> <file alias="sw">locale/bitcoin_sw.qm</file> <file alias="szl">locale/bitcoin_szl.qm</file> <file alias="ta">locale/bitcoin_ta.qm</file> <file alias="te">locale/bitcoin_te.qm</file> <file alias="th">locale/bitcoin_th.qm</file> <file alias="tk">locale/bitcoin_tk.qm</file> <file alias="tl">locale/bitcoin_tl.qm</file> <file alias="tr">locale/bitcoin_tr.qm</file> <file alias="ug">locale/bitcoin_ug.qm</file> <file alias="uk">locale/bitcoin_uk.qm</file> <file alias="ur">locale/bitcoin_ur.qm</file> <file alias="uz">locale/bitcoin_uz.qm</file> <file alias="uz@Cyrl">locale/[email protected]</file> <file alias="uz@Latn">locale/[email protected]</file> <file alias="vi">locale/bitcoin_vi.qm</file> <file alias="yo">locale/bitcoin_yo.qm</file> <file alias="yue">locale/bitcoin_yue.qm</file> <file alias="zh-Hans">locale/bitcoin_zh-Hans.qm</file> <file alias="zh-Hant">locale/bitcoin_zh-Hant.qm</file> <file alias="zh">locale/bitcoin_zh.qm</file> <file alias="zh_CN">locale/bitcoin_zh_CN.qm</file> <file alias="zh_HK">locale/bitcoin_zh_HK.qm</file> <file alias="zh_TW">locale/bitcoin_zh_TW.qm</file> <file alias="zu">locale/bitcoin_zu.qm</file> </qresource> </RCC>
0
bitcoin/src
bitcoin/src/qt/utilitydialog.h
// Copyright (c) 2011-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_QT_UTILITYDIALOG_H #define BITCOIN_QT_UTILITYDIALOG_H #include <QDialog> #include <QWidget> QT_BEGIN_NAMESPACE class QMainWindow; QT_END_NAMESPACE namespace Ui { class HelpMessageDialog; } /** "Help message" dialog box */ class HelpMessageDialog : public QDialog { Q_OBJECT public: explicit HelpMessageDialog(QWidget *parent, bool about); ~HelpMessageDialog(); void printToConsole(); void showOrPrint(); private: Ui::HelpMessageDialog *ui; QString text; private Q_SLOTS: void on_okButton_accepted(); }; /** "Shutdown" window */ class ShutdownWindow : public QWidget { Q_OBJECT public: explicit ShutdownWindow(QWidget *parent=nullptr, Qt::WindowFlags f=Qt::Widget); static QWidget* showShutdownWindow(QMainWindow* window); protected: void closeEvent(QCloseEvent *event) override; }; #endif // BITCOIN_QT_UTILITYDIALOG_H
0
bitcoin/src
bitcoin/src/qt/openuridialog.h
// Copyright (c) 2011-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_QT_OPENURIDIALOG_H #define BITCOIN_QT_OPENURIDIALOG_H #include <QDialog> class PlatformStyle; namespace Ui { class OpenURIDialog; } class OpenURIDialog : public QDialog { Q_OBJECT public: explicit OpenURIDialog(const PlatformStyle* platformStyle, QWidget* parent); ~OpenURIDialog(); QString getURI(); protected Q_SLOTS: void accept() override; void changeEvent(QEvent* e) override; private: Ui::OpenURIDialog* ui; const PlatformStyle* m_platform_style; }; #endif // BITCOIN_QT_OPENURIDIALOG_H
0
bitcoin/src
bitcoin/src/qt/addresstablemodel.h
// Copyright (c) 2011-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_QT_ADDRESSTABLEMODEL_H #define BITCOIN_QT_ADDRESSTABLEMODEL_H #include <optional> #include <QAbstractTableModel> #include <QStringList> enum class OutputType; class AddressTablePriv; class WalletModel; namespace interfaces { class Wallet; } namespace wallet { enum class AddressPurpose; } // namespace wallet /** Qt model of the address book in the core. This allows views to access and modify the address book. */ class AddressTableModel : public QAbstractTableModel { Q_OBJECT public: explicit AddressTableModel(WalletModel *parent = nullptr, bool pk_hash_only = false); ~AddressTableModel(); enum ColumnIndex { Label = 0, /**< User specified label */ Address = 1 /**< Bitcoin address */ }; enum RoleIndex { TypeRole = Qt::UserRole /**< Type of address (#Send or #Receive) */ }; /** Return status of edit/insert operation */ enum EditStatus { OK, /**< Everything ok */ NO_CHANGES, /**< No changes were made during edit operation */ INVALID_ADDRESS, /**< Unparseable address */ DUPLICATE_ADDRESS, /**< Address already in address book */ WALLET_UNLOCK_FAILURE, /**< Wallet could not be unlocked to create new receiving address */ KEY_GENERATION_FAILURE /**< Generating a new public key for a receiving address failed */ }; static const QString Send; /**< Specifies send address */ static const QString Receive; /**< Specifies receive address */ /** @name Methods overridden from QAbstractTableModel @{*/ int rowCount(const QModelIndex &parent) const override; int columnCount(const QModelIndex &parent) const override; QVariant data(const QModelIndex &index, int role) const override; bool setData(const QModelIndex &index, const QVariant &value, int role) override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; QModelIndex index(int row, int column, const QModelIndex &parent) const override; bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; Qt::ItemFlags flags(const QModelIndex &index) const override; /*@}*/ /* Add an address to the model. Returns the added address on success, and an empty string otherwise. */ QString addRow(const QString &type, const QString &label, const QString &address, const OutputType address_type); /** Look up label for address in address book, if not found return empty string. */ QString labelForAddress(const QString &address) const; /** Look up purpose for address in address book, if not found return empty string. */ std::optional<wallet::AddressPurpose> purposeForAddress(const QString &address) const; /* Look up row index of an address in the model. Return -1 if not found. */ int lookupAddress(const QString &address) const; EditStatus getEditStatus() const { return editStatus; } OutputType GetDefaultAddressType() const; QString GetWalletDisplayName() const; private: WalletModel* const walletModel; AddressTablePriv *priv = nullptr; QStringList columns; EditStatus editStatus = OK; /** Look up address book data given an address string. */ bool getAddressData(const QString &address, std::string* name, wallet::AddressPurpose* purpose) const; /** Notify listeners that data changed. */ void emitDataChanged(int index); public Q_SLOTS: /* Update address list from core. */ void updateEntry(const QString &address, const QString &label, bool isMine, wallet::AddressPurpose purpose, int status); friend class AddressTablePriv; }; #endif // BITCOIN_QT_ADDRESSTABLEMODEL_H
0
bitcoin/src
bitcoin/src/qt/walletcontroller.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 <qt/walletcontroller.h> #include <qt/askpassphrasedialog.h> #include <qt/clientmodel.h> #include <qt/createwalletdialog.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <external_signer.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <util/string.h> #include <util/threadnames.h> #include <util/translation.h> #include <wallet/wallet.h> #include <algorithm> #include <chrono> #include <QApplication> #include <QMessageBox> #include <QMetaObject> #include <QMutexLocker> #include <QThread> #include <QTimer> #include <QWindow> using wallet::WALLET_FLAG_BLANK_WALLET; using wallet::WALLET_FLAG_DESCRIPTORS; using wallet::WALLET_FLAG_DISABLE_PRIVATE_KEYS; using wallet::WALLET_FLAG_EXTERNAL_SIGNER; WalletController::WalletController(ClientModel& client_model, const PlatformStyle* platform_style, QObject* parent) : QObject(parent) , m_activity_thread(new QThread(this)) , m_activity_worker(new QObject) , m_client_model(client_model) , m_node(client_model.node()) , m_platform_style(platform_style) , m_options_model(client_model.getOptionsModel()) { m_handler_load_wallet = m_node.walletLoader().handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { getOrCreateWallet(std::move(wallet)); }); m_activity_worker->moveToThread(m_activity_thread); m_activity_thread->start(); QTimer::singleShot(0, m_activity_worker, []() { util::ThreadRename("qt-walletctrl"); }); } // Not using the default destructor because not all member types definitions are // available in the header, just forward declared. WalletController::~WalletController() { m_activity_thread->quit(); m_activity_thread->wait(); delete m_activity_worker; } std::map<std::string, bool> WalletController::listWalletDir() const { QMutexLocker locker(&m_mutex); std::map<std::string, bool> wallets; for (const std::string& name : m_node.walletLoader().listWalletDir()) { wallets[name] = false; } for (WalletModel* wallet_model : m_wallets) { auto it = wallets.find(wallet_model->wallet().getWalletName()); if (it != wallets.end()) it->second = true; } return wallets; } void WalletController::closeWallet(WalletModel* wallet_model, QWidget* parent) { QMessageBox box(parent); box.setWindowTitle(tr("Close wallet")); box.setText(tr("Are you sure you wish to close the wallet <i>%1</i>?").arg(GUIUtil::HtmlEscape(wallet_model->getDisplayName()))); box.setInformativeText(tr("Closing the wallet for too long can result in having to resync the entire chain if pruning is enabled.")); box.setStandardButtons(QMessageBox::Yes|QMessageBox::Cancel); box.setDefaultButton(QMessageBox::Yes); if (box.exec() != QMessageBox::Yes) return; // First remove wallet from node. wallet_model->wallet().remove(); // Now release the model. removeAndDeleteWallet(wallet_model); } void WalletController::closeAllWallets(QWidget* parent) { QMessageBox::StandardButton button = QMessageBox::question(parent, tr("Close all wallets"), tr("Are you sure you wish to close all wallets?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes); if (button != QMessageBox::Yes) return; QMutexLocker locker(&m_mutex); for (WalletModel* wallet_model : m_wallets) { wallet_model->wallet().remove(); Q_EMIT walletRemoved(wallet_model); delete wallet_model; } m_wallets.clear(); } WalletModel* WalletController::getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet) { QMutexLocker locker(&m_mutex); // Return model instance if exists. if (!m_wallets.empty()) { std::string name = wallet->getWalletName(); for (WalletModel* wallet_model : m_wallets) { if (wallet_model->wallet().getWalletName() == name) { return wallet_model; } } } // Instantiate model and register it. WalletModel* wallet_model = new WalletModel(std::move(wallet), m_client_model, m_platform_style, nullptr /* required for the following moveToThread() call */); // Move WalletModel object to the thread that created the WalletController // object (GUI main thread), instead of the current thread, which could be // an outside wallet thread or RPC thread sending a LoadWallet notification. // This ensures queued signals sent to the WalletModel object will be // handled on the GUI event loop. wallet_model->moveToThread(thread()); // setParent(parent) must be called in the thread which created the parent object. More details in #18948. QMetaObject::invokeMethod(this, [wallet_model, this] { wallet_model->setParent(this); }, GUIUtil::blockingGUIThreadConnection()); m_wallets.push_back(wallet_model); // WalletModel::startPollBalance needs to be called in a thread managed by // Qt because of startTimer. Considering the current thread can be a RPC // thread, better delegate the calling to Qt with Qt::AutoConnection. const bool called = QMetaObject::invokeMethod(wallet_model, "startPollBalance"); assert(called); connect(wallet_model, &WalletModel::unload, this, [this, wallet_model] { // Defer removeAndDeleteWallet when no modal widget is active. // TODO: remove this workaround by removing usage of QDialog::exec. if (QApplication::activeModalWidget()) { connect(qApp, &QApplication::focusWindowChanged, wallet_model, [this, wallet_model]() { if (!QApplication::activeModalWidget()) { removeAndDeleteWallet(wallet_model); } }, Qt::QueuedConnection); } else { removeAndDeleteWallet(wallet_model); } }, Qt::QueuedConnection); // Re-emit coinsSent signal from wallet model. connect(wallet_model, &WalletModel::coinsSent, this, &WalletController::coinsSent); Q_EMIT walletAdded(wallet_model); return wallet_model; } void WalletController::removeAndDeleteWallet(WalletModel* wallet_model) { // Unregister wallet model. { QMutexLocker locker(&m_mutex); m_wallets.erase(std::remove(m_wallets.begin(), m_wallets.end(), wallet_model)); } Q_EMIT walletRemoved(wallet_model); // Currently this can trigger the unload since the model can hold the last // CWallet shared pointer. delete wallet_model; } WalletControllerActivity::WalletControllerActivity(WalletController* wallet_controller, QWidget* parent_widget) : QObject(wallet_controller) , m_wallet_controller(wallet_controller) , m_parent_widget(parent_widget) { connect(this, &WalletControllerActivity::finished, this, &QObject::deleteLater); } void WalletControllerActivity::showProgressDialog(const QString& title_text, const QString& label_text, bool show_minimized) { auto progress_dialog = new QProgressDialog(m_parent_widget); progress_dialog->setAttribute(Qt::WA_DeleteOnClose); connect(this, &WalletControllerActivity::finished, progress_dialog, &QWidget::close); progress_dialog->setWindowTitle(title_text); progress_dialog->setLabelText(label_text); progress_dialog->setRange(0, 0); progress_dialog->setCancelButton(nullptr); progress_dialog->setWindowModality(Qt::ApplicationModal); GUIUtil::PolishProgressDialog(progress_dialog); // The setValue call forces QProgressDialog to start the internal duration estimation. // See details in https://bugreports.qt.io/browse/QTBUG-47042. progress_dialog->setValue(0); // When requested, launch dialog minimized if (show_minimized) progress_dialog->showMinimized(); } CreateWalletActivity::CreateWalletActivity(WalletController* wallet_controller, QWidget* parent_widget) : WalletControllerActivity(wallet_controller, parent_widget) { m_passphrase.reserve(MAX_PASSPHRASE_SIZE); } CreateWalletActivity::~CreateWalletActivity() { delete m_create_wallet_dialog; delete m_passphrase_dialog; } void CreateWalletActivity::askPassphrase() { m_passphrase_dialog = new AskPassphraseDialog(AskPassphraseDialog::Encrypt, m_parent_widget, &m_passphrase); m_passphrase_dialog->setWindowModality(Qt::ApplicationModal); m_passphrase_dialog->show(); connect(m_passphrase_dialog, &QObject::destroyed, [this] { m_passphrase_dialog = nullptr; }); connect(m_passphrase_dialog, &QDialog::accepted, [this] { createWallet(); }); connect(m_passphrase_dialog, &QDialog::rejected, [this] { Q_EMIT finished(); }); } void CreateWalletActivity::createWallet() { showProgressDialog( //: Title of window indicating the progress of creation of a new wallet. tr("Create Wallet"), /*: Descriptive text of the create wallet progress window which indicates to the user which wallet is currently being created. */ tr("Creating Wallet <b>%1</b>…").arg(m_create_wallet_dialog->walletName().toHtmlEscaped())); std::string name = m_create_wallet_dialog->walletName().toStdString(); uint64_t flags = 0; // Enable descriptors by default. flags |= WALLET_FLAG_DESCRIPTORS; if (m_create_wallet_dialog->isDisablePrivateKeysChecked()) { flags |= WALLET_FLAG_DISABLE_PRIVATE_KEYS; } if (m_create_wallet_dialog->isMakeBlankWalletChecked()) { flags |= WALLET_FLAG_BLANK_WALLET; } if (m_create_wallet_dialog->isExternalSignerChecked()) { flags |= WALLET_FLAG_EXTERNAL_SIGNER; } QTimer::singleShot(500ms, worker(), [this, name, flags] { auto wallet{node().walletLoader().createWallet(name, m_passphrase, flags, m_warning_message)}; if (wallet) { m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(*wallet)); } else { m_error_message = util::ErrorString(wallet); } QTimer::singleShot(500ms, this, &CreateWalletActivity::finish); }); } void CreateWalletActivity::finish() { if (!m_error_message.empty()) { QMessageBox::critical(m_parent_widget, tr("Create wallet failed"), QString::fromStdString(m_error_message.translated)); } else if (!m_warning_message.empty()) { QMessageBox::warning(m_parent_widget, tr("Create wallet warning"), QString::fromStdString(Join(m_warning_message, Untranslated("\n")).translated)); } if (m_wallet_model) Q_EMIT created(m_wallet_model); Q_EMIT finished(); } void CreateWalletActivity::create() { m_create_wallet_dialog = new CreateWalletDialog(m_parent_widget); std::vector<std::unique_ptr<interfaces::ExternalSigner>> signers; try { signers = node().listExternalSigners(); } catch (const std::runtime_error& e) { QMessageBox::critical(nullptr, tr("Can't list signers"), e.what()); } if (signers.size() > 1) { QMessageBox::critical(nullptr, tr("Too many external signers found"), QString::fromStdString("More than one external signer found. Please connect only one at a time.")); signers.clear(); } m_create_wallet_dialog->setSigners(signers); m_create_wallet_dialog->setWindowModality(Qt::ApplicationModal); m_create_wallet_dialog->show(); connect(m_create_wallet_dialog, &QObject::destroyed, [this] { m_create_wallet_dialog = nullptr; }); connect(m_create_wallet_dialog, &QDialog::rejected, [this] { Q_EMIT finished(); }); connect(m_create_wallet_dialog, &QDialog::accepted, [this] { if (m_create_wallet_dialog->isEncryptWalletChecked()) { askPassphrase(); } else { createWallet(); } }); } OpenWalletActivity::OpenWalletActivity(WalletController* wallet_controller, QWidget* parent_widget) : WalletControllerActivity(wallet_controller, parent_widget) { } void OpenWalletActivity::finish() { if (!m_error_message.empty()) { QMessageBox::critical(m_parent_widget, tr("Open wallet failed"), QString::fromStdString(m_error_message.translated)); } else if (!m_warning_message.empty()) { QMessageBox::warning(m_parent_widget, tr("Open wallet warning"), QString::fromStdString(Join(m_warning_message, Untranslated("\n")).translated)); } if (m_wallet_model) Q_EMIT opened(m_wallet_model); Q_EMIT finished(); } void OpenWalletActivity::open(const std::string& path) { QString name = path.empty() ? QString("["+tr("default wallet")+"]") : QString::fromStdString(path); showProgressDialog( //: Title of window indicating the progress of opening of a wallet. tr("Open Wallet"), /*: Descriptive text of the open wallet progress window which indicates to the user which wallet is currently being opened. */ tr("Opening Wallet <b>%1</b>…").arg(name.toHtmlEscaped())); QTimer::singleShot(0, worker(), [this, path] { auto wallet{node().walletLoader().loadWallet(path, m_warning_message)}; if (wallet) { m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(*wallet)); } else { m_error_message = util::ErrorString(wallet); } QTimer::singleShot(0, this, &OpenWalletActivity::finish); }); } LoadWalletsActivity::LoadWalletsActivity(WalletController* wallet_controller, QWidget* parent_widget) : WalletControllerActivity(wallet_controller, parent_widget) { } void LoadWalletsActivity::load(bool show_loading_minimized) { showProgressDialog( //: Title of progress window which is displayed when wallets are being loaded. tr("Load Wallets"), /*: Descriptive text of the load wallets progress window which indicates to the user that wallets are currently being loaded.*/ tr("Loading wallets…"), /*show_minimized=*/show_loading_minimized); QTimer::singleShot(0, worker(), [this] { for (auto& wallet : node().walletLoader().getWallets()) { m_wallet_controller->getOrCreateWallet(std::move(wallet)); } QTimer::singleShot(0, this, [this] { Q_EMIT finished(); }); }); } RestoreWalletActivity::RestoreWalletActivity(WalletController* wallet_controller, QWidget* parent_widget) : WalletControllerActivity(wallet_controller, parent_widget) { } void RestoreWalletActivity::restore(const fs::path& backup_file, const std::string& wallet_name) { QString name = QString::fromStdString(wallet_name); showProgressDialog( //: Title of progress window which is displayed when wallets are being restored. tr("Restore Wallet"), /*: Descriptive text of the restore wallets progress window which indicates to the user that wallets are currently being restored.*/ tr("Restoring Wallet <b>%1</b>…").arg(name.toHtmlEscaped())); QTimer::singleShot(0, worker(), [this, backup_file, wallet_name] { auto wallet{node().walletLoader().restoreWallet(backup_file, wallet_name, m_warning_message)}; if (wallet) { m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(*wallet)); } else { m_error_message = util::ErrorString(wallet); } QTimer::singleShot(0, this, &RestoreWalletActivity::finish); }); } void RestoreWalletActivity::finish() { if (!m_error_message.empty()) { //: Title of message box which is displayed when the wallet could not be restored. QMessageBox::critical(m_parent_widget, tr("Restore wallet failed"), QString::fromStdString(m_error_message.translated)); } else if (!m_warning_message.empty()) { //: Title of message box which is displayed when the wallet is restored with some warning. QMessageBox::warning(m_parent_widget, tr("Restore wallet warning"), QString::fromStdString(Join(m_warning_message, Untranslated("\n")).translated)); } else { //: Title of message box which is displayed when the wallet is successfully restored. QMessageBox::information(m_parent_widget, tr("Restore wallet message"), QString::fromStdString(Untranslated("Wallet restored successfully \n").translated)); } if (m_wallet_model) Q_EMIT restored(m_wallet_model); Q_EMIT finished(); } void MigrateWalletActivity::migrate(WalletModel* wallet_model) { // Warn the user about migration QMessageBox box(m_parent_widget); box.setWindowTitle(tr("Migrate wallet")); box.setText(tr("Are you sure you wish to migrate the wallet <i>%1</i>?").arg(GUIUtil::HtmlEscape(wallet_model->getDisplayName()))); box.setInformativeText(tr("Migrating the wallet will convert this wallet to one or more descriptor wallets. A new wallet backup will need to be made.\n" "If this wallet contains any watchonly scripts, a new wallet will be created which contains those watchonly scripts.\n" "If this wallet contains any solvable but not watched scripts, a different and new wallet will be created which contains those scripts.\n\n" "The migration process will create a backup of the wallet before migrating. This backup file will be named " "<wallet name>-<timestamp>.legacy.bak and can be found in the directory for this wallet. In the event of " "an incorrect migration, the backup can be restored with the \"Restore Wallet\" functionality.")); box.setStandardButtons(QMessageBox::Yes|QMessageBox::Cancel); box.setDefaultButton(QMessageBox::Yes); if (box.exec() != QMessageBox::Yes) return; // Get the passphrase if it is encrypted regardless of it is locked or unlocked. We need the passphrase itself. SecureString passphrase; WalletModel::EncryptionStatus enc_status = wallet_model->getEncryptionStatus(); if (enc_status == WalletModel::EncryptionStatus::Locked || enc_status == WalletModel::EncryptionStatus::Unlocked) { AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, m_parent_widget, &passphrase); dlg.setModel(wallet_model); dlg.exec(); } // GUI needs to remove the wallet so that it can actually be unloaded by migration const std::string name = wallet_model->wallet().getWalletName(); m_wallet_controller->removeAndDeleteWallet(wallet_model); showProgressDialog(tr("Migrate Wallet"), tr("Migrating Wallet <b>%1</b>…").arg(GUIUtil::HtmlEscape(name))); QTimer::singleShot(0, worker(), [this, name, passphrase] { auto res{node().walletLoader().migrateWallet(name, passphrase)}; if (res) { m_success_message = tr("The wallet '%1' was migrated successfully.").arg(GUIUtil::HtmlEscape(res->wallet->getWalletName())); if (res->watchonly_wallet_name) { m_success_message += QChar(' ') + tr("Watchonly scripts have been migrated to a new wallet named '%1'.").arg(GUIUtil::HtmlEscape(res->watchonly_wallet_name.value())); } if (res->solvables_wallet_name) { m_success_message += QChar(' ') + tr("Solvable but not watched scripts have been migrated to a new wallet named '%1'.").arg(GUIUtil::HtmlEscape(res->solvables_wallet_name.value())); } m_wallet_model = m_wallet_controller->getOrCreateWallet(std::move(res->wallet)); } else { m_error_message = util::ErrorString(res); } QTimer::singleShot(0, this, &MigrateWalletActivity::finish); }); } void MigrateWalletActivity::finish() { if (!m_error_message.empty()) { QMessageBox::critical(m_parent_widget, tr("Migration failed"), QString::fromStdString(m_error_message.translated)); } else { QMessageBox::information(m_parent_widget, tr("Migration Successful"), m_success_message); } if (m_wallet_model) Q_EMIT migrated(m_wallet_model); Q_EMIT finished(); }
0
bitcoin/src
bitcoin/src/qt/openuridialog.cpp
// Copyright (c) 2011-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 <qt/openuridialog.h> #include <qt/forms/ui_openuridialog.h> #include <qt/guiutil.h> #include <qt/platformstyle.h> #include <qt/sendcoinsrecipient.h> #include <QAbstractButton> #include <QLineEdit> #include <QUrl> OpenURIDialog::OpenURIDialog(const PlatformStyle* platformStyle, QWidget* parent) : QDialog(parent, GUIUtil::dialog_flags), ui(new Ui::OpenURIDialog), m_platform_style(platformStyle) { ui->setupUi(this); ui->pasteButton->setIcon(m_platform_style->SingleColorIcon(":/icons/editpaste")); QObject::connect(ui->pasteButton, &QAbstractButton::clicked, ui->uriEdit, &QLineEdit::paste); GUIUtil::handleCloseWindowShortcut(this); } OpenURIDialog::~OpenURIDialog() { delete ui; } QString OpenURIDialog::getURI() { return ui->uriEdit->text(); } void OpenURIDialog::accept() { SendCoinsRecipient rcp; if (GUIUtil::parseBitcoinURI(getURI(), &rcp)) { /* Only accept value URIs */ QDialog::accept(); } else { ui->uriEdit->setValid(false); } } void OpenURIDialog::changeEvent(QEvent* e) { if (e->type() == QEvent::PaletteChange) { ui->pasteButton->setIcon(m_platform_style->SingleColorIcon(":/icons/editpaste")); } QDialog::changeEvent(e); }
0
bitcoin/src
bitcoin/src/qt/macos_appnap.mm
// Copyright (c) 2011-2018 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 "macos_appnap.h" #include <AvailabilityMacros.h> #include <Foundation/NSProcessInfo.h> #include <Foundation/Foundation.h> class CAppNapInhibitor::CAppNapImpl { public: ~CAppNapImpl() { if(activityId) enableAppNap(); } void disableAppNap() { if (!activityId) { @autoreleasepool { const NSActivityOptions activityOptions = NSActivityUserInitiatedAllowingIdleSystemSleep & ~(NSActivitySuddenTerminationDisabled | NSActivityAutomaticTerminationDisabled); id processInfo = [NSProcessInfo processInfo]; if ([processInfo respondsToSelector:@selector(beginActivityWithOptions:reason:)]) { activityId = [processInfo beginActivityWithOptions: activityOptions reason:@"Temporarily disable App Nap for bitcoin-qt."]; [activityId retain]; } } } } void enableAppNap() { if(activityId) { @autoreleasepool { id processInfo = [NSProcessInfo processInfo]; if ([processInfo respondsToSelector:@selector(endActivity:)]) [processInfo endActivity:activityId]; [activityId release]; activityId = nil; } } } private: NSObject* activityId; }; CAppNapInhibitor::CAppNapInhibitor() : impl(new CAppNapImpl()) {} CAppNapInhibitor::~CAppNapInhibitor() = default; void CAppNapInhibitor::disableAppNap() { impl->disableAppNap(); } void CAppNapInhibitor::enableAppNap() { impl->enableAppNap(); }
0
bitcoin/src
bitcoin/src/qt/bitcoinunits.cpp
// Copyright (c) 2011-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 <qt/bitcoinunits.h> #include <consensus/amount.h> #include <QStringList> #include <cassert> static constexpr auto MAX_DIGITS_BTC = 16; BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnit> BitcoinUnits::availableUnits() { QList<BitcoinUnit> unitlist; unitlist.append(Unit::BTC); unitlist.append(Unit::mBTC); unitlist.append(Unit::uBTC); unitlist.append(Unit::SAT); return unitlist; } QString BitcoinUnits::longName(Unit unit) { switch (unit) { case Unit::BTC: return QString("BTC"); case Unit::mBTC: return QString("mBTC"); case Unit::uBTC: return QString::fromUtf8("µBTC (bits)"); case Unit::SAT: return QString("Satoshi (sat)"); } // no default case, so the compiler can warn about missing cases assert(false); } QString BitcoinUnits::shortName(Unit unit) { switch (unit) { case Unit::BTC: return longName(unit); case Unit::mBTC: return longName(unit); case Unit::uBTC: return QString("bits"); case Unit::SAT: return QString("sat"); } // no default case, so the compiler can warn about missing cases assert(false); } QString BitcoinUnits::description(Unit unit) { switch (unit) { case Unit::BTC: return QString("Bitcoins"); case Unit::mBTC: return QString("Milli-Bitcoins (1 / 1" THIN_SP_UTF8 "000)"); case Unit::uBTC: return QString("Micro-Bitcoins (bits) (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); case Unit::SAT: return QString("Satoshi (sat) (1 / 100" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); } // no default case, so the compiler can warn about missing cases assert(false); } qint64 BitcoinUnits::factor(Unit unit) { switch (unit) { case Unit::BTC: return 100'000'000; case Unit::mBTC: return 100'000; case Unit::uBTC: return 100; case Unit::SAT: return 1; } // no default case, so the compiler can warn about missing cases assert(false); } int BitcoinUnits::decimals(Unit unit) { switch (unit) { case Unit::BTC: return 8; case Unit::mBTC: return 5; case Unit::uBTC: return 2; case Unit::SAT: return 0; } // no default case, so the compiler can warn about missing cases assert(false); } QString BitcoinUnits::format(Unit unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators, bool justify) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. qint64 n = (qint64)nIn; qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; QString quotient_str = QString::number(quotient); if (justify) { quotient_str = quotient_str.rightJustified(MAX_DIGITS_BTC - num_decimals, ' '); } // Use SI-style thin space separators as these are locale independent and can't be // confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == SeparatorStyle::ALWAYS || (separators == SeparatorStyle::STANDARD && q_size > 4)) for (int i = 3; i < q_size; i += 3) quotient_str.insert(q_size - i, thin_sp); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); if (num_decimals > 0) { qint64 remainder = n_abs % coin; QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); return quotient_str + QString(".") + remainder_str; } else { return quotient_str; } } // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString BitcoinUnits::formatWithUnit(Unit unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + shortName(unit); } QString BitcoinUnits::formatHtmlWithUnit(Unit unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } QString BitcoinUnits::formatWithPrivacy(Unit unit, const CAmount& amount, SeparatorStyle separators, bool privacy) { assert(amount >= 0); QString value; if (privacy) { value = format(unit, 0, false, separators, true).replace('0', '#'); } else { value = format(unit, amount, false, separators, true); } return value + QString(" ") + shortName(unit); } bool BitcoinUnits::parse(Unit unit, const QString& value, CAmount* val_out) { if (value.isEmpty()) { return false; // Refuse to parse invalid unit or empty string } int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if(val_out) { *val_out = retvalue; } return ok; } QString BitcoinUnits::getAmountColumnTitle(Unit unit) { return QObject::tr("Amount") + " (" + shortName(unit) + ")"; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(longName(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant::fromValue(unit); } } return QVariant(); } CAmount BitcoinUnits::maxMoney() { return MAX_MONEY; } namespace { qint8 ToQint8(BitcoinUnit unit) { switch (unit) { case BitcoinUnit::BTC: return 0; case BitcoinUnit::mBTC: return 1; case BitcoinUnit::uBTC: return 2; case BitcoinUnit::SAT: return 3; } // no default case, so the compiler can warn about missing cases assert(false); } BitcoinUnit FromQint8(qint8 num) { switch (num) { case 0: return BitcoinUnit::BTC; case 1: return BitcoinUnit::mBTC; case 2: return BitcoinUnit::uBTC; case 3: return BitcoinUnit::SAT; } assert(false); } } // namespace QDataStream& operator<<(QDataStream& out, const BitcoinUnit& unit) { return out << ToQint8(unit); } QDataStream& operator>>(QDataStream& in, BitcoinUnit& unit) { qint8 input; in >> input; unit = FromQint8(input); return in; }
0
bitcoin/src
bitcoin/src/qt/trafficgraphwidget.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 <interfaces/node.h> #include <qt/trafficgraphwidget.h> #include <qt/clientmodel.h> #include <QPainter> #include <QPainterPath> #include <QColor> #include <QTimer> #include <chrono> #include <cmath> #define DESIRED_SAMPLES 800 #define XMARGIN 10 #define YMARGIN 10 TrafficGraphWidget::TrafficGraphWidget(QWidget* parent) : QWidget(parent), vSamplesIn(), vSamplesOut() { timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &TrafficGraphWidget::updateRates); } void TrafficGraphWidget::setClientModel(ClientModel *model) { clientModel = model; if(model) { nLastBytesIn = model->node().getTotalBytesRecv(); nLastBytesOut = model->node().getTotalBytesSent(); } } std::chrono::minutes TrafficGraphWidget::getGraphRange() const { return m_range; } void TrafficGraphWidget::paintPath(QPainterPath &path, QQueue<float> &samples) { int sampleCount = samples.size(); if(sampleCount > 0) { int h = height() - YMARGIN * 2, w = width() - XMARGIN * 2; int x = XMARGIN + w; path.moveTo(x, YMARGIN + h); for(int i = 0; i < sampleCount; ++i) { x = XMARGIN + w - w * i / DESIRED_SAMPLES; int y = YMARGIN + h - (int)(h * samples.at(i) / fMax); path.lineTo(x, y); } path.lineTo(x, YMARGIN + h); } } void TrafficGraphWidget::paintEvent(QPaintEvent *) { QPainter painter(this); painter.fillRect(rect(), Qt::black); if(fMax <= 0.0f) return; QColor axisCol(Qt::gray); int h = height() - YMARGIN * 2; painter.setPen(axisCol); painter.drawLine(XMARGIN, YMARGIN + h, width() - XMARGIN, YMARGIN + h); // decide what order of magnitude we are int base = std::floor(std::log10(fMax)); float val = std::pow(10.0f, base); const QString units = tr("kB/s"); const float yMarginText = 2.0; // draw lines painter.setPen(axisCol); painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units)); for(float y = val; y < fMax; y += val) { int yy = YMARGIN + h - h * y / fMax; painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy); } // if we drew 3 or fewer lines, break them up at the next lower order of magnitude if(fMax / val <= 3.0f) { axisCol = axisCol.darker(); val = pow(10.0f, base - 1); painter.setPen(axisCol); painter.drawText(XMARGIN, YMARGIN + h - h * val / fMax-yMarginText, QString("%1 %2").arg(val).arg(units)); int count = 1; for(float y = val; y < fMax; y += val, count++) { // don't overwrite lines drawn above if(count % 10 == 0) continue; int yy = YMARGIN + h - h * y / fMax; painter.drawLine(XMARGIN, yy, width() - XMARGIN, yy); } } painter.setRenderHint(QPainter::Antialiasing); if(!vSamplesIn.empty()) { QPainterPath p; paintPath(p, vSamplesIn); painter.fillPath(p, QColor(0, 255, 0, 128)); painter.setPen(Qt::green); painter.drawPath(p); } if(!vSamplesOut.empty()) { QPainterPath p; paintPath(p, vSamplesOut); painter.fillPath(p, QColor(255, 0, 0, 128)); painter.setPen(Qt::red); painter.drawPath(p); } } void TrafficGraphWidget::updateRates() { if(!clientModel) return; quint64 bytesIn = clientModel->node().getTotalBytesRecv(), bytesOut = clientModel->node().getTotalBytesSent(); float in_rate_kilobytes_per_sec = static_cast<float>(bytesIn - nLastBytesIn) / timer->interval(); float out_rate_kilobytes_per_sec = static_cast<float>(bytesOut - nLastBytesOut) / timer->interval(); vSamplesIn.push_front(in_rate_kilobytes_per_sec); vSamplesOut.push_front(out_rate_kilobytes_per_sec); nLastBytesIn = bytesIn; nLastBytesOut = bytesOut; while(vSamplesIn.size() > DESIRED_SAMPLES) { vSamplesIn.pop_back(); } while(vSamplesOut.size() > DESIRED_SAMPLES) { vSamplesOut.pop_back(); } float tmax = 0.0f; for (const float f : vSamplesIn) { if(f > tmax) tmax = f; } for (const float f : vSamplesOut) { if(f > tmax) tmax = f; } fMax = tmax; update(); } void TrafficGraphWidget::setGraphRange(std::chrono::minutes new_range) { m_range = new_range; const auto msecs_per_sample{std::chrono::duration_cast<std::chrono::milliseconds>(m_range) / DESIRED_SAMPLES}; timer->stop(); timer->setInterval(msecs_per_sample); clear(); } void TrafficGraphWidget::clear() { timer->stop(); vSamplesOut.clear(); vSamplesIn.clear(); fMax = 0.0f; if(clientModel) { nLastBytesIn = clientModel->node().getTotalBytesRecv(); nLastBytesOut = clientModel->node().getTotalBytesSent(); } timer->start(); }
0
bitcoin/src
bitcoin/src/qt/addressbookpage.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. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/addressbookpage.h> #include <qt/forms/ui_addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/csvmodelwriter.h> #include <qt/editaddressdialog.h> #include <qt/guiutil.h> #include <qt/platformstyle.h> #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) #include <QRegularExpression> #else #include <QRegExp> #endif class AddressBookSortFilterProxyModel final : public QSortFilterProxyModel { const QString m_type; public: AddressBookSortFilterProxyModel(const QString& type, QObject* parent) : QSortFilterProxyModel(parent) , m_type(type) { setDynamicSortFilter(true); setFilterCaseSensitivity(Qt::CaseInsensitive); setSortCaseSensitivity(Qt::CaseInsensitive); } protected: bool filterAcceptsRow(int row, const QModelIndex& parent) const override { auto model = sourceModel(); auto label = model->index(row, AddressTableModel::Label, parent); if (model->data(label, AddressTableModel::TypeRole).toString() != m_type) { return false; } auto address = model->index(row, AddressTableModel::Address, parent); #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) const auto pattern = filterRegularExpression(); #else const auto pattern = filterRegExp(); #endif return (model->data(address).toString().contains(pattern) || model->data(label).toString().contains(pattern)); } }; AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode _mode, Tabs _tab, QWidget *parent) : QDialog(parent, GUIUtil::dialog_flags), ui(new Ui::AddressBookPage), mode(_mode), tab(_tab) { ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); } else { ui->newAddress->setIcon(platformStyle->SingleColorIcon(":/icons/add")); ui->copyAddress->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy")); ui->deleteAddress->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export")); } if (mode == ForSelection) { switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, &QTableView::doubleClicked, this, &QDialog::accept); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); ui->newAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Bitcoin addresses for receiving payments. Use the 'Create new receiving address' button in the receive tab to create new addresses.\nSigning is only possible with addresses of the type 'legacy'.")); ui->deleteAddress->setVisible(false); ui->newAddress->setVisible(false); break; } // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(tr("&Copy Address"), this, &AddressBookPage::on_copyAddress_clicked); contextMenu->addAction(tr("Copy &Label"), this, &AddressBookPage::onCopyLabelAction); contextMenu->addAction(tr("&Edit"), this, &AddressBookPage::onEditAction); if (tab == SendingTab) { contextMenu->addAction(tr("&Delete"), this, &AddressBookPage::on_deleteAddress_clicked); } connect(ui->tableView, &QWidget::customContextMenuRequested, this, &AddressBookPage::contextualMenu); connect(ui->closeButton, &QPushButton::clicked, this, &QDialog::accept); GUIUtil::handleCloseWindowShortcut(this); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *_model) { this->model = _model; if(!_model) return; auto type = tab == ReceivingTab ? AddressTableModel::Receive : AddressTableModel::Send; proxyModel = new AddressBookSortFilterProxyModel(type, this); proxyModel->setSourceModel(_model); connect(ui->searchLineEdit, &QLineEdit::textChanged, proxyModel, &QSortFilterProxyModel::setFilterWildcard); ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); connect(ui->tableView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &AddressBookPage::selectionChanged); // Select row for newly created address connect(_model, &AddressTableModel::rowsInserted, this, &AddressBookPage::selectNewAddress); selectionChanged(); this->updateWindowsTitleWithWalletName(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; auto dlg = new EditAddressDialog( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg->setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg->loadRow(origIndex.row()); GUIUtil::ShowModalDialogAsynchronously(dlg); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; if (tab == ReceivingTab) { return; } EditAddressDialog dlg(EditAddressDialog::NewSendingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); for (const QModelIndex& index : indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), /*: Expanded name of the CSV file format. See: https://en.wikipedia.org/wiki/Comma-separated_values. */ tr("Comma separated file") + QLatin1String(" (*.csv)"), nullptr); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), /*: An error message. %1 is a stand-in argument for the name of the file we attempted to save to. */ tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } void AddressBookPage::updateWindowsTitleWithWalletName() { const QString walletName = this->model->GetWalletDisplayName(); if (mode == ForEditing) { switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses - %1").arg(walletName)); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses - %1").arg(walletName)); break; } } }
0
bitcoin/src
bitcoin/src/qt/editaddressdialog.h
// Copyright (c) 2011-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_QT_EDITADDRESSDIALOG_H #define BITCOIN_QT_EDITADDRESSDIALOG_H #include <QDialog> class AddressTableModel; namespace Ui { class EditAddressDialog; } QT_BEGIN_NAMESPACE class QDataWidgetMapper; QT_END_NAMESPACE /** Dialog for editing an address and associated information. */ class EditAddressDialog : public QDialog { Q_OBJECT public: enum Mode { NewSendingAddress, EditReceivingAddress, EditSendingAddress }; explicit EditAddressDialog(Mode mode, QWidget *parent = nullptr); ~EditAddressDialog(); void setModel(AddressTableModel *model); void loadRow(int row); QString getAddress() const; void setAddress(const QString &address); public Q_SLOTS: void accept() override; private: bool saveCurrentRow(); /** Return a descriptive string when adding an already-existing address fails. */ QString getDuplicateAddressWarning() const; Ui::EditAddressDialog *ui; QDataWidgetMapper* mapper{nullptr}; Mode mode; AddressTableModel* model{nullptr}; QString address; }; #endif // BITCOIN_QT_EDITADDRESSDIALOG_H
0
bitcoin/src
bitcoin/src/qt/networkstyle.cpp
// Copyright (c) 2014-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 <qt/networkstyle.h> #include <qt/guiconstants.h> #include <tinyformat.h> #include <util/chaintype.h> #include <QApplication> static const struct { const ChainType networkId; const char *appName; const int iconColorHueShift; const int iconColorSaturationReduction; } network_styles[] = { {ChainType::MAIN, QAPP_APP_NAME_DEFAULT, 0, 0}, {ChainType::TESTNET, QAPP_APP_NAME_TESTNET, 70, 30}, {ChainType::SIGNET, QAPP_APP_NAME_SIGNET, 35, 15}, {ChainType::REGTEST, QAPP_APP_NAME_REGTEST, 160, 30}, }; // titleAddText needs to be const char* for tr() NetworkStyle::NetworkStyle(const QString &_appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *_titleAddText): appName(_appName), titleAddText(qApp->translate("SplashScreen", _titleAddText)) { // load pixmap QPixmap pixmap(":/icons/bitcoin"); if(iconColorHueShift != 0 && iconColorSaturationReduction != 0) { // generate QImage from QPixmap QImage img = pixmap.toImage(); int h,s,l,a; // traverse though lines for(int y=0;y<img.height();y++) { QRgb *scL = reinterpret_cast< QRgb *>( img.scanLine( y ) ); // loop through pixels for(int x=0;x<img.width();x++) { // preserve alpha because QColor::getHsl doesn't return the alpha value a = qAlpha(scL[x]); QColor col(scL[x]); // get hue value col.getHsl(&h,&s,&l); // rotate color on RGB color circle // 70° should end up with the typical "testnet" green h+=iconColorHueShift; // change saturation value if(s>iconColorSaturationReduction) { s -= iconColorSaturationReduction; } col.setHsl(h,s,l,a); // set the pixel scL[x] = col.rgba(); } } //convert back to QPixmap pixmap.convertFromImage(img); } appIcon = QIcon(pixmap); trayAndWindowIcon = QIcon(pixmap.scaled(QSize(256,256))); } const NetworkStyle* NetworkStyle::instantiate(const ChainType networkId) { std::string titleAddText = networkId == ChainType::MAIN ? "" : strprintf("[%s]", ChainTypeToString(networkId)); for (const auto& network_style : network_styles) { if (networkId == network_style.networkId) { return new NetworkStyle( network_style.appName, network_style.iconColorHueShift, network_style.iconColorSaturationReduction, titleAddText.c_str()); } } return nullptr; }
0
bitcoin/src
bitcoin/src/qt/macnotificationhandler.mm
// Copyright (c) 2011-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. #include "macnotificationhandler.h" #undef slots #import <objc/runtime.h> #include <Cocoa/Cocoa.h> // Add an obj-c category (extension) to return the expected bundle identifier @implementation NSBundle(returnCorrectIdentifier) - (NSString *)__bundleIdentifier { if (self == [NSBundle mainBundle]) { return @"org.bitcoinfoundation.Bitcoin-Qt"; } else { return [self __bundleIdentifier]; } } @end void MacNotificationHandler::showNotification(const QString &title, const QString &text) { // check if users OS has support for NSUserNotification if(this->hasUserNotificationCenterSupport()) { NSUserNotification* userNotification = [[NSUserNotification alloc] init]; userNotification.title = title.toNSString(); userNotification.informativeText = text.toNSString(); [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification: userNotification]; [userNotification release]; } } bool MacNotificationHandler::hasUserNotificationCenterSupport(void) { Class possibleClass = NSClassFromString(@"NSUserNotificationCenter"); // check if users OS has support for NSUserNotification if(possibleClass!=nil) { return true; } return false; } MacNotificationHandler *MacNotificationHandler::instance() { static MacNotificationHandler *s_instance = nullptr; if (!s_instance) { s_instance = new MacNotificationHandler(); Class aPossibleClass = objc_getClass("NSBundle"); if (aPossibleClass) { // change NSBundle -bundleIdentifier method to return a correct bundle identifier // a bundle identifier is required to use OSXs User Notification Center method_exchangeImplementations(class_getInstanceMethod(aPossibleClass, @selector(bundleIdentifier)), class_getInstanceMethod(aPossibleClass, @selector(__bundleIdentifier))); } } return s_instance; }
0
bitcoin/src
bitcoin/src/qt/receiverequestdialog.h
// Copyright (c) 2011-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_QT_RECEIVEREQUESTDIALOG_H #define BITCOIN_QT_RECEIVEREQUESTDIALOG_H #include <qt/sendcoinsrecipient.h> #include <QDialog> class WalletModel; namespace Ui { class ReceiveRequestDialog; } class ReceiveRequestDialog : public QDialog { Q_OBJECT public: explicit ReceiveRequestDialog(QWidget *parent = nullptr); ~ReceiveRequestDialog(); void setModel(WalletModel *model); void setInfo(const SendCoinsRecipient &info); private Q_SLOTS: void on_btnCopyURI_clicked(); void on_btnCopyAddress_clicked(); void updateDisplayUnit(); private: Ui::ReceiveRequestDialog *ui; WalletModel* model{nullptr}; SendCoinsRecipient info; }; #endif // BITCOIN_QT_RECEIVEREQUESTDIALOG_H
0
bitcoin/src
bitcoin/src/qt/splashscreen.h
// 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. #ifndef BITCOIN_QT_SPLASHSCREEN_H #define BITCOIN_QT_SPLASHSCREEN_H #include <QWidget> #include <memory> class NetworkStyle; namespace interfaces { class Handler; class Node; class Wallet; }; /** Class for the splashscreen with information of the running client. * * @note this is intentionally not a QSplashScreen. Bitcoin Core initialization * can take a long time, and in that case a progress window that cannot be * moved around and minimized has turned out to be frustrating to the user. */ class SplashScreen : public QWidget { Q_OBJECT public: explicit SplashScreen(const NetworkStyle *networkStyle); ~SplashScreen(); void setNode(interfaces::Node& node); protected: void paintEvent(QPaintEvent *event) override; void closeEvent(QCloseEvent *event) override; public Q_SLOTS: /** Show message and progress */ void showMessage(const QString &message, int alignment, const QColor &color); /** Handle wallet load notifications. */ void handleLoadWallet(); protected: bool eventFilter(QObject * obj, QEvent * ev) override; private: /** Connect core signals to splash screen */ void subscribeToCoreSignals(); /** Disconnect core signals to splash screen */ void unsubscribeFromCoreSignals(); /** Initiate shutdown */ void shutdown(); QPixmap pixmap; QString curMessage; QColor curColor; int curAlignment{0}; interfaces::Node* m_node = nullptr; bool m_shutdown = false; std::unique_ptr<interfaces::Handler> m_handler_init_message; std::unique_ptr<interfaces::Handler> m_handler_show_progress; std::unique_ptr<interfaces::Handler> m_handler_init_wallet; std::unique_ptr<interfaces::Handler> m_handler_load_wallet; std::list<std::unique_ptr<interfaces::Wallet>> m_connected_wallets; std::list<std::unique_ptr<interfaces::Handler>> m_connected_wallet_handlers; }; #endif // BITCOIN_QT_SPLASHSCREEN_H
0
bitcoin/src
bitcoin/src/qt/guiutil.h
// 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. #ifndef BITCOIN_QT_GUIUTIL_H #define BITCOIN_QT_GUIUTIL_H #include <consensus/amount.h> #include <net.h> #include <netaddress.h> #include <util/check.h> #include <util/fs.h> #include <QApplication> #include <QEvent> #include <QHeaderView> #include <QItemDelegate> #include <QLabel> #include <QMessageBox> #include <QMetaObject> #include <QObject> #include <QProgressBar> #include <QString> #include <QTableView> #include <cassert> #include <chrono> #include <utility> class PlatformStyle; class QValidatedLineEdit; class SendCoinsRecipient; namespace interfaces { class Node; } QT_BEGIN_NAMESPACE class QAbstractButton; class QAbstractItemView; class QAction; class QDateTime; class QDialog; class QFont; class QKeySequence; class QLineEdit; class QMenu; class QPoint; class QProgressDialog; class QUrl; class QWidget; QT_END_NAMESPACE /** Utility functions used by the Bitcoin Qt UI. */ namespace GUIUtil { // Use this flags to prevent a "What's This" button in the title bar of the dialog on Windows. constexpr auto dialog_flags = Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint; // Create human-readable string from date QString dateTimeStr(const QDateTime &datetime); QString dateTimeStr(qint64 nTime); // Return a monospace font QFont fixedPitchFont(bool use_embedded_font = false); // Set up widget for address void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent); /** * Connects an additional shortcut to a QAbstractButton. Works around the * one shortcut limitation of the button's shortcut property. * @param[in] button QAbstractButton to assign shortcut to * @param[in] shortcut QKeySequence to use as shortcut */ void AddButtonShortcut(QAbstractButton* button, const QKeySequence& shortcut); // Parse "bitcoin:" URI into recipient object, return true on successful parsing bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out); bool parseBitcoinURI(QString uri, SendCoinsRecipient *out); QString formatBitcoinURI(const SendCoinsRecipient &info); // Returns true if given address+amount meets "dust" definition bool isDust(interfaces::Node& node, const QString& address, const CAmount& amount); // HTML escaping for rich text controls QString HtmlEscape(const QString& str, bool fMultiLine=false); QString HtmlEscape(const std::string& str, bool fMultiLine=false); /** Copy a field of the currently selected entry of a view to the clipboard. Does nothing if nothing is selected. @param[in] column Data column to extract from the model @param[in] role Data role to extract from the model @see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress */ void copyEntryData(const QAbstractItemView *view, int column, int role=Qt::EditRole); /** Return a field of the currently selected entry as a QString. Does nothing if nothing is selected. @param[in] column Data column to extract from the model @see TransactionView::copyLabel, TransactionView::copyAmount, TransactionView::copyAddress */ QList<QModelIndex> getEntryData(const QAbstractItemView *view, int column); /** Returns true if the specified field of the currently selected view entry is not empty. @param[in] column Data column to extract from the model @param[in] role Data role to extract from the model @see TransactionView::contextualMenu */ bool hasEntryData(const QAbstractItemView *view, int column, int role); void setClipboard(const QString& str); /** * Loads the font from the file specified by file_name, aborts if it fails. */ void LoadFont(const QString& file_name); /** * Determine default data directory for operating system. */ QString getDefaultDataDirectory(); /** * Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...). * * @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" * @return QString */ QString ExtractFirstSuffixFromFilter(const QString& filter); /** Get save filename, mimics QFileDialog::getSaveFileName, except that it appends a default suffix when no suffix is provided by the user. @param[in] parent Parent window (or 0) @param[in] caption Window caption (or empty, for default) @param[in] dir Starting directory (or empty, to default to documents directory) @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" @param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0). Can be useful when choosing the save file format based on suffix. */ QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut); /** Get open filename, convenience wrapper for QFileDialog::getOpenFileName. @param[in] parent Parent window (or 0) @param[in] caption Window caption (or empty, for default) @param[in] dir Starting directory (or empty, to default to documents directory) @param[in] filter Filter specification such as "Comma Separated Files (*.csv)" @param[out] selectedSuffixOut Pointer to return the suffix (file type) that was selected (or 0). Can be useful when choosing the save file format based on suffix. */ QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut); /** Get connection type to call object slot in GUI thread with invokeMethod. The call will be blocking. @returns If called from the GUI thread, return a Qt::DirectConnection. If called from another thread, return a Qt::BlockingQueuedConnection. */ Qt::ConnectionType blockingGUIThreadConnection(); // Determine whether a widget is hidden behind other windows bool isObscured(QWidget *w); // Activate, show and raise the widget void bringToFront(QWidget* w); // Set shortcut to close window void handleCloseWindowShortcut(QWidget* w); // Open debug.log void openDebugLogfile(); // Open the config file bool openBitcoinConf(); /** Qt event filter that intercepts ToolTipChange events, and replaces the tooltip with a rich text representation if needed. This assures that Qt can word-wrap long tooltip messages. Tooltips longer than the provided size threshold (in characters) are wrapped. */ class ToolTipToRichTextFilter : public QObject { Q_OBJECT public: explicit ToolTipToRichTextFilter(int size_threshold, QObject *parent = nullptr); protected: bool eventFilter(QObject *obj, QEvent *evt) override; private: int size_threshold; }; /** * Qt event filter that intercepts QEvent::FocusOut events for QLabel objects, and * resets their `textInteractionFlags' property to get rid of the visible cursor. * * This is a temporary fix of QTBUG-59514. */ class LabelOutOfFocusEventFilter : public QObject { Q_OBJECT public: explicit LabelOutOfFocusEventFilter(QObject* parent); bool eventFilter(QObject* watched, QEvent* event) override; }; bool GetStartOnSystemStartup(); bool SetStartOnSystemStartup(bool fAutoStart); /** Convert QString to OS specific boost path through UTF-8 */ fs::path QStringToPath(const QString &path); /** Convert OS specific boost path to QString through UTF-8 */ QString PathToQString(const fs::path &path); /** Convert enum Network to QString */ QString NetworkToQString(Network net); /** Convert enum ConnectionType to QString */ QString ConnectionTypeToQString(ConnectionType conn_type, bool prepend_direction); /** Convert seconds into a QString with days, hours, mins, secs */ QString formatDurationStr(std::chrono::seconds dur); /** Convert peer connection time to a QString denominated in the most relevant unit. */ QString FormatPeerAge(std::chrono::seconds time_connected); /** Format CNodeStats.nServices bitmask into a user-readable string */ QString formatServicesStr(quint64 mask); /** Format a CNodeStats.m_last_ping_time into a user-readable string or display N/A, if 0 */ QString formatPingTime(std::chrono::microseconds ping_time); /** Format a CNodeCombinedStats.nTimeOffset into a user-readable string */ QString formatTimeOffset(int64_t nTimeOffset); QString formatNiceTimeOffset(qint64 secs); QString formatBytes(uint64_t bytes); qreal calculateIdealFontSize(int width, const QString& text, QFont font, qreal minPointSize = 4, qreal startPointSize = 14); class ThemedLabel : public QLabel { Q_OBJECT public: explicit ThemedLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr); void setThemedPixmap(const QString& image_filename, int width, int height); protected: void changeEvent(QEvent* e) override; private: const PlatformStyle* m_platform_style; QString m_image_filename; int m_pixmap_width; int m_pixmap_height; void updateThemedPixmap(); }; class ClickableLabel : public ThemedLabel { Q_OBJECT public: explicit ClickableLabel(const PlatformStyle* platform_style, QWidget* parent = nullptr); Q_SIGNALS: /** Emitted when the label is clicked. The relative mouse coordinates of the click are * passed to the signal. */ void clicked(const QPoint& point); protected: void mouseReleaseEvent(QMouseEvent *event) override; }; class ClickableProgressBar : public QProgressBar { Q_OBJECT Q_SIGNALS: /** Emitted when the progressbar is clicked. The relative mouse coordinates of the click are * passed to the signal. */ void clicked(const QPoint& point); protected: void mouseReleaseEvent(QMouseEvent *event) override; }; typedef ClickableProgressBar ProgressBar; class ItemDelegate : public QItemDelegate { Q_OBJECT public: ItemDelegate(QObject* parent) : QItemDelegate(parent) {} Q_SIGNALS: void keyEscapePressed(); private: bool eventFilter(QObject *object, QEvent *event) override; }; // Fix known bugs in QProgressDialog class. void PolishProgressDialog(QProgressDialog* dialog); /** * Returns the distance in pixels appropriate for drawing a subsequent character after text. * * In Qt 5.12 and before the QFontMetrics::width() is used and it is deprecated since Qt 5.13. * In Qt 5.11 the QFontMetrics::horizontalAdvance() was introduced. */ int TextWidth(const QFontMetrics& fm, const QString& text); /** * Writes to debug.log short info about the used Qt and the host system. */ void LogQtInfo(); /** * Call QMenu::popup() only on supported QT_QPA_PLATFORM. */ void PopupMenu(QMenu* menu, const QPoint& point, QAction* at_action = nullptr); /** * Returns the start-moment of the day in local time. * * QDateTime::QDateTime(const QDate& date) is deprecated since Qt 5.15. * QDate::startOfDay() was introduced in Qt 5.14. */ QDateTime StartOfDay(const QDate& date); /** * Returns true if pixmap has been set. * * QPixmap* QLabel::pixmap() is deprecated since Qt 5.15. */ bool HasPixmap(const QLabel* label); QImage GetImage(const QLabel* label); /** * Splits the string into substrings wherever separator occurs, and returns * the list of those strings. Empty strings do not appear in the result. * * QString::split() signature differs in different Qt versions: * - QString::SplitBehavior is deprecated since Qt 5.15 * - Qt::SplitBehavior was introduced in Qt 5.14 * If {QString|Qt}::SkipEmptyParts behavior is required, use this * function instead of QString::split(). */ template <typename SeparatorType> QStringList SplitSkipEmptyParts(const QString& string, const SeparatorType& separator) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) return string.split(separator, Qt::SkipEmptyParts); #else return string.split(separator, QString::SkipEmptyParts); #endif } /** * Replaces a plain text link with an HTML tagged one. */ QString MakeHtmlLink(const QString& source, const QString& link); void PrintSlotException( const std::exception* exception, const QObject* sender, const QObject* receiver); /** * A drop-in replacement of QObject::connect function * (see: https://doc.qt.io/qt-5/qobject.html#connect-3), that * guaranties that all exceptions are handled within the slot. * * NOTE: This function is incompatible with Qt private signals. */ template <typename Sender, typename Signal, typename Receiver, typename Slot> auto ExceptionSafeConnect( Sender sender, Signal signal, Receiver receiver, Slot method, Qt::ConnectionType type = Qt::AutoConnection) { return QObject::connect( sender, signal, receiver, [sender, receiver, method](auto&&... args) { bool ok{true}; try { (receiver->*method)(std::forward<decltype(args)>(args)...); } catch (const NonFatalCheckError& e) { PrintSlotException(&e, sender, receiver); ok = QMetaObject::invokeMethod( qApp, "handleNonFatalException", blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(e.what()))); } catch (const std::exception& e) { PrintSlotException(&e, sender, receiver); ok = QMetaObject::invokeMethod( qApp, "handleRunawayException", blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(e.what()))); } catch (...) { PrintSlotException(nullptr, sender, receiver); ok = QMetaObject::invokeMethod( qApp, "handleRunawayException", blockingGUIThreadConnection(), Q_ARG(QString, "Unknown failure occurred.")); } assert(ok); }, type); } /** * Shows a QDialog instance asynchronously, and deletes it on close. */ void ShowModalDialogAsynchronously(QDialog* dialog); inline bool IsEscapeOrBack(int key) { if (key == Qt::Key_Escape) return true; #ifdef Q_OS_ANDROID if (key == Qt::Key_Back) return true; #endif // Q_OS_ANDROID return false; } } // namespace GUIUtil #endif // BITCOIN_QT_GUIUTIL_H
0
bitcoin/src
bitcoin/src/qt/walletview.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 <qt/walletview.h> #include <qt/addressbookpage.h> #include <qt/askpassphrasedialog.h> #include <qt/clientmodel.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/overviewpage.h> #include <qt/platformstyle.h> #include <qt/receivecoinsdialog.h> #include <qt/sendcoinsdialog.h> #include <qt/signverifymessagedialog.h> #include <qt/transactiontablemodel.h> #include <qt/transactionview.h> #include <qt/walletmodel.h> #include <interfaces/node.h> #include <node/interface_ui.h> #include <util/strencodings.h> #include <QAction> #include <QFileDialog> #include <QHBoxLayout> #include <QProgressDialog> #include <QPushButton> #include <QVBoxLayout> WalletView::WalletView(WalletModel* wallet_model, const PlatformStyle* _platformStyle, QWidget* parent) : QStackedWidget(parent), walletModel(wallet_model), platformStyle(_platformStyle) { assert(walletModel); // Create tabs overviewPage = new OverviewPage(platformStyle); overviewPage->setWalletModel(walletModel); transactionsPage = new QWidget(this); QVBoxLayout *vbox = new QVBoxLayout(); QHBoxLayout *hbox_buttons = new QHBoxLayout(); transactionView = new TransactionView(platformStyle, this); transactionView->setModel(walletModel); vbox->addWidget(transactionView); QPushButton *exportButton = new QPushButton(tr("&Export"), this); exportButton->setToolTip(tr("Export the data in the current tab to a file")); if (platformStyle->getImagesOnButtons()) { exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/export")); } hbox_buttons->addStretch(); hbox_buttons->addWidget(exportButton); vbox->addLayout(hbox_buttons); transactionsPage->setLayout(vbox); receiveCoinsPage = new ReceiveCoinsDialog(platformStyle); receiveCoinsPage->setModel(walletModel); sendCoinsPage = new SendCoinsDialog(platformStyle); sendCoinsPage->setModel(walletModel); usedSendingAddressesPage = new AddressBookPage(platformStyle, AddressBookPage::ForEditing, AddressBookPage::SendingTab, this); usedSendingAddressesPage->setModel(walletModel->getAddressTableModel()); usedReceivingAddressesPage = new AddressBookPage(platformStyle, AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this); usedReceivingAddressesPage->setModel(walletModel->getAddressTableModel()); addWidget(overviewPage); addWidget(transactionsPage); addWidget(receiveCoinsPage); addWidget(sendCoinsPage); connect(overviewPage, &OverviewPage::transactionClicked, this, &WalletView::transactionClicked); // Clicking on a transaction on the overview pre-selects the transaction on the transaction history page connect(overviewPage, &OverviewPage::transactionClicked, transactionView, qOverload<const QModelIndex&>(&TransactionView::focusTransaction)); connect(overviewPage, &OverviewPage::outOfSyncWarningClicked, this, &WalletView::outOfSyncWarningClicked); connect(sendCoinsPage, &SendCoinsDialog::coinsSent, this, &WalletView::coinsSent); // Highlight transaction after send connect(sendCoinsPage, &SendCoinsDialog::coinsSent, transactionView, qOverload<const uint256&>(&TransactionView::focusTransaction)); // Clicking on "Export" allows to export the transaction list connect(exportButton, &QPushButton::clicked, transactionView, &TransactionView::exportClicked); // Pass through messages from sendCoinsPage connect(sendCoinsPage, &SendCoinsDialog::message, this, &WalletView::message); // Pass through messages from transactionView connect(transactionView, &TransactionView::message, this, &WalletView::message); connect(this, &WalletView::setPrivacy, overviewPage, &OverviewPage::setPrivacy); connect(this, &WalletView::setPrivacy, this, &WalletView::disableTransactionView); // Receive and pass through messages from wallet model connect(walletModel, &WalletModel::message, this, &WalletView::message); // Handle changes in encryption status connect(walletModel, &WalletModel::encryptionStatusChanged, this, &WalletView::encryptionStatusChanged); // Balloon pop-up for new transaction connect(walletModel->getTransactionTableModel(), &TransactionTableModel::rowsInserted, this, &WalletView::processNewTransaction); // Ask for passphrase if needed connect(walletModel, &WalletModel::requireUnlock, this, &WalletView::unlockWallet); // Show progress dialog connect(walletModel, &WalletModel::showProgress, this, &WalletView::showProgress); } WalletView::~WalletView() = default; void WalletView::setClientModel(ClientModel *_clientModel) { this->clientModel = _clientModel; overviewPage->setClientModel(_clientModel); sendCoinsPage->setClientModel(_clientModel); walletModel->setClientModel(_clientModel); } void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/) { // Prevent balloon-spam when initial block download is in progress if (!clientModel || clientModel->node().isInitialBlockDownload()) { return; } TransactionTableModel *ttm = walletModel->getTransactionTableModel(); if (!ttm || ttm->processingQueuedTransactions()) return; QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString(); qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong(); QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString(); QModelIndex index = ttm->index(start, 0, parent); QString address = ttm->data(index, TransactionTableModel::AddressRole).toString(); QString label = GUIUtil::HtmlEscape(ttm->data(index, TransactionTableModel::LabelRole).toString()); Q_EMIT incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address, label, GUIUtil::HtmlEscape(walletModel->getWalletName())); } void WalletView::gotoOverviewPage() { setCurrentWidget(overviewPage); } void WalletView::gotoHistoryPage() { setCurrentWidget(transactionsPage); } void WalletView::gotoReceiveCoinsPage() { setCurrentWidget(receiveCoinsPage); } void WalletView::gotoSendCoinsPage(QString addr) { setCurrentWidget(sendCoinsPage); if (!addr.isEmpty()) sendCoinsPage->setAddress(addr); } void WalletView::gotoSignMessageTab(QString addr) { // calls show() in showTab_SM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(platformStyle, this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_SM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_SM(addr); } void WalletView::gotoVerifyMessageTab(QString addr) { // calls show() in showTab_VM() SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(platformStyle, this); signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose); signVerifyMessageDialog->setModel(walletModel); signVerifyMessageDialog->showTab_VM(true); if (!addr.isEmpty()) signVerifyMessageDialog->setAddress_VM(addr); } bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient) { return sendCoinsPage->handlePaymentRequest(recipient); } void WalletView::showOutOfSyncWarning(bool fShow) { overviewPage->showOutOfSyncWarning(fShow); } void WalletView::encryptWallet() { auto dlg = new AskPassphraseDialog(AskPassphraseDialog::Encrypt, this); dlg->setModel(walletModel); connect(dlg, &QDialog::finished, this, &WalletView::encryptionStatusChanged); GUIUtil::ShowModalDialogAsynchronously(dlg); } void WalletView::backupWallet() { QString filename = GUIUtil::getSaveFileName(this, tr("Backup Wallet"), QString(), //: Name of the wallet data file format. tr("Wallet Data") + QLatin1String(" (*.dat)"), nullptr); if (filename.isEmpty()) return; if (!walletModel->wallet().backupWallet(filename.toLocal8Bit().data())) { Q_EMIT message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename), CClientUIInterface::MSG_ERROR); } else { Q_EMIT message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename), CClientUIInterface::MSG_INFORMATION); } } void WalletView::changePassphrase() { auto dlg = new AskPassphraseDialog(AskPassphraseDialog::ChangePass, this); dlg->setModel(walletModel); GUIUtil::ShowModalDialogAsynchronously(dlg); } void WalletView::unlockWallet() { // Unlock wallet when requested by wallet model if (walletModel->getEncryptionStatus() == WalletModel::Locked) { AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this); dlg.setModel(walletModel); // A modal dialog must be synchronous here as expected // in the WalletModel::requestUnlock() function. dlg.exec(); } } void WalletView::usedSendingAddresses() { GUIUtil::bringToFront(usedSendingAddressesPage); } void WalletView::usedReceivingAddresses() { GUIUtil::bringToFront(usedReceivingAddressesPage); } void WalletView::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, tr("Cancel"), 0, 100); GUIUtil::PolishProgressDialog(progressDialog); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); progressDialog = nullptr; } } else if (progressDialog) { if (progressDialog->wasCanceled()) { getWalletModel()->wallet().abortRescan(); } else { progressDialog->setValue(nProgress); } } } void WalletView::disableTransactionView(bool disable) { transactionView->setDisabled(disable); }
0
bitcoin/src
bitcoin/src/qt/Makefile
.PHONY: FORCE all: FORCE $(MAKE) -C .. bitcoin_qt test_bitcoin_qt clean: FORCE $(MAKE) -C .. bitcoin_qt_clean test_bitcoin_qt_clean check: FORCE $(MAKE) -C .. test_bitcoin_qt_check bitcoin-qt bitcoin-qt.exe: FORCE $(MAKE) -C .. bitcoin_qt apk: FORCE $(MAKE) -C .. bitcoin_qt_apk
0
bitcoin/src
bitcoin/src/qt/transactionoverviewwidget.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 <qt/transactionoverviewwidget.h> #include <qt/transactiontablemodel.h> #include <QListView> #include <QSize> #include <QSizePolicy> TransactionOverviewWidget::TransactionOverviewWidget(QWidget* parent) : QListView(parent) {} QSize TransactionOverviewWidget::sizeHint() const { return {sizeHintForColumn(TransactionTableModel::ToAddress), QListView::sizeHint().height()}; } void TransactionOverviewWidget::showEvent(QShowEvent* event) { Q_UNUSED(event); QSizePolicy sp = sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Minimum); setSizePolicy(sp); }
0
bitcoin/src
bitcoin/src/qt/transactionoverviewwidget.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_QT_TRANSACTIONOVERVIEWWIDGET_H #define BITCOIN_QT_TRANSACTIONOVERVIEWWIDGET_H #include <QListView> #include <QSize> QT_BEGIN_NAMESPACE class QShowEvent; class QWidget; QT_END_NAMESPACE class TransactionOverviewWidget : public QListView { Q_OBJECT public: explicit TransactionOverviewWidget(QWidget* parent = nullptr); QSize sizeHint() const override; protected: void showEvent(QShowEvent* event) override; }; #endif // BITCOIN_QT_TRANSACTIONOVERVIEWWIDGET_H
0
bitcoin/src
bitcoin/src/qt/winshutdownmonitor.h
// Copyright (c) 2014-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_QT_WINSHUTDOWNMONITOR_H #define BITCOIN_QT_WINSHUTDOWNMONITOR_H #ifdef WIN32 #include <QByteArray> #include <QString> #include <functional> #include <windef.h> // for HWND #include <QAbstractNativeEventFilter> class WinShutdownMonitor : public QAbstractNativeEventFilter { public: WinShutdownMonitor(std::function<void()> shutdown_fn) : m_shutdown_fn{std::move(shutdown_fn)} {} /** Implements QAbstractNativeEventFilter interface for processing Windows messages */ bool nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult) override; /** Register the reason for blocking shutdown on Windows to allow clean client exit */ static void registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId); private: std::function<void()> m_shutdown_fn; }; #endif #endif // BITCOIN_QT_WINSHUTDOWNMONITOR_H
0
bitcoin/src
bitcoin/src/qt/receivecoinsdialog.h
// Copyright (c) 2011-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_QT_RECEIVECOINSDIALOG_H #define BITCOIN_QT_RECEIVECOINSDIALOG_H #include <qt/guiutil.h> #include <QDialog> #include <QHeaderView> #include <QItemSelection> #include <QKeyEvent> #include <QMenu> #include <QPoint> #include <QVariant> class PlatformStyle; class WalletModel; namespace Ui { class ReceiveCoinsDialog; } QT_BEGIN_NAMESPACE class QModelIndex; QT_END_NAMESPACE /** Dialog for requesting payment of bitcoins */ class ReceiveCoinsDialog : public QDialog { Q_OBJECT public: enum ColumnWidths { DATE_COLUMN_WIDTH = 130, LABEL_COLUMN_WIDTH = 120, AMOUNT_MINIMUM_COLUMN_WIDTH = 180, MINIMUM_COLUMN_WIDTH = 130 }; explicit ReceiveCoinsDialog(const PlatformStyle *platformStyle, QWidget *parent = nullptr); ~ReceiveCoinsDialog(); void setModel(WalletModel *model); public Q_SLOTS: void clear(); void reject() override; void accept() override; private: Ui::ReceiveCoinsDialog *ui; WalletModel* model{nullptr}; QMenu *contextMenu; QAction* copyLabelAction; QAction* copyMessageAction; QAction* copyAmountAction; const PlatformStyle *platformStyle; QModelIndex selectedRow(); void copyColumnToClipboard(int column); private Q_SLOTS: void on_receiveButton_clicked(); void on_showRequestButton_clicked(); void on_removeRequestButton_clicked(); void on_recentRequestsView_doubleClicked(const QModelIndex &index); void recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void updateDisplayUnit(); void showMenu(const QPoint &point); void copyURI(); void copyAddress(); void copyLabel(); void copyMessage(); void copyAmount(); }; #endif // BITCOIN_QT_RECEIVECOINSDIALOG_H
0
bitcoin/src
bitcoin/src/qt/coincontroltreewidget.h
// Copyright (c) 2011-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_QT_COINCONTROLTREEWIDGET_H #define BITCOIN_QT_COINCONTROLTREEWIDGET_H #include <QKeyEvent> #include <QTreeWidget> class CoinControlTreeWidget : public QTreeWidget { Q_OBJECT public: explicit CoinControlTreeWidget(QWidget *parent = nullptr); protected: virtual void keyPressEvent(QKeyEvent *event) override; }; #endif // BITCOIN_QT_COINCONTROLTREEWIDGET_H
0
bitcoin/src
bitcoin/src/qt/transactiondescdialog.h
// Copyright (c) 2011-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_QT_TRANSACTIONDESCDIALOG_H #define BITCOIN_QT_TRANSACTIONDESCDIALOG_H #include <QDialog> namespace Ui { class TransactionDescDialog; } QT_BEGIN_NAMESPACE class QModelIndex; QT_END_NAMESPACE /** Dialog showing transaction details. */ class TransactionDescDialog : public QDialog { Q_OBJECT public: explicit TransactionDescDialog(const QModelIndex &idx, QWidget *parent = nullptr); ~TransactionDescDialog(); private: Ui::TransactionDescDialog *ui; }; #endif // BITCOIN_QT_TRANSACTIONDESCDIALOG_H
0
bitcoin/src
bitcoin/src/qt/platformstyle.cpp
// Copyright (c) 2015-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 <qt/platformstyle.h> #include <QApplication> #include <QColor> #include <QImage> #include <QPalette> static const struct { const char *platformId; /** Show images on push buttons */ const bool imagesOnButtons; /** Colorize single-color icons */ const bool colorizeIcons; /** Extra padding/spacing in transactionview */ const bool useExtraSpacing; } platform_styles[] = { {"macosx", false, true, true}, {"windows", true, false, false}, /* Other: linux, unix, ... */ {"other", true, true, false} }; namespace { /* Local functions for colorizing single-color images */ void MakeSingleColorImage(QImage& img, const QColor& colorbase) { img = img.convertToFormat(QImage::Format_ARGB32); for (int x = img.width(); x--; ) { for (int y = img.height(); y--; ) { const QRgb rgb = img.pixel(x, y); img.setPixel(x, y, qRgba(colorbase.red(), colorbase.green(), colorbase.blue(), qAlpha(rgb))); } } } QIcon ColorizeIcon(const QIcon& ico, const QColor& colorbase) { QIcon new_ico; for (const QSize& sz : ico.availableSizes()) { QImage img(ico.pixmap(sz).toImage()); MakeSingleColorImage(img, colorbase); new_ico.addPixmap(QPixmap::fromImage(img)); } return new_ico; } QImage ColorizeImage(const QString& filename, const QColor& colorbase) { QImage img(filename); MakeSingleColorImage(img, colorbase); return img; } QIcon ColorizeIcon(const QString& filename, const QColor& colorbase) { return QIcon(QPixmap::fromImage(ColorizeImage(filename, colorbase))); } } PlatformStyle::PlatformStyle(const QString &_name, bool _imagesOnButtons, bool _colorizeIcons, bool _useExtraSpacing): name(_name), imagesOnButtons(_imagesOnButtons), colorizeIcons(_colorizeIcons), useExtraSpacing(_useExtraSpacing) { } QColor PlatformStyle::TextColor() const { return QApplication::palette().color(QPalette::WindowText); } QColor PlatformStyle::SingleColor() const { if (colorizeIcons) { QColor colorHighlightBg(QApplication::palette().color(QPalette::Highlight)); QColor colorHighlightFg(QApplication::palette().color(QPalette::HighlightedText)); const QColor colorText(QApplication::palette().color(QPalette::WindowText)); const int colorTextLightness = colorText.lightness(); if (abs(colorHighlightBg.lightness() - colorTextLightness) < abs(colorHighlightFg.lightness() - colorTextLightness)) { return colorHighlightBg; } return colorHighlightFg; } return {0, 0, 0}; } QImage PlatformStyle::SingleColorImage(const QString& filename) const { if (!colorizeIcons) return QImage(filename); return ColorizeImage(filename, SingleColor()); } QIcon PlatformStyle::SingleColorIcon(const QString& filename) const { if (!colorizeIcons) return QIcon(filename); return ColorizeIcon(filename, SingleColor()); } QIcon PlatformStyle::SingleColorIcon(const QIcon& icon) const { if (!colorizeIcons) return icon; return ColorizeIcon(icon, SingleColor()); } QIcon PlatformStyle::TextColorIcon(const QIcon& icon) const { return ColorizeIcon(icon, TextColor()); } const PlatformStyle *PlatformStyle::instantiate(const QString &platformId) { for (const auto& platform_style : platform_styles) { if (platformId == platform_style.platformId) { return new PlatformStyle( platform_style.platformId, platform_style.imagesOnButtons, platform_style.colorizeIcons, platform_style.useExtraSpacing); } } return nullptr; }
0
bitcoin/src
bitcoin/src/qt/clientmodel.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 <qt/clientmodel.h> #include <qt/bantablemodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/peertablemodel.h> #include <qt/peertablesortproxy.h> #include <clientversion.h> #include <common/args.h> #include <common/system.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <net.h> #include <netbase.h> #include <util/threadnames.h> #include <util/time.h> #include <validation.h> #include <stdint.h> #include <QDebug> #include <QMetaObject> #include <QThread> #include <QTimer> static SteadyClock::time_point g_last_header_tip_update_notification{}; static SteadyClock::time_point g_last_block_tip_update_notification{}; ClientModel::ClientModel(interfaces::Node& node, OptionsModel *_optionsModel, QObject *parent) : QObject(parent), m_node(node), optionsModel(_optionsModel), m_thread(new QThread(this)) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(m_node, this); m_peer_table_sort_proxy = new PeerTableSortProxy(this); m_peer_table_sort_proxy->setSourceModel(peerTableModel); banTableModel = new BanTableModel(m_node, this); QTimer* timer = new QTimer; timer->setInterval(MODEL_UPDATE_DELAY); connect(timer, &QTimer::timeout, [this] { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(m_node.getMempoolSize(), m_node.getMempoolDynamicUsage()); Q_EMIT bytesChanged(m_node.getTotalBytesRecv(), m_node.getTotalBytesSent()); }); connect(m_thread, &QThread::finished, timer, &QObject::deleteLater); connect(m_thread, &QThread::started, [timer] { timer->start(); }); // move timer to thread so that polling doesn't disturb main event loop timer->moveToThread(m_thread); m_thread->start(); QTimer::singleShot(0, timer, []() { util::ThreadRename("qt-clientmodl"); }); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); m_thread->quit(); m_thread->wait(); } int ClientModel::getNumConnections(unsigned int flags) const { ConnectionDirection connections = ConnectionDirection::None; if(flags == CONNECTIONS_IN) connections = ConnectionDirection::In; else if (flags == CONNECTIONS_OUT) connections = ConnectionDirection::Out; else if (flags == CONNECTIONS_ALL) connections = ConnectionDirection::Both; return m_node.getNodeCount(connections); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update int height; int64_t blockTime; if (m_node.getHeaderTip(height, blockTime)) { cachedBestHeaderHeight = height; cachedBestHeaderTime = blockTime; } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { int height; int64_t blockTime; if (m_node.getHeaderTip(height, blockTime)) { cachedBestHeaderHeight = height; cachedBestHeaderTime = blockTime; } } return cachedBestHeaderTime; } int ClientModel::getNumBlocks() const { if (m_cached_num_blocks == -1) { m_cached_num_blocks = m_node.getNumBlocks(); } return m_cached_num_blocks; } uint256 ClientModel::getBestBlockHash() { uint256 tip{WITH_LOCK(m_cached_tip_mutex, return m_cached_tip_blocks)}; if (!tip.IsNull()) { return tip; } // Lock order must be: first `cs_main`, then `m_cached_tip_mutex`. // The following will lock `cs_main` (and release it), so we must not // own `m_cached_tip_mutex` here. tip = m_node.getBestBlockHash(); LOCK(m_cached_tip_mutex); // We checked that `m_cached_tip_blocks` is not null above, but then we // released the mutex `m_cached_tip_mutex`, so it could have changed in the // meantime. Thus, check again. if (m_cached_tip_blocks.IsNull()) { m_cached_tip_blocks = tip; } return m_cached_tip_blocks; } BlockSource ClientModel::getBlockSource() const { if (m_node.isLoadingBlocks()) return BlockSource::DISK; if (getNumConnections() > 0) return BlockSource::NETWORK; return BlockSource::NONE; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(m_node.getWarnings().translated); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } PeerTableSortProxy* ClientModel::peerTableSortProxy() { return m_peer_table_sort_proxy; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromSecsSinceEpoch(GetStartupTime()).toString(); } QString ClientModel::dataDir() const { return GUIUtil::PathToQString(gArgs.GetDataDirNet()); } QString ClientModel::blocksDir() const { return GUIUtil::PathToQString(gArgs.GetBlocksDirPath()); } void ClientModel::TipChanged(SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress, SyncType synctype) { if (synctype == SyncType::HEADER_SYNC) { // cache best headers time and height to reduce future cs_main locks cachedBestHeaderHeight = tip.block_height; cachedBestHeaderTime = tip.block_time; } else if (synctype == SyncType::BLOCK_SYNC) { m_cached_num_blocks = tip.block_height; WITH_LOCK(m_cached_tip_mutex, m_cached_tip_blocks = tip.block_hash;); } // Throttle GUI notifications about (a) blocks during initial sync, and (b) both blocks and headers during reindex. const bool throttle = (sync_state != SynchronizationState::POST_INIT && synctype == SyncType::BLOCK_SYNC) || sync_state == SynchronizationState::INIT_REINDEX; const auto now{throttle ? SteadyClock::now() : SteadyClock::time_point{}}; auto& nLastUpdateNotification = synctype != SyncType::BLOCK_SYNC ? g_last_header_tip_update_notification : g_last_block_tip_update_notification; if (throttle && now < nLastUpdateNotification + MODEL_UPDATE_DELAY) { return; } Q_EMIT numBlocksChanged(tip.block_height, QDateTime::fromSecsSinceEpoch(tip.block_time), verification_progress, synctype, sync_state); nLastUpdateNotification = now; } void ClientModel::subscribeToCoreSignals() { m_handler_show_progress = m_node.handleShowProgress( [this](const std::string& title, int progress, [[maybe_unused]] bool resume_possible) { Q_EMIT showProgress(QString::fromStdString(title), progress); }); m_handler_notify_num_connections_changed = m_node.handleNotifyNumConnectionsChanged( [this](int new_num_connections) { Q_EMIT numConnectionsChanged(new_num_connections); }); m_handler_notify_network_active_changed = m_node.handleNotifyNetworkActiveChanged( [this](bool network_active) { Q_EMIT networkActiveChanged(network_active); }); m_handler_notify_alert_changed = m_node.handleNotifyAlertChanged( [this]() { qDebug() << "ClientModel: NotifyAlertChanged"; Q_EMIT alertsChanged(getStatusBarWarnings()); }); m_handler_banned_list_changed = m_node.handleBannedListChanged( [this]() { qDebug() << "ClienModel: Requesting update for peer banlist"; QMetaObject::invokeMethod(banTableModel, [this] { banTableModel->refresh(); }); }); m_handler_notify_block_tip = m_node.handleNotifyBlockTip( [this](SynchronizationState sync_state, interfaces::BlockTip tip, double verification_progress) { TipChanged(sync_state, tip, verification_progress, SyncType::BLOCK_SYNC); }); m_handler_notify_header_tip = m_node.handleNotifyHeaderTip( [this](SynchronizationState sync_state, interfaces::BlockTip tip, bool presync) { TipChanged(sync_state, tip, /*verification_progress=*/0.0, presync ? SyncType::HEADER_PRESYNC : SyncType::HEADER_SYNC); }); } void ClientModel::unsubscribeFromCoreSignals() { m_handler_show_progress->disconnect(); m_handler_notify_num_connections_changed->disconnect(); m_handler_notify_network_active_changed->disconnect(); m_handler_notify_alert_changed->disconnect(); m_handler_banned_list_changed->disconnect(); m_handler_notify_block_tip->disconnect(); m_handler_notify_header_tip->disconnect(); } bool ClientModel::getProxyInfo(std::string& ip_port) const { Proxy ipv4, ipv6; if (m_node.getProxy((Network) 1, ipv4) && m_node.getProxy((Network) 2, ipv6)) { ip_port = ipv4.proxy.ToStringAddrPort(); return true; } return false; }
0
bitcoin/src
bitcoin/src/qt/sendcoinsentry.h
// 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. #ifndef BITCOIN_QT_SENDCOINSENTRY_H #define BITCOIN_QT_SENDCOINSENTRY_H #include <qt/sendcoinsrecipient.h> #include <QWidget> class WalletModel; class PlatformStyle; namespace interfaces { class Node; } // namespace interfaces namespace Ui { class SendCoinsEntry; } /** * A single entry in the dialog for sending bitcoins. */ class SendCoinsEntry : public QWidget { Q_OBJECT public: explicit SendCoinsEntry(const PlatformStyle *platformStyle, QWidget *parent = nullptr); ~SendCoinsEntry(); void setModel(WalletModel *model); bool validate(interfaces::Node& node); SendCoinsRecipient getValue(); /** Return whether the entry is still empty and unedited */ bool isClear(); void setValue(const SendCoinsRecipient &value); void setAddress(const QString &address); void setAmount(const CAmount &amount); /** Set up the tab chain manually, as Qt messes up the tab chain by default in some cases * (issue https://bugreports.qt-project.org/browse/QTBUG-10907). */ QWidget *setupTabChain(QWidget *prev); void setFocus(); public Q_SLOTS: void clear(); void checkSubtractFeeFromAmount(); Q_SIGNALS: void removeEntry(SendCoinsEntry *entry); void useAvailableBalance(SendCoinsEntry* entry); void payAmountChanged(); void subtractFeeFromAmountChanged(); private Q_SLOTS: void deleteClicked(); void useAvailableBalanceClicked(); void on_payTo_textChanged(const QString &address); void on_addressBookButton_clicked(); void on_pasteButton_clicked(); void updateDisplayUnit(); protected: void changeEvent(QEvent* e) override; private: SendCoinsRecipient recipient; Ui::SendCoinsEntry *ui; WalletModel* model{nullptr}; const PlatformStyle *platformStyle; bool updateLabel(const QString &address); }; #endif // BITCOIN_QT_SENDCOINSENTRY_H
0
bitcoin/src
bitcoin/src/qt/addresstablemodel.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 <qt/addresstablemodel.h> #include <qt/guiutil.h> #include <qt/walletmodel.h> #include <key_io.h> #include <wallet/types.h> #include <wallet/wallet.h> #include <algorithm> #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() = default; AddressTableEntry(Type _type, const QString &_label, const QString &_address): type(_type), label(_label), address(_address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ constexpr AddressTableEntry::Type translateTransactionType(wallet::AddressPurpose purpose, bool isMine) { // "refund" addresses aren't shown, and change addresses aren't returned by getAddresses at all. switch (purpose) { case wallet::AddressPurpose::SEND: return AddressTableEntry::Sending; case wallet::AddressPurpose::RECEIVE: return AddressTableEntry::Receiving; case wallet::AddressPurpose::REFUND: return AddressTableEntry::Hidden; } // no default case, so the compiler can warn about missing cases assert(false); } // Private implementation class AddressTablePriv { public: QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; explicit AddressTablePriv(AddressTableModel *_parent): parent(_parent) {} void refreshAddressTable(interfaces::Wallet& wallet, bool pk_hash_only = false) { cachedAddressTable.clear(); { for (const auto& address : wallet.getAddresses()) { if (pk_hash_only && !std::holds_alternative<PKHash>(address.dest)) { continue; } AddressTableEntry::Type addressType = translateTransactionType( address.purpose, address.is_mine); cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(address.name), QString::fromStdString(EncodeDestination(address.dest)))); } } // std::lower_bound() and std::upper_bound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. std::sort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, wallet::AddressPurpose purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = std::lower_bound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = std::upper_bound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return nullptr; } } }; AddressTableModel::AddressTableModel(WalletModel *parent, bool pk_hash_only) : QAbstractTableModel(parent), walletModel(parent) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(this); priv->refreshAddressTable(parent->wallet(), pk_hash_only); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) { return 0; } return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); const auto column = static_cast<ColumnIndex>(index.column()); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (column) { case Label: if (rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } // no default case, so the compiler can warn about missing cases assert(false); } else if (role == Qt::FontRole) { switch (column) { case Label: return QFont(); case Address: return GUIUtil::fixedPitchFont(); } // no default case, so the compiler can warn about missing cases assert(false); } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; case AddressTableEntry::Hidden: return {}; } // no default case, so the compiler can warn about missing cases assert(false); } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); wallet::AddressPurpose purpose = rec->type == AddressTableEntry::Sending ? wallet::AddressPurpose::SEND : wallet::AddressPurpose::RECEIVE; editStatus = OK; if(role == Qt::EditRole) { CTxDestination curAddress = DecodeDestination(rec->address.toStdString()); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } walletModel->wallet().setAddressBook(curAddress, value.toString().toStdString(), purpose); } else if(index.column() == Address) { CTxDestination newAddress = DecodeDestination(value.toString().toStdString()); // Refuse to set invalid address, set error status and return false if(std::get_if<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) if (walletModel->wallet().getAddress( newAddress, /* name= */ nullptr, /* is_mine= */ nullptr, /* purpose= */ nullptr)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry walletModel->wallet().delAddressBook(curAddress); // Add new entry with new address walletModel->wallet().setAddressBook(newAddress, value.toString().toStdString(), purpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, wallet::AddressPurpose purpose, int status) { // Update address book model from Bitcoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address, const OutputType address_type) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { if (walletModel->wallet().getAddress( DecodeDestination(strAddress), /* name= */ nullptr, /* is_mine= */ nullptr, /* purpose= */ nullptr)) { editStatus = DUPLICATE_ADDRESS; return QString(); } } // Add entry walletModel->wallet().setAddressBook(DecodeDestination(strAddress), strLabel, wallet::AddressPurpose::SEND); } else if(type == Receive) { // Generate a new address to associate with given label auto op_dest = walletModel->wallet().getNewDestination(address_type, strLabel); if (!op_dest) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if (!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } op_dest = walletModel->wallet().getNewDestination(address_type, strLabel); if (!op_dest) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = EncodeDestination(*op_dest); } else { return QString(); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } walletModel->wallet().delAddressBook(DecodeDestination(rec->address.toStdString())); return true; } QString AddressTableModel::labelForAddress(const QString &address) const { std::string name; if (getAddressData(address, &name, /* purpose= */ nullptr)) { return QString::fromStdString(name); } return QString(); } std::optional<wallet::AddressPurpose> AddressTableModel::purposeForAddress(const QString &address) const { wallet::AddressPurpose purpose; if (getAddressData(address, /* name= */ nullptr, &purpose)) { return purpose; } return std::nullopt; } bool AddressTableModel::getAddressData(const QString &address, std::string* name, wallet::AddressPurpose* purpose) const { CTxDestination destination = DecodeDestination(address.toStdString()); return walletModel->wallet().getAddress(destination, name, /* is_mine= */ nullptr, purpose); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } OutputType AddressTableModel::GetDefaultAddressType() const { return walletModel->wallet().getDefaultAddressType(); }; void AddressTableModel::emitDataChanged(int idx) { Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } QString AddressTableModel::GetWalletDisplayName() const { return walletModel->getDisplayName(); };
0
bitcoin/src
bitcoin/src/qt/walletmodel.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. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/walletmodel.h> #include <qt/addresstablemodel.h> #include <qt/clientmodel.h> #include <qt/guiconstants.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/paymentserver.h> #include <qt/recentrequeststablemodel.h> #include <qt/sendcoinsdialog.h> #include <qt/transactiontablemodel.h> #include <common/args.h> // for GetBoolArg #include <interfaces/handler.h> #include <interfaces/node.h> #include <key_io.h> #include <node/interface_ui.h> #include <psbt.h> #include <util/translation.h> #include <wallet/coincontrol.h> #include <wallet/wallet.h> // for CRecipient #include <stdint.h> #include <functional> #include <QDebug> #include <QMessageBox> #include <QSet> #include <QTimer> using wallet::CCoinControl; using wallet::CRecipient; using wallet::DEFAULT_DISABLE_WALLET; WalletModel::WalletModel(std::unique_ptr<interfaces::Wallet> wallet, ClientModel& client_model, const PlatformStyle *platformStyle, QObject *parent) : QObject(parent), m_wallet(std::move(wallet)), m_client_model(&client_model), m_node(client_model.node()), optionsModel(client_model.getOptionsModel()), timer(new QTimer(this)) { fHaveWatchOnly = m_wallet->haveWatchOnly(); addressTableModel = new AddressTableModel(this); transactionTableModel = new TransactionTableModel(platformStyle, this); recentRequestsTableModel = new RecentRequestsTableModel(this); subscribeToCoreSignals(); } WalletModel::~WalletModel() { unsubscribeFromCoreSignals(); } void WalletModel::startPollBalance() { // Update the cached balance right away, so every view can make use of it, // so them don't need to waste resources recalculating it. pollBalanceChanged(); // This timer will be fired repeatedly to update the balance // Since the QTimer::timeout is a private signal, it cannot be used // in the GUIUtil::ExceptionSafeConnect directly. connect(timer, &QTimer::timeout, this, &WalletModel::timerTimeout); GUIUtil::ExceptionSafeConnect(this, &WalletModel::timerTimeout, this, &WalletModel::pollBalanceChanged); timer->start(MODEL_UPDATE_DELAY); } void WalletModel::setClientModel(ClientModel* client_model) { m_client_model = client_model; if (!m_client_model) timer->stop(); } void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); if(cachedEncryptionStatus != newEncryptionStatus) { Q_EMIT encryptionStatusChanged(); } } void WalletModel::pollBalanceChanged() { // Avoid recomputing wallet balances unless a TransactionChanged or // BlockTip notification was received. if (!fForceCheckBalanceChanged && m_cached_last_update_tip == getLastBlockProcessed()) return; // Try to get balances and return early if locks can't be acquired. This // avoids the GUI from getting stuck on periodical polls if the core is // holding the locks for a longer time - for example, during a wallet // rescan. interfaces::WalletBalances new_balances; uint256 block_hash; if (!m_wallet->tryGetBalances(new_balances, block_hash)) { return; } if (fForceCheckBalanceChanged || block_hash != m_cached_last_update_tip) { fForceCheckBalanceChanged = false; // Balance and number of transactions might have changed m_cached_last_update_tip = block_hash; checkBalanceChanged(new_balances); if(transactionTableModel) transactionTableModel->updateConfirmations(); } } void WalletModel::checkBalanceChanged(const interfaces::WalletBalances& new_balances) { if (new_balances.balanceChanged(m_cached_balances)) { m_cached_balances = new_balances; Q_EMIT balanceChanged(new_balances); } } interfaces::WalletBalances WalletModel::getCachedBalance() const { return m_cached_balances; } void WalletModel::updateTransaction() { // Balance and number of transactions might have changed fForceCheckBalanceChanged = true; } void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, wallet::AddressPurpose purpose, int status) { if(addressTableModel) addressTableModel->updateEntry(address, label, isMine, purpose, status); } void WalletModel::updateWatchOnlyFlag(bool fHaveWatchonly) { fHaveWatchOnly = fHaveWatchonly; Q_EMIT notifyWatchonlyChanged(fHaveWatchonly); } bool WalletModel::validateAddress(const QString& address) const { return IsValidDestinationString(address.toStdString()); } WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl& coinControl) { CAmount total = 0; bool fSubtractFeeFromAmount = false; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<CRecipient> vecSend; if(recipients.empty()) { return OK; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity for (const SendCoinsRecipient &rcp : recipients) { if (rcp.fSubtractFeeFromAmount) fSubtractFeeFromAmount = true; { // User-entered bitcoin address / amount: if(!validateAddress(rcp.address)) { return InvalidAddress; } if(rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CRecipient recipient{DecodeDestination(rcp.address.toStdString()), rcp.amount, rcp.fSubtractFeeFromAmount}; vecSend.push_back(recipient); total += rcp.amount; } } if(setAddress.size() != nAddresses) { return DuplicateAddress; } // If no coin was manually selected, use the cached balance // Future: can merge this call with 'createTransaction'. CAmount nBalance = getAvailableBalance(&coinControl); if(total > nBalance) { return AmountExceedsBalance; } try { CAmount nFeeRequired = 0; int nChangePosRet = -1; auto& newTx = transaction.getWtx(); const auto& res = m_wallet->createTransaction(vecSend, coinControl, /*sign=*/!wallet().privateKeysDisabled(), nChangePosRet, nFeeRequired); newTx = res ? *res : nullptr; transaction.setTransactionFee(nFeeRequired); if (fSubtractFeeFromAmount && newTx) transaction.reassignAmounts(nChangePosRet); if(!newTx) { if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } Q_EMIT message(tr("Send Coins"), QString::fromStdString(util::ErrorString(res).translated), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } // Reject absurdly high fee. (This can never happen because the // wallet never creates transactions with fee greater than // m_default_max_tx_fee. This merely a belt-and-suspenders check). if (nFeeRequired > m_wallet->getDefaultMaxTxFee()) { return AbsurdFee; } } catch (const std::runtime_error& err) { // Something unexpected happened, instruct user to report this bug. Q_EMIT message(tr("Send Coins"), QString::fromStdString(err.what()), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } return SendCoinsReturn(OK); } void WalletModel::sendCoins(WalletModelTransaction& transaction) { QByteArray transaction_array; /* store serialized transaction */ { std::vector<std::pair<std::string, std::string>> vOrderForm; for (const SendCoinsRecipient &rcp : transaction.getRecipients()) { if (!rcp.message.isEmpty()) // Message from normal bitcoin:URI (bitcoin:123...?message=example) vOrderForm.emplace_back("Message", rcp.message.toStdString()); } auto& newTx = transaction.getWtx(); wallet().commitTransaction(newTx, /*value_map=*/{}, std::move(vOrderForm)); DataStream ssTx; ssTx << TX_WITH_WITNESS(*newTx); transaction_array.append((const char*)ssTx.data(), ssTx.size()); } // Add addresses / update labels that we've sent to the address book, // and emit coinsSent signal for each recipient for (const SendCoinsRecipient &rcp : transaction.getRecipients()) { { std::string strAddress = rcp.address.toStdString(); CTxDestination dest = DecodeDestination(strAddress); std::string strLabel = rcp.label.toStdString(); { // Check if we have a new address or an updated label std::string name; if (!m_wallet->getAddress( dest, &name, /* is_mine= */ nullptr, /* purpose= */ nullptr)) { m_wallet->setAddressBook(dest, strLabel, wallet::AddressPurpose::SEND); } else if (name != strLabel) { m_wallet->setAddressBook(dest, strLabel, {}); // {} means don't change purpose } } } Q_EMIT coinsSent(this, rcp, transaction_array); } checkBalanceChanged(m_wallet->getBalances()); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits } OptionsModel* WalletModel::getOptionsModel() const { return optionsModel; } AddressTableModel* WalletModel::getAddressTableModel() const { return addressTableModel; } TransactionTableModel* WalletModel::getTransactionTableModel() const { return transactionTableModel; } RecentRequestsTableModel* WalletModel::getRecentRequestsTableModel() const { return recentRequestsTableModel; } WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { if(!m_wallet->isCrypted()) { // A previous bug allowed for watchonly wallets to be encrypted (encryption keys set, but nothing is actually encrypted). // To avoid misrepresenting the encryption status of such wallets, we only return NoKeys for watchonly wallets that are unencrypted. if (m_wallet->privateKeysDisabled()) { return NoKeys; } return Unencrypted; } else if(m_wallet->isLocked()) { return Locked; } else { return Unlocked; } } bool WalletModel::setWalletEncrypted(const SecureString& passphrase) { return m_wallet->encryptWallet(passphrase); } bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) { if(locked) { // Lock return m_wallet->lock(); } else { // Unlock return m_wallet->unlock(passPhrase); } } bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { m_wallet->lock(); // Make sure wallet is locked before attempting pass change return m_wallet->changeWalletPassphrase(oldPass, newPass); } // Handlers for core signals static void NotifyUnload(WalletModel* walletModel) { qDebug() << "NotifyUnload"; bool invoked = QMetaObject::invokeMethod(walletModel, "unload"); assert(invoked); } static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel) { qDebug() << "NotifyKeyStoreStatusChanged"; bool invoked = QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection); assert(invoked); } static void NotifyAddressBookChanged(WalletModel *walletmodel, const CTxDestination &address, const std::string &label, bool isMine, wallet::AddressPurpose purpose, ChangeType status) { QString strAddress = QString::fromStdString(EncodeDestination(address)); QString strLabel = QString::fromStdString(label); qDebug() << "NotifyAddressBookChanged: " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " purpose=" + QString::number(static_cast<uint8_t>(purpose)) + " status=" + QString::number(status); bool invoked = QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Q_ARG(QString, strAddress), Q_ARG(QString, strLabel), Q_ARG(bool, isMine), Q_ARG(wallet::AddressPurpose, purpose), Q_ARG(int, status)); assert(invoked); } static void NotifyTransactionChanged(WalletModel *walletmodel, const uint256 &hash, ChangeType status) { Q_UNUSED(hash); Q_UNUSED(status); bool invoked = QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection); assert(invoked); } static void ShowProgress(WalletModel *walletmodel, const std::string &title, int nProgress) { // emits signal "showProgress" bool invoked = QMetaObject::invokeMethod(walletmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); assert(invoked); } static void NotifyWatchonlyChanged(WalletModel *walletmodel, bool fHaveWatchonly) { bool invoked = QMetaObject::invokeMethod(walletmodel, "updateWatchOnlyFlag", Qt::QueuedConnection, Q_ARG(bool, fHaveWatchonly)); assert(invoked); } static void NotifyCanGetAddressesChanged(WalletModel* walletmodel) { bool invoked = QMetaObject::invokeMethod(walletmodel, "canGetAddressesChanged"); assert(invoked); } void WalletModel::subscribeToCoreSignals() { // Connect signals to wallet m_handler_unload = m_wallet->handleUnload(std::bind(&NotifyUnload, this)); m_handler_status_changed = m_wallet->handleStatusChanged(std::bind(&NotifyKeyStoreStatusChanged, this)); m_handler_address_book_changed = m_wallet->handleAddressBookChanged(std::bind(NotifyAddressBookChanged, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5)); m_handler_transaction_changed = m_wallet->handleTransactionChanged(std::bind(NotifyTransactionChanged, this, std::placeholders::_1, std::placeholders::_2)); m_handler_show_progress = m_wallet->handleShowProgress(std::bind(ShowProgress, this, std::placeholders::_1, std::placeholders::_2)); m_handler_watch_only_changed = m_wallet->handleWatchOnlyChanged(std::bind(NotifyWatchonlyChanged, this, std::placeholders::_1)); m_handler_can_get_addrs_changed = m_wallet->handleCanGetAddressesChanged(std::bind(NotifyCanGetAddressesChanged, this)); } void WalletModel::unsubscribeFromCoreSignals() { // Disconnect signals from wallet m_handler_unload->disconnect(); m_handler_status_changed->disconnect(); m_handler_address_book_changed->disconnect(); m_handler_transaction_changed->disconnect(); m_handler_show_progress->disconnect(); m_handler_watch_only_changed->disconnect(); m_handler_can_get_addrs_changed->disconnect(); } // WalletModel::UnlockContext implementation WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; if(was_locked) { // Request UI to unlock wallet Q_EMIT requireUnlock(); } // If wallet is still locked, unlock was failed or cancelled, mark context as invalid bool valid = getEncryptionStatus() != Locked; return UnlockContext(this, valid, was_locked); } WalletModel::UnlockContext::UnlockContext(WalletModel *_wallet, bool _valid, bool _relock): wallet(_wallet), valid(_valid), relock(_relock) { } WalletModel::UnlockContext::~UnlockContext() { if(valid && relock) { wallet->setWalletLocked(true); } } bool WalletModel::bumpFee(uint256 hash, uint256& new_hash) { CCoinControl coin_control; coin_control.m_signal_bip125_rbf = true; std::vector<bilingual_str> errors; CAmount old_fee; CAmount new_fee; CMutableTransaction mtx; if (!m_wallet->createBumpTransaction(hash, coin_control, errors, old_fee, new_fee, mtx)) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Increasing transaction fee failed") + "<br />(" + (errors.size() ? QString::fromStdString(errors[0].translated) : "") +")"); return false; } // allow a user based fee verification /*: Asks a user if they would like to manually increase the fee of a transaction that has already been created. */ QString questionString = tr("Do you want to increase the fee?"); questionString.append("<br />"); questionString.append("<table style=\"text-align: left;\">"); questionString.append("<tr><td>"); questionString.append(tr("Current fee:")); questionString.append("</td><td>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), old_fee)); questionString.append("</td></tr><tr><td>"); questionString.append(tr("Increase:")); questionString.append("</td><td>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), new_fee - old_fee)); questionString.append("</td></tr><tr><td>"); questionString.append(tr("New fee:")); questionString.append("</td><td>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(getOptionsModel()->getDisplayUnit(), new_fee)); questionString.append("</td></tr></table>"); // Display warning in the "Confirm fee bump" window if the "Coin Control Features" option is enabled if (getOptionsModel()->getCoinControlFeatures()) { questionString.append("<br><br>"); questionString.append(tr("Warning: This may pay the additional fee by reducing change outputs or adding inputs, when necessary. It may add a new change output if one does not already exist. These changes may potentially leak privacy.")); } const bool enable_send{!wallet().privateKeysDisabled() || wallet().hasExternalSigner()}; const bool always_show_unsigned{getOptionsModel()->getEnablePSBTControls()}; auto confirmationDialog = new SendConfirmationDialog(tr("Confirm fee bump"), questionString, "", "", SEND_CONFIRM_DELAY, enable_send, always_show_unsigned, nullptr); confirmationDialog->setAttribute(Qt::WA_DeleteOnClose); // TODO: Replace QDialog::exec() with safer QDialog::show(). const auto retval = static_cast<QMessageBox::StandardButton>(confirmationDialog->exec()); // cancel sign&broadcast if user doesn't want to bump the fee if (retval != QMessageBox::Yes && retval != QMessageBox::Save) { return false; } WalletModel::UnlockContext ctx(requestUnlock()); if(!ctx.isValid()) { return false; } // Short-circuit if we are returning a bumped transaction PSBT to clipboard if (retval == QMessageBox::Save) { // "Create Unsigned" clicked PartiallySignedTransaction psbtx(mtx); bool complete = false; const TransactionError err = wallet().fillPSBT(SIGHASH_ALL, /*sign=*/false, /*bip32derivs=*/true, nullptr, psbtx, complete); if (err != TransactionError::OK || complete) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Can't draft transaction.")); return false; } // Serialize the PSBT DataStream ssTx{}; ssTx << psbtx; GUIUtil::setClipboard(EncodeBase64(ssTx.str()).c_str()); Q_EMIT message(tr("PSBT copied"), tr("Copied to clipboard", "Fee-bump PSBT saved"), CClientUIInterface::MSG_INFORMATION); return true; } assert(!m_wallet->privateKeysDisabled() || wallet().hasExternalSigner()); // sign bumped transaction if (!m_wallet->signBumpTransaction(mtx)) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Can't sign transaction.")); return false; } // commit the bumped transaction if(!m_wallet->commitBumpTransaction(hash, std::move(mtx), errors, new_hash)) { QMessageBox::critical(nullptr, tr("Fee bump error"), tr("Could not commit transaction") + "<br />(" + QString::fromStdString(errors[0].translated)+")"); return false; } return true; } bool WalletModel::displayAddress(std::string sAddress) const { CTxDestination dest = DecodeDestination(sAddress); bool res = false; try { res = m_wallet->displayAddress(dest); } catch (const std::runtime_error& e) { QMessageBox::critical(nullptr, tr("Can't display address"), e.what()); } return res; } bool WalletModel::isWalletEnabled() { return !gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET); } QString WalletModel::getWalletName() const { return QString::fromStdString(m_wallet->getWalletName()); } QString WalletModel::getDisplayName() const { const QString name = getWalletName(); return name.isEmpty() ? "["+tr("default wallet")+"]" : name; } bool WalletModel::isMultiwallet() const { return m_node.walletLoader().getWallets().size() > 1; } void WalletModel::refresh(bool pk_hash_only) { addressTableModel = new AddressTableModel(this, pk_hash_only); } uint256 WalletModel::getLastBlockProcessed() const { return m_client_model ? m_client_model->getBestBlockHash() : uint256{}; } CAmount WalletModel::getAvailableBalance(const CCoinControl* control) { // No selected coins, return the cached balance if (!control || !control->HasSelected()) { const interfaces::WalletBalances& balances = getCachedBalance(); CAmount available_balance = balances.balance; // if wallet private keys are disabled, this is a watch-only wallet // so, let's include the watch-only balance. if (balances.have_watch_only && m_wallet->privateKeysDisabled()) { available_balance += balances.watch_only_balance; } return available_balance; } // Fetch balance from the wallet, taking into account the selected coins return wallet().getAvailableBalance(*control); }
0
bitcoin/src
bitcoin/src/qt/qvaluecombobox.h
// Copyright (c) 2011-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_QT_QVALUECOMBOBOX_H #define BITCOIN_QT_QVALUECOMBOBOX_H #include <QComboBox> #include <QVariant> /* QComboBox that can be used with QDataWidgetMapper to select ordinal values from a model. */ class QValueComboBox : public QComboBox { Q_OBJECT Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged USER true) public: explicit QValueComboBox(QWidget *parent = nullptr); QVariant value() const; void setValue(const QVariant &value); /** Specify model role to use as ordinal value (defaults to Qt::UserRole) */ void setRole(int role); Q_SIGNALS: void valueChanged(); private: int role{Qt::UserRole}; private Q_SLOTS: void handleSelectionChanged(int idx); }; #endif // BITCOIN_QT_QVALUECOMBOBOX_H
0
bitcoin/src
bitcoin/src/qt/initexecutor.h
// Copyright (c) 2014-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_QT_INITEXECUTOR_H #define BITCOIN_QT_INITEXECUTOR_H #include <interfaces/node.h> #include <exception> #include <QObject> #include <QThread> QT_BEGIN_NAMESPACE class QString; QT_END_NAMESPACE /** Class encapsulating Bitcoin Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class InitExecutor : public QObject { Q_OBJECT public: explicit InitExecutor(interfaces::Node& node); ~InitExecutor(); public Q_SLOTS: void initialize(); void shutdown(); Q_SIGNALS: void initializeResult(bool success, interfaces::BlockAndHeaderTipInfo tip_info); void shutdownResult(); void runawayException(const QString& message); private: /// Pass fatal exception message to UI thread void handleRunawayException(const std::exception* e); interfaces::Node& m_node; QObject m_context; QThread m_thread; }; #endif // BITCOIN_QT_INITEXECUTOR_H
0
bitcoin/src
bitcoin/src/qt/sendcoinsentry.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. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/sendcoinsentry.h> #include <qt/forms/ui_sendcoinsentry.h> #include <qt/addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::SendCoinsEntry), platformStyle(_platformStyle) { ui->setupUi(this); ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(":/icons/address-book")); ui->pasteButton->setIcon(platformStyle->SingleColorIcon(":/icons/editpaste")); ui->deleteButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); if (platformStyle->getUseExtraSpacing()) ui->payToLayout->setSpacing(4); GUIUtil::setupAddressWidget(ui->payTo, this); // Connect signals connect(ui->payAmount, &BitcoinAmountField::valueChanged, this, &SendCoinsEntry::payAmountChanged); connect(ui->checkboxSubtractFeeFromAmount, &QCheckBox::toggled, this, &SendCoinsEntry::subtractFeeFromAmountChanged); connect(ui->deleteButton, &QPushButton::clicked, this, &SendCoinsEntry::deleteClicked); connect(ui->useAvailableBalanceButton, &QPushButton::clicked, this, &SendCoinsEntry::useAvailableBalanceClicked); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { updateLabel(address); } void SendCoinsEntry::setModel(WalletModel *_model) { this->model = _model; if (_model && _model->getOptionsModel()) connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SendCoinsEntry::updateDisplayUnit); clear(); } void SendCoinsEntry::clear() { // clear UI elements for normal payment ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); if (model && model->getOptionsModel()) { ui->checkboxSubtractFeeFromAmount->setChecked(model->getOptionsModel()->getSubFeeFromAmount()); } ui->messageTextLabel->clear(); ui->messageTextLabel->hide(); ui->messageLabel->hide(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::checkSubtractFeeFromAmount() { ui->checkboxSubtractFeeFromAmount->setChecked(true); } void SendCoinsEntry::deleteClicked() { Q_EMIT removeEntry(this); } void SendCoinsEntry::useAvailableBalanceClicked() { Q_EMIT useAvailableBalance(this); } bool SendCoinsEntry::validate(interfaces::Node& node) { if (!model) return false; // Check input validity bool retval = true; if (!model->validateAddress(ui->payTo->text())) { ui->payTo->setValid(false); retval = false; } if (!ui->payAmount->validate()) { retval = false; } // Sending a zero amount is invalid if (ui->payAmount->value(nullptr) <= 0) { ui->payAmount->setValid(false); retval = false; } // Reject dust outputs: if (retval && GUIUtil::isDust(node, ui->payTo->text(), ui->payAmount->value())) { ui->payAmount->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { recipient.address = ui->payTo->text(); recipient.label = ui->addAsLabel->text(); recipient.amount = ui->payAmount->value(); recipient.message = ui->messageTextLabel->text(); recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked); return recipient; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addAsLabel); QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel); QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount); QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); return ui->deleteButton; } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { recipient = value; { // message ui->messageTextLabel->setText(recipient.message); ui->messageTextLabel->setVisible(!recipient.message.isEmpty()); ui->messageLabel->setVisible(!recipient.message.isEmpty()); ui->addAsLabel->clear(); ui->payTo->setText(recipient.address); // this may set a label from addressbook if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label ui->addAsLabel->setText(recipient.label); ui->payAmount->setValue(recipient.amount); } } void SendCoinsEntry::setAddress(const QString &address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } void SendCoinsEntry::setAmount(const CAmount &amount) { ui->payAmount->setValue(amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if (model && model->getOptionsModel()) { ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } void SendCoinsEntry::changeEvent(QEvent* e) { if (e->type() == QEvent::PaletteChange) { ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/address-book"))); ui->pasteButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/editpaste"))); ui->deleteButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove"))); } QWidget::changeEvent(e); } bool SendCoinsEntry::updateLabel(const QString &address) { if(!model) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; }
0
bitcoin/src
bitcoin/src/qt/walletmodeltransaction.h
// Copyright (c) 2011-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_QT_WALLETMODELTRANSACTION_H #define BITCOIN_QT_WALLETMODELTRANSACTION_H #include <primitives/transaction.h> #include <qt/sendcoinsrecipient.h> #include <consensus/amount.h> #include <QObject> class SendCoinsRecipient; namespace interfaces { class Node; } /** Data model for a walletmodel transaction. */ class WalletModelTransaction { public: explicit WalletModelTransaction(const QList<SendCoinsRecipient> &recipients); QList<SendCoinsRecipient> getRecipients() const; CTransactionRef& getWtx(); void setWtx(const CTransactionRef&); unsigned int getTransactionSize(); void setTransactionFee(const CAmount& newFee); CAmount getTransactionFee() const; CAmount getTotalTransactionAmount() const; void reassignAmounts(int nChangePosRet); // needed for the subtract-fee-from-amount feature private: QList<SendCoinsRecipient> recipients; CTransactionRef wtx; CAmount fee{0}; }; #endif // BITCOIN_QT_WALLETMODELTRANSACTION_H
0