From 8a0d23eabc82f62c83df8b4914005ec9f5935663 Mon Sep 17 00:00:00 2001 From: Lee *!* Clagett Date: Sun, 30 Mar 2025 17:37:10 -0400 Subject: [PATCH] Several different changes (still WIP): * Reverted back to standard `::Monero::` interface * Added some previsouly missing functions * Fixed several bugs --- include/lws_frontend.h | 234 ++++++++++++++++---------------- src/CMakeLists.txt | 2 + src/address_book.cpp | 203 ++++++++++++++++++++++++++++ src/address_book.h | 70 ++++++++++ src/backend.cpp | 263 +++++++++++++++++++++++++++++++----- src/backend.h | 65 ++++++--- src/error.cpp | 59 ++++++++ src/error.h | 68 ++++++++++ src/lwsf_config.h | 4 +- src/pending_transaction.cpp | 76 +++++++++++ src/pending_transaction.h | 95 +++++++++++++ src/rpc.cpp | 42 +++++- src/rpc.h | 59 ++++++-- src/subaddress_account.h | 61 +++++++++ src/transaction_history.cpp | 112 ++++++++++----- src/transaction_history.h | 19 ++- src/transaction_info.cpp | 79 ++++++++++- src/transaction_info.h | 32 +++-- src/wallet.cpp | 203 +++++++++++++++++++++++++--- src/wallet.h | 96 ++++++------- src/wallet_manager.cpp | 51 +++---- src/wire/basic_value.cpp | 54 ++++++++ src/wire/basic_value.h | 64 +++++++++ src/wire/wrapper/variant.h | 13 ++ 24 files changed, 1699 insertions(+), 325 deletions(-) create mode 100644 src/address_book.cpp create mode 100644 src/address_book.h create mode 100644 src/error.cpp create mode 100644 src/error.h create mode 100644 src/pending_transaction.cpp create mode 100644 src/pending_transaction.h create mode 100644 src/subaddress_account.h create mode 100644 src/wire/basic_value.cpp create mode 100644 src/wire/basic_value.h diff --git a/include/lws_frontend.h b/include/lws_frontend.h index 4e1b1cc..bde664a 100644 --- a/include/lws_frontend.h +++ b/include/lws_frontend.h @@ -38,10 +38,12 @@ #include #include +#include "wallet/api/wallet2_api.h" // monero/src + // Public interface for libwallet library namespace lwsf { - +/* enum NetworkType : uint8_t { MAINNET = 0, TESTNET, @@ -67,7 +69,7 @@ enum NetworkType : uint8_t { }; /** * @brief Transaction-like interface for sending money - */ + * / struct PendingTransaction { enum class Status { @@ -96,7 +98,7 @@ struct PendingTransaction /*! * \brief txCount - number of transactions current transaction will be splitted to * \return - */ + * / virtual uint64_t txCount() const = 0; virtual std::vector subaddrAccount() const = 0; virtual std::vector> subaddrIndices() const = 0; @@ -116,19 +118,19 @@ struct PendingTransaction * pendingTransaction = wallet->restoreMultisigTransaction(signed); * pendingTransaction->signMultisigTx(); * pendingTransaction->commit(); - */ + * / virtual std::string multisigSignData() = 0; virtual void signMultisigTx() = 0; /** * @brief signersKeys * @return vector of base58-encoded signers' public keys - */ + * / virtual std::vector signersKeys() const = 0; }; /** * @brief Transaction-like interface for sending money - */ + * / struct UnsignedTransaction { enum class Status { @@ -151,19 +153,19 @@ struct UnsignedTransaction /*! * \brief txCount - number of transactions current transaction will be splitted to * \return - */ + * / virtual uint64_t txCount() const = 0; /*! * @brief sign - Sign txs and saves to file * @param signedFileName * return - true on success - */ + * / virtual bool sign(const std::string &signedFileName) = 0; }; /** * @brief The TransactionInfo - interface for displaying transaction information - */ + * / struct TransactionInfo { enum class Direction { @@ -200,7 +202,7 @@ struct TransactionInfo }; /** * @brief The TransactionHistory - interface for displaying transaction history - */ + * / struct TransactionHistory { virtual ~TransactionHistory() = 0; @@ -214,7 +216,7 @@ struct TransactionHistory /** * @brief AddressBookRow - provides functions to manage address book - */ + * / struct AddressBookRow { public: AddressBookRow(std::size_t _rowId, const std::string &_address, const std::string &_paymentId, const std::string &_description): @@ -239,7 +241,7 @@ public: /** * @brief The AddressBook - interface for Book - */ + * / struct AddressBook { enum ErrorCode { @@ -349,60 +351,60 @@ struct WalletListener * @brief moneySpent - called when money spent * @param txId - transaction id * @param amount - amount - */ + * / virtual void moneySpent(const std::string &txId, uint64_t amount) = 0; /** * @brief moneyReceived - called when money received * @param txId - transaction id * @param amount - amount - */ + * / virtual void moneyReceived(const std::string &txId, uint64_t amount) = 0; /** * @brief unconfirmedMoneyReceived - called when payment arrived in tx pool * @param txId - transaction id * @param amount - amount - */ + * / virtual void unconfirmedMoneyReceived(const std::string &txId, uint64_t amount) = 0; /** * @brief newBlock - called when new block received * @param height - block height - */ + * / virtual void newBlock(uint64_t height) = 0; /** * @brief updated - generic callback, called when any event (sent/received/block reveived/etc) happened with the wallet; - */ + * / virtual void updated() = 0; /** * @brief refreshed - called when wallet refreshed by background thread or explicitly refreshed by calling "refresh" synchronously - */ + * / virtual void refreshed() = 0; /** * @brief called by device if the action is required - */ + * / virtual void onDeviceButtonRequest(uint64_t code) { (void)code; } /** * @brief called by device if the button was pressed - */ + * / virtual void onDeviceButtonPressed() { } /** * @brief called by device when PIN is needed - */ + * / virtual optional onDevicePinRequest() { throw std::runtime_error("Not supported"); } /** * @brief called by device when passphrase entry is needed - */ + * / virtual optional onDevicePassphraseRequest(bool & on_device) { on_device = true; return {}; @@ -410,19 +412,19 @@ struct WalletListener /** * @brief Signalizes device operation progress - */ + * / virtual void onDeviceProgress(const DeviceProgress & event) { (void)event; }; /** * @brief If the listener is created before the wallet this enables to set created wallet object - */ + * / virtual void onSetWallet(std::shared_ptr wallet) { (void)wallet; }; }; /** * @brief Interface for wallet operations. - */ + * / struct Wallet { enum Device { @@ -482,42 +484,42 @@ struct Wallet * \param payment_id - 16 characters hexadecimal string or empty string if new random payment id needs to be * generated * \return - 106 characters string representing integrated address - */ + * / virtual std::string integratedAddress(const std::string &payment_id) const = 0; /*! * \brief secretViewKey - returns secret view key * \return - secret view key - */ + * / virtual std::string secretViewKey() const = 0; /*! * \brief publicViewKey - returns public view key * \return - public view key - */ + * / virtual std::string publicViewKey() const = 0; /*! * \brief secretSpendKey - returns secret spend key * \return - secret spend key - */ + * / virtual std::string secretSpendKey() const = 0; /*! * \brief publicSpendKey - returns public spend key * \return - public spend key - */ + * / virtual std::string publicSpendKey() const = 0; /*! * \brief publicMultisigSignerKey - returns public signer key * \return - public multisignature signer key or empty string if wallet is not multisig - */ + * / virtual std::string publicMultisigSignerKey() const = 0; /*! * \brief stop - interrupts wallet refresh() loop once (doesn't stop background refresh thread) - */ + * / virtual void stop() = 0; /*! @@ -525,17 +527,17 @@ struct Wallet * \param path - main filename to store wallet to. additionally stores address file and keys file. * to store to the same file - just pass empty string; * \return - */ + * / virtual bool store(const std::string &path) = 0; /*! * \brief filename - returns wallet filename * \return - */ + * / virtual std::string filename() const = 0; /*! * \brief keysFilename - returns keys filename. usually this formed as "wallet_filename".keys * \return - */ + * / virtual std::string keysFilename() const = 0; /*! * \brief init - initializes wallet with daemon connection params. @@ -549,7 +551,7 @@ struct Wallet * \param lightWallet - deprecated * \param proxy_address - set proxy address, empty string to disable * \return - true on success - */ + * / virtual bool init(const std::string &daemon_address, uint64_t upper_transaction_size_limit = 0, const std::string &daemon_username = "", const std::string &daemon_password = "", bool use_ssl = false, bool lightWallet = false, const std::string &proxy_address = "") = 0; /*! @@ -558,34 +560,34 @@ struct Wallet * \param password * \param language * \return - true if created successfully - */ + * / virtual bool createWatchOnly(const std::string &path, const std::string &password, const std::string &language) const = 0; /*! * \brief setRefreshFromBlockHeight - start refresh from block height on recover * * \param refresh_from_block_height - blockchain start height - */ + * / virtual void setRefreshFromBlockHeight(uint64_t refresh_from_block_height) = 0; /*! * \brief getRestoreHeight - get wallet creation height * - */ + * / virtual uint64_t getRefreshFromBlockHeight() const = 0; /*! * \brief setRecoveringFromSeed - set state recover form seed * * \param recoveringFromSeed - true/false - */ + * / virtual void setRecoveringFromSeed(bool recoveringFromSeed) = 0; /*! * \brief setRecoveringFromDevice - set state to recovering from device * * \param recoveringFromDevice - true/false - */ + * / virtual void setRecoveringFromDevice(bool recoveringFromDevice) = 0; /*! @@ -593,19 +595,19 @@ struct Wallet * * \param major - size fot the major index * \param minor - size fot the minor index - */ + * / virtual void setSubaddressLookahead(uint32_t major, uint32_t minor) = 0; /** * @brief connectToDaemon - connects to the daemon. TODO: check if it can be removed * @return - */ + * / virtual bool connectToDaemon() = 0; /** * @brief connected - checks if the wallet connected to the daemon * @return - true if connected - */ + * / virtual ConnectionStatus connected() const = 0; virtual void setTrustedDaemon(bool arg) = 0; virtual bool trustedDaemon() const = 0; @@ -628,51 +630,51 @@ struct Wallet /** * @brief watchOnly - checks if wallet is watch only * @return - true if watch only - */ + * / virtual bool watchOnly() const = 0; /** * @brief isDeterministic - checks if wallet keys are deterministic * @return - true if deterministic - */ + * / virtual bool isDeterministic() const = 0; /** * @brief blockChainHeight - returns current blockchain height * @return - */ + * / virtual uint64_t blockChainHeight() const = 0; /** * @brief approximateBlockChainHeight - returns approximate blockchain height calculated from date/time * @return - */ + * / virtual uint64_t approximateBlockChainHeight() const = 0; /** * @brief estimateBlockChainHeight - returns estimate blockchain height. More accurate than approximateBlockChainHeight, * uses daemon height and falls back to calculation from date/time * @return - **/ + ** / virtual uint64_t estimateBlockChainHeight() const = 0; /** * @brief daemonBlockChainHeight - returns daemon blockchain height * @return 0 - in case error communicating with the daemon. * status() will return Status_Error and errorString() will return verbose error description - */ + * / virtual uint64_t daemonBlockChainHeight() const = 0; /** * @brief daemonBlockChainTargetHeight - returns daemon blockchain target height * @return 0 - in case error communicating with the daemon. * status() will return Status_Error and errorString() will return verbose error description - */ + * / virtual uint64_t daemonBlockChainTargetHeight() const = 0; /** * @brief synchronized - checks if wallet was ever synchronized * @return - */ + * / virtual bool synchronized() const = 0; static std::string displayAmount(uint64_t amount); @@ -706,128 +708,128 @@ struct Wallet /** * @brief StartRefresh - Start/resume refresh thread (refresh every 10 seconds) - */ + * / virtual void startRefresh() = 0; /** * @brief pauseRefresh - pause refresh thread - */ + * / virtual void pauseRefresh() = 0; /** * @brief refresh - refreshes the wallet, updating transactions from daemon * @return - true if refreshed successfully; - */ + * / virtual bool refresh() = 0; /** * @brief refreshAsync - refreshes wallet asynchronously. - */ + * / virtual void refreshAsync() = 0; /** * @brief rescanBlockchain - rescans the wallet, updating transactions from daemon * @return - true if refreshed successfully; - */ + * / virtual bool rescanBlockchain() = 0; /** * @brief rescanBlockchainAsync - rescans wallet asynchronously, starting from genesys - */ + * / virtual void rescanBlockchainAsync() = 0; /** * @brief setAutoRefreshInterval - setup interval for automatic refresh. * @param seconds - interval in millis. if zero or less than zero - automatic refresh disabled; - */ + * / virtual void setAutoRefreshInterval(int millis) = 0; /** * @brief autoRefreshInterval - returns automatic refresh interval in millis * @return - */ + * / virtual int autoRefreshInterval() const = 0; /** * @brief addSubaddressAccount - appends a new subaddress account at the end of the last major index of existing subaddress accounts * @param label - the label for the new account (which is the as the label of the primary address (accountIndex,0)) - */ + * / virtual void addSubaddressAccount(const std::string& label) = 0; /** * @brief numSubaddressAccounts - returns the number of existing subaddress accounts - */ + * / virtual size_t numSubaddressAccounts() const = 0; /** * @brief numSubaddresses - returns the number of existing subaddresses associated with the specified subaddress account * @param accountIndex - the major index specifying the subaddress account - */ + * / virtual size_t numSubaddresses(uint32_t accountIndex) const = 0; /** * @brief addSubaddress - appends a new subaddress at the end of the last minor index of the specified subaddress account * @param accountIndex - the major index specifying the subaddress account * @param label - the label for the new subaddress - */ + * / virtual void addSubaddress(uint32_t accountIndex, const std::string& label) = 0; /** * @brief getSubaddressLabel - gets the label of the specified subaddress * @param accountIndex - the major index specifying the subaddress account * @param addressIndex - the minor index specifying the subaddress - */ + * / virtual std::string getSubaddressLabel(uint32_t accountIndex, uint32_t addressIndex) const = 0; /** * @brief setSubaddressLabel - sets the label of the specified subaddress * @param accountIndex - the major index specifying the subaddress account * @param addressIndex - the minor index specifying the subaddress * @param label - the new label for the specified subaddress - */ + * / virtual void setSubaddressLabel(uint32_t accountIndex, uint32_t addressIndex, const std::string &label) = 0; /** * @brief multisig - returns current state of multisig wallet creation process * @return MultisigState struct - */ + * / virtual MultisigState multisig() const = 0; /** * @brief getMultisigInfo * @return serialized and signed multisig info string - */ + * / virtual std::string getMultisigInfo() const = 0; /** * @brief makeMultisig - switches wallet in multisig state. The one and only creation phase for N / N wallets * @param info - vector of multisig infos from other participants obtained with getMulitisInfo call * @param threshold - number of required signers to make valid transaction. Must be <= number of participants * @return in case of N / N wallets returns empty string since no more key exchanges needed. For N - 1 / N wallets returns base58 encoded extra multisig info - */ + * / virtual std::string makeMultisig(const std::vector& info, uint32_t threshold) = 0; /** * @brief exchange_multisig_keys - provides additional key exchange round for arbitrary multisig schemes (like N-1/N, M/N) * @param info - base58 encoded key derivations returned by makeMultisig or exchangeMultisigKeys function call * @param force_update_use_with_caution - force multisig account to update even if not all signers contribute round messages * @return new info string if more rounds required or an empty string if wallet creation is done - */ + * / virtual std::string exchangeMultisigKeys(const std::vector &info, const bool force_update_use_with_caution) = 0; /** * @brief exportMultisigImages - exports transfers' key images * @param images - output paramter for hex encoded array of images * @return true if success - */ + * / virtual bool exportMultisigImages(std::string& images) = 0; /** * @brief importMultisigImages - imports other participants' multisig images * @param images - array of hex encoded arrays of images obtained with exportMultisigImages * @return number of imported images - */ + * / virtual size_t importMultisigImages(const std::vector& images) = 0; /** * @brief hasMultisigPartialKeyImages - checks if wallet needs to import multisig key images from other participants * @return true if there are partial key images - */ + * / virtual bool hasMultisigPartialKeyImages() const = 0; /** * @brief restoreMultisigTransaction creates PendingTransaction from signData * @param signData encrypted unsigned transaction. Obtained with PendingTransaction::multisigSignData * @return PendingTransaction - */ + * / virtual std::unique_ptr restoreMultisigTransaction(const std::string& signData) = 0; /*! @@ -841,7 +843,7 @@ struct Wallet * \param priority * \return PendingTransaction object. caller is responsible to check PendingTransaction::status() * after object returned - */ + * / virtual std::unique_ptr createTransactionMultDest(const std::vector &dst_addr, const std::string &payment_id, optional> amount, uint32_t mixin_count, @@ -860,7 +862,7 @@ struct Wallet * \param priority * \return PendingTransaction object. caller is responsible to check PendingTransaction::status() * after object returned - */ + * / virtual std::unique_ptr createTransaction(const std::string &dst_addr, const std::string &payment_id, optional amount, uint32_t mixin_count, @@ -872,7 +874,7 @@ struct Wallet * \brief createSweepUnmixableTransaction creates transaction with unmixable outputs. * \return PendingTransaction object. caller is responsible to check PendingTransaction::status() * after object returned - */ + * / virtual std::unique_ptr createSweepUnmixableTransaction() = 0; @@ -880,27 +882,27 @@ struct Wallet * \brief loadUnsignedTx - creates transaction from unsigned tx file * \return - UnsignedTransaction object. caller is responsible to check UnsignedTransaction::status() * after object returned - */ + * / virtual std::unique_ptr loadUnsignedTx(const std::string &unsigned_filename) = 0; /*! * \brief submitTransaction - submits transaction in signed tx file * \return - true on success - */ + * / virtual bool submitTransaction(const std::string &fileName) = 0; /*! * \brief disposeTransaction - destroys transaction object * \param t - pointer to the "PendingTransaction" object. Pointer is not valid after function returned; - */ + * / virtual void disposeTransaction(PendingTransaction * t) = 0; /*! * \brief Estimates transaction fee. * \param destinations Vector consisting of pairs. * \return Estimated fee. - */ + * / virtual uint64_t estimateTransactionFee(const std::vector> &destinations, PendingTransaction::Priority priority) const = 0; @@ -909,35 +911,35 @@ struct Wallet * \param filename * \param all - export all key images or only those that have not yet been exported * \return - true on success - */ + * / virtual bool exportKeyImages(const std::string &filename, bool all = false) = 0; /*! * \brief importKeyImages - imports key images from file * \param filename * \return - true on success - */ + * / virtual bool importKeyImages(const std::string &filename) = 0; /*! * \brief importOutputs - exports outputs to file * \param filename * \return - true on success - */ + * / virtual bool exportOutputs(const std::string &filename, bool all = false) = 0; /*! * \brief importOutputs - imports outputs from file * \param filename * \return - true on success - */ + * / virtual bool importOutputs(const std::string &filename) = 0; /*! * \brief scanTransactions - scan a list of transaction ids, this operation may reveal the txids to the remote node and affect your privacy * \param txids - list of transaction ids * \return - true on success - */ + * / virtual bool scanTransactions(const std::vector &txids) = 0; virtual std::shared_ptr history() = 0; @@ -948,12 +950,12 @@ struct Wallet /*! * \brief defaultMixin - returns number of mixins used in transactions * \return - */ + * / virtual uint32_t defaultMixin() const = 0; /*! * \brief setDefaultMixin - setum number of mixins to be used for new transactions * \param arg - */ + * / virtual void setDefaultMixin(uint32_t arg) = 0; /*! @@ -961,26 +963,26 @@ struct Wallet * \param key - the key * \param val - the value * \return true if successful, false otherwise - */ + * / virtual bool setCacheAttribute(const std::string &key, const std::string &val) = 0; /*! * \brief getCacheAttribute - return an arbitrary string attached to a wallet cache attribute * \param key - the key * \return the attached string, or empty string if there is none - */ + * / virtual std::string getCacheAttribute(const std::string &key) const = 0; /*! * \brief setUserNote - attach an arbitrary string note to a txid * \param txid - the transaction id to attach the note to * \param note - the note * \return true if successful, false otherwise - */ + * / virtual bool setUserNote(const std::string &txid, const std::string ¬e) = 0; /*! * \brief getUserNote - return an arbitrary string note attached to a txid * \param txid - the transaction id to attach the note to * \return the attached note, or empty string if there is none - */ + * / virtual std::string getUserNote(const std::string &txid) const = 0; virtual std::string getTxKey(const std::string &txid) const = 0; virtual bool checkTxKey(const std::string &txid, std::string tx_key, const std::string &address, uint64_t &received, bool &in_pool, uint64_t &confirmations) = 0; @@ -991,7 +993,7 @@ struct Wallet /*! * \brief getReserveProof - Generates a proof that proves the reserve of unspent funds * Parameters `account_index` and `amount` are ignored when `all` is true - */ + * / virtual std::string getReserveProof(bool all, uint32_t account_index, uint64_t amount, const std::string &message) const = 0; virtual bool checkReserveProof(const std::string &address, const std::string &message, const std::string &signature, bool &good, uint64_t &total, uint64_t &spent) const = 0; @@ -999,7 +1001,7 @@ struct Wallet * \brief signMessage - sign a message with the spend private key * \param message - the message to sign (arbitrary byte data) * \return the signature - */ + * / virtual std::string signMessage(const std::string &message, const std::string &address = "") = 0; /*! * \brief verifySignedMessage - verify a signature matches a given message @@ -1007,14 +1009,14 @@ struct Wallet * \param address - the address the signature claims to be made with * \param signature - the signature * \return true if the signature verified, false otherwise - */ + * / virtual bool verifySignedMessage(const std::string &message, const std::string &addres, const std::string &signature) const = 0; /*! * \brief signMultisigParticipant signs given message with the multisig public signer key * \param message message to sign * \return signature in case of success. Sets status to Error and return empty string in case of error - */ + * / virtual std::string signMultisigParticipant(const std::string &message) const = 0; /*! * \brief verifyMessageWithPublicKey verifies that message was signed with the given public key @@ -1022,7 +1024,7 @@ struct Wallet * \param publicKey hex encoded public key * \param signature signature of the message * \return true if the signature is correct. false and sets error state in case of error - */ + * / virtual bool verifyMessageWithPublicKey(const std::string &message, const std::string &publicKey, const std::string &signature) const = 0; virtual bool parse_uri(const std::string &uri, std::string &address, std::string &payment_id, uint64_t &amount, std::string &tx_description, std::string &recipient_name, std::vector &unknown_parameters, std::string &error) = 0; @@ -1033,13 +1035,13 @@ struct Wallet /* * \brief rescanSpent - Rescan spent outputs - Can only be used with trusted daemon * \return true on success - */ + * / virtual bool rescanSpent() = 0; /* * \brief setOffline - toggle set offline on/off * \param offline - true/false - */ + * / virtual void setOffline(bool offline) = 0; virtual bool isOffline() const = 0; @@ -1079,7 +1081,7 @@ struct Wallet /*! * \brief Queries backing device for wallet keys * \return Device they are on - */ + * / virtual Device getDeviceType() const = 0; //! cold-device protocol key image sync @@ -1100,7 +1102,7 @@ struct Wallet /** * @brief WalletManager - provides functions to manage wallets - */ + * / struct WalletManager { virtual ~WalletManager() = 0; @@ -1113,7 +1115,7 @@ struct WalletManager * \param nettype Network type * \param kdf_rounds Number of rounds for key derivation function * \return Wallet instance (Wallet::status() needs to be called to check if created successfully) - */ + * / virtual std::unique_ptr createWallet(const std::string &path, const std::string &password, const std::string &language, NetworkType nettype, uint64_t kdf_rounds = 1) = 0; std::unique_ptr createWallet(const std::string &path, const std::string &password, const std::string &language, bool testnet = false) // deprecated { @@ -1128,7 +1130,7 @@ struct WalletManager * \param kdf_rounds Number of rounds for key derivation function * \param listener Wallet listener to set to the wallet after creation * \return Wallet instance (Wallet::status() needs to be called to check if opened successfully) - */ + * / virtual std::shared_ptr openWallet(const std::string &path, const std::string &password, NetworkType nettype, uint64_t kdf_rounds = 1, std::shared_ptr listener = nullptr) = 0; std::shared_ptr openWallet(const std::string &path, const std::string &password, bool testnet = false) // deprecated { @@ -1145,7 +1147,7 @@ struct WalletManager * \param kdf_rounds Number of rounds for key derivation function * \param seed_offset Seed offset passphrase (optional) * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) - */ + * / virtual std::unique_ptr recoveryWallet(const std::string &path, const std::string &password, const std::string &mnemonic, NetworkType nettype = MAINNET, uint64_t restoreHeight = 0, uint64_t kdf_rounds = 1, const std::string &seed_offset = {}) = 0; @@ -1163,7 +1165,7 @@ struct WalletManager * \param nettype Network type * \param restoreHeight restore from start height * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) - */ + * / virtual std::unique_ptr recoveryWallet(const std::string &path, const std::string &mnemonic, NetworkType nettype, uint64_t restoreHeight = 0) = 0; std::unique_ptr recoveryWallet(const std::string &path, const std::string &mnemonic, bool testnet = false, uint64_t restoreHeight = 0) // deprecated { @@ -1182,7 +1184,7 @@ struct WalletManager * \param spendKeyString spend key (optional) * \param kdf_rounds Number of rounds for key derivation function * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) - */ + * / virtual std::unique_ptr createWalletFromKeys(const std::string &path, const std::string &password, const std::string &language, @@ -1215,7 +1217,7 @@ struct WalletManager * \param viewKeyString view key * \param spendKeyString spend key (optional) * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) - */ + * / virtual std::unique_ptr createWalletFromKeys(const std::string &path, const std::string &language, NetworkType nettype, @@ -1245,7 +1247,7 @@ struct WalletManager * \param kdf_rounds Number of rounds for key derivation function * \param listener Wallet listener to set to the wallet after creation * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) - */ + * / virtual std::unique_ptr createWalletFromDevice(const std::string &path, const std::string &password, NetworkType nettype, @@ -1259,18 +1261,18 @@ struct WalletManager * \brief Closes wallet. In case operation succeeded, wallet object deleted. in case operation failed, wallet object not deleted * \param wallet previously opened / created wallet instance * \return None - */ + * / virtual bool closeWallet(std::unique_ptr wallet, bool store = true) = 0; /* * ! checks if wallet with the given name already exists - */ + * / /*! * @brief TODO: delme walletExists - check if the given filename is the wallet * @param path - filename * @return - true if wallet exists - */ + * / virtual bool walletExists(const std::string &path) = 0; /*! @@ -1284,7 +1286,7 @@ struct WalletManager * @note * This function will fail when the wallet keys file is opened because the wallet program locks the keys file. * In this case, Wallet::unlockKeysFile() and Wallet::lockKeysFile() need to be called before and after the call to this function, respectively. - */ + * / virtual bool verifyWalletPassword(const std::string &keys_file_name, const std::string &password, bool no_spend_key, uint64_t kdf_rounds = 1) const = 0; /*! @@ -1296,14 +1298,14 @@ struct WalletManager * * for verification only - determines key storage hardware * - */ + * / virtual bool queryWalletDevice(Wallet::Device& device_type, const std::string &keys_file_name, const std::string &password, uint64_t kdf_rounds = 1) const = 0; /*! * \brief findWallets - searches for the wallet files by given path name recursively * \param path - starting point to search * \return - list of strings with found wallets (absolute paths); - */ + * / virtual std::vector findWallets(const std::string &path) = 0; //! returns verbose error string regarding last error; @@ -1352,7 +1354,7 @@ struct WalletManager //! sets proxy address, empty string to disable virtual bool setProxy(const std::string &address) = 0; }; - +*/ struct WalletManagerFactory { @@ -1368,7 +1370,7 @@ struct WalletManagerFactory LogLevel_Max = LogLevel_4 }; - static std::unique_ptr getWalletManager(); + static Monero::WalletManager* getWalletManager(); static void setLogLevel(int level); static void setLogCategories(const std::string &categories); }; diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 85f3fcf..3cae6af 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -30,10 +30,12 @@ include_directories(.) # For both the server and admin utility. set(monero-lwsf_sources + address_book.cpp backend.cpp error.cpp pending_transaction.cpp rpc.cpp + subaddress_account.cpp transaction_history.cpp transaction_info.cpp wallet.cpp diff --git a/src/address_book.cpp b/src/address_book.cpp new file mode 100644 index 0000000..94f4b65 --- /dev/null +++ b/src/address_book.cpp @@ -0,0 +1,203 @@ +// Copyright (c) 2025, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "address_book.h" + +#include +#include +#include "backend.h" +#include "cryptonote_basic/cryptonote_basic_impl.h" + +namespace lwsf { namespace internal { + + namespace + { + void clear_addresses(std::vector& rows) noexcept + { + for (const auto row : rows) + delete row; + rows.clear(); + } + + struct force_refresh_ + { + void operator()(address_book* ptr) const noexcept + { + try + { + ptr->refresh(); + } + catch (...) + {} + } + }; + + using force_refresh = std::unique_ptr; + } + + void address_book::clear_status() + { + error_string_.clear(); + error_ = Status_Ok; + } + + address_book::address_book(std::shared_ptr data) + : data_(std::move(data)), addresses_(), error_string_(), error_(Status_Ok) + {} + + address_book::~address_book() + { + clear_addresses(addresses_); + } + + bool address_book::addRow(const std::string &dst_addr , const std::string &payment_id, const std::string &description) + { + clear_status(); + + cryptonote::address_parse_info info; + if(!cryptonote::get_account_address_from_str(info, data_->get_net_type(), dst_addr)) + { + error_string_ = "Invalid destination address"; + error_ = Invalid_Address; + return false; + } + + if (!payment_id.empty() && payment_id.size() != sizeof(crypto::hash8) * 2 && payment_id.size() != sizeof(crypto::hash) * 2) + { + error_string_ = "Invalid payment id"; + error_ = Invalid_Payment_Id; + return false; + } + + force_refresh force{this}; + auto row = std::make_unique(addresses_.size(), dst_addr, payment_id, description); + addresses_.push_back(row.get()); + row.release(); + + const boost::lock_guard lock{data_->sync}; + data_->primary.addressbook.push_back( + backend::address_book_entry{dst_addr, payment_id, description} + ); + + force.release(); + return true; + } + + bool address_book::deleteRow(std::size_t rowId) + { + if (addresses_.size() <= rowId) + return false; + + clear_status(); + force_refresh force{this}; + + const std::unique_ptr destroy{addresses_[rowId]}; + addresses_[rowId] = nullptr; + addresses_.erase(addresses_.begin() + rowId); + + const boost::lock_guard lock{data_->sync}; + if (data_->primary.addressbook.size() <= rowId) + return false; + + data_->primary.addressbook.erase(data_->primary.addressbook.begin() + rowId); + force.release(); + return true; + } + + bool address_book::setDescription(std::size_t index, const std::string &description) + { + clear_status(); + if (addresses_.size() <= index) + return false; + + force_refresh force{this}; + + const std::unique_ptr destroy{addresses_[index]}; + addresses_[index] = nullptr; + addresses_[index] = new Monero::AddressBookRow{ + index, destroy->getAddress(), destroy->getPaymentId(), description + }; + + const boost::lock_guard lock{data_->sync}; + if (data_->primary.addressbook.size() <= index) + return false; + + data_->primary.addressbook[index].description = description; + force.release(); + return true; + } + + void address_book::refresh() + { + try + { + clear_addresses(addresses_); + + const boost::lock_guard lock{data_->sync}; + addresses_.resize(data_->primary.addressbook.size()); + + for (std::size_t i = 0; i < addresses_.size(); ++i) + { + const auto& current = data_->primary.addressbook[i]; + addresses_[i] = new Monero::AddressBookRow{ + i, current.address, current.payment_id, current.description + }; + } + } + catch (...) + { + clear_addresses(addresses_); + } + } + + int address_book::lookupPaymentID(const std::string &payment_id) const + { + static constexpr const auto int_max = std::numeric_limits::max(); + static_assert(int_max <= std::numeric_limits::max()); + const std::size_t end = std::min(std::size_t(int_max), addresses_.size()); + + // from primary implementation + std::string long_payment_id = payment_id; + long_payment_id.resize(64, '0'); + + for (std::size_t i = 0; i < end; ++i) + { + std::string current = addresses_[i]->getPaymentId(); + if (payment_id == current) + return i; + if (long_payment_id == current) + return i; + // also from primary implementation + current.resize(64, '0'); + if (payment_id == current) + return i; + } + + return -1; + } +}} // lwsf // internal diff --git a/src/address_book.h b/src/address_book.h new file mode 100644 index 0000000..4002bf4 --- /dev/null +++ b/src/address_book.h @@ -0,0 +1,70 @@ +// Copyright (c) 2025, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include +#include +#include +#include +#include "lws_frontend.h" +#include "wallet/api/wallet2_api.h" // monero/src + +namespace lwsf { namespace internal { + namespace backend { struct wallet; } + + class address_book final : public ::Monero::AddressBook + { + const std::shared_ptr data_; + std::vector addresses_; + std::string error_string_; + ErrorCode error_; + + void clear_status(); + + public: + + explicit address_book(std::shared_ptr data); + + address_book(const address_book&) = delete; + address_book(address_book&&) = delete; + virtual ~address_book() override; + address_book& operator=(const address_book&) = delete; + address_book& operator=(address_book&&) = delete; + + virtual std::vector getAll() const override { return addresses_; } + virtual bool addRow(const std::string &dst_addr , const std::string &payment_id, const std::string &description) override; + virtual bool deleteRow(std::size_t rowId) override; + virtual bool setDescription(std::size_t index, const std::string &description) override; + virtual void refresh() override; + virtual std::string errorString() const override { return error_string_; } + virtual int errorCode() const override { return error_; } + virtual int lookupPaymentID(const std::string &payment_id) const override; + + }; +}} // lwsf // internal diff --git a/src/backend.cpp b/src/backend.cpp index b32b0c5..0024320 100644 --- a/src/backend.cpp +++ b/src/backend.cpp @@ -30,6 +30,7 @@ #include #include "cryptonote_basic/cryptonote_basic_impl.h" // monero/src +#include "error.h" #include "lwsf_config.h" #include "ringct/rctOps.h" #include "wire.h" @@ -37,25 +38,27 @@ #include "wire/adapted/pair.h" #include "wire/msgpack.h" #include "wire/wrapper/trusted_array.h" +#include "wire/wrapper/variant.h" -namespace lwsf +namespace Monero { WIRE_AS_INTEGER(TransactionInfo::Direction); - WIRE_AS_INTEGER(NetworkType); + WIRE_AS_INTEGER(Monero::NetworkType); } + namespace lwsf { namespace internal { namespace backend { namespace { - cryptonote::network_type convert_net_type(const NetworkType in) + cryptonote::network_type convert_net_type(const Monero::NetworkType in) { switch(in) { - case NetworkType::MAINNET: + case Monero::NetworkType::MAINNET: return cryptonote::network_type::MAINNET; - case NetworkType::TESTNET: + case Monero::NetworkType::TESTNET: return cryptonote::network_type::TESTNET; - case NetworkType::STAGENET: + case Monero::NetworkType::STAGENET: return cryptonote::network_type::STAGENET; default: break; @@ -63,6 +66,71 @@ namespace lwsf { namespace internal { namespace backend return cryptonote::network_type::UNDEFINED; } + bool is_tx_spendtime_unlocked(const std::uint64_t chain_height, const std::uint64_t unlock_time, const std::uint64_t block_height, Monero::NetworkType nettype_in) + { + const auto nettype = convert_net_type(nettype_in); + if(unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER) + { + //interpret as block index + if(chain_height - 1 + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time) + return true; + else + return false; + }else + { + //interpret as time + const uint64_t adjusted_time = std::time(nullptr); + // XXX: this needs to be fast, so we'd need to get the starting heights + // from the daemon to be correct once voting kicks in + uint64_t v2height = nettype == cryptonote::TESTNET ? 624634 : nettype == cryptonote::STAGENET ? 32000 : 1009827; + uint64_t leeway = chain_height < v2height ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2; + if(adjusted_time + leeway >= unlock_time) + return true; + else + return false; + } + return false; + } + + crypto::secret_key get_subaddress_secret_key(const crypto::secret_key &a, const std::uint32_t major, const std::uint32_t minor) + { + char data[sizeof(::config::HASH_KEY_SUBADDRESS) + sizeof(crypto::secret_key) + 2 * sizeof(uint32_t)]; + memcpy(data, ::config::HASH_KEY_SUBADDRESS, sizeof(::config::HASH_KEY_SUBADDRESS)); + memcpy(data + sizeof(::config::HASH_KEY_SUBADDRESS), &a, sizeof(crypto::secret_key)); + std::uint32_t idx = SWAP32LE(major); + memcpy(data + sizeof(::config::HASH_KEY_SUBADDRESS) + sizeof(crypto::secret_key), &idx, sizeof(uint32_t)); + idx = SWAP32LE(minor); + memcpy(data + sizeof(::config::HASH_KEY_SUBADDRESS) + sizeof(crypto::secret_key) + sizeof(uint32_t), &idx, sizeof(uint32_t)); + crypto::secret_key m; + crypto::hash_to_scalar(data, sizeof(data), m); + return m; + } + + template + void map_address_book_entry(F& format, T& self) + { + wire::object(format, + WIRE_FIELD(address), + WIRE_FIELD(payment_id), + WIRE_FIELD(description) + ); + } + + template + void map_subaddress(F& format, T& self) + { + wire::object(format, WIRE_FIELD(label)); + } + + template + void map_sub_account(F& format, T& self) + { + wire::object(format, + wire::field("minor", wire::trusted_array(std::ref(self.minor))), + WIRE_FIELD(label) + ); + } + template void map_transfer_out(F& format, T& self) { @@ -88,24 +156,24 @@ namespace lwsf { namespace internal { namespace backend WIRE_FIELD(tx_pub) ); } - } // anonymous - namespace - { template void map_transaction(F& format, T& self) { //! TODO complete payment_id storage + auto payment_id = wire::variant(std::ref(self.payment_id)); wire::object(format, wire::field("spends", wire::trusted_array(std::ref(self.spends))), wire::field("receives", wire::trusted_array(std::ref(self.receives))), WIRE_FIELD(description), - WIRE_FIELD(label), WIRE_OPTIONAL_FIELD(timestamp), WIRE_FIELD(amount), WIRE_OPTIONAL_FIELD(height), WIRE_FIELD(unlock_time), WIRE_FIELD(direction), + WIRE_OPTION("payment_id0", rpc::empty, payment_id), + WIRE_OPTION("payment_id8", crypto::hash8, payment_id), + WIRE_OPTION("payment_id32", crypto::hash, payment_id), WIRE_FIELD(id), WIRE_FIELD(prefix), WIRE_FIELD(coinbase) @@ -139,7 +207,10 @@ namespace lwsf { namespace internal { namespace backend void map_account(F& format, T& self) { wire::object(format, + wire::field("addressbook", wire::trusted_array(std::ref(self.addressbook))), + wire::field("subaccounts", wire::trusted_array(std::ref(self.subaccounts))), wire::field("txes", wire::trusted_array(std::ref(self.txes))), + wire::field("attributes", wire::trusted_array(std::ref(self.attributes))), WIRE_FIELD(scan_height), WIRE_FIELD(restore_height), WIRE_FIELD(type), @@ -235,12 +306,12 @@ namespace lwsf { namespace internal { namespace backend if (rpc::uint64_string(total_spent) < source.total_received) { - out.direction = TransactionInfo::Direction::In; + out.direction = Monero::TransactionInfo::Direction_In; out.amount = std::uint64_t(source.total_received) - total_spent; } else { - out.direction = TransactionInfo::Direction::Out; + out.direction = Monero::TransactionInfo::Direction_Out; out.amount = total_spent - std::uint64_t(source.total_received); } } @@ -307,7 +378,7 @@ namespace lwsf { namespace internal { namespace backend else inserted.first->second = std::make_shared(); - if (existing != self.primary.txes.end()) + if (existing == self.primary.txes.end()) out.push_back(inserted.first->second); } update_tx(self.primary, *inserted.first->second, tx); @@ -332,8 +403,33 @@ namespace lwsf { namespace internal { namespace backend return out; } + + void merge_subaddrs(account& self, const epee::span subaddrs) + { + /* This will purge subaddresses that the server somehow no longer claims + as being valid. The existing info per subaddress is moved/preserved. */ + + std::map subaccounts; + subaccounts.swap(self.subaccounts); + + for (const auto& subaddr : subaddrs) + { + auto& account = self.subaccounts[subaddr.key]; + auto& old = subaccounts[subaddr.key]; + for (const auto& minors : subaddr.value) + { + for (std::uint32_t minor = std::get<0>(minors); minor < std::uint64_t(std::get<1>(minors)) + 1; ++minor) + { + auto elem = account.minor.try_emplace(minor); + if (elem.second) + elem.first->second = std::move(old.minor[minor]); + } + } + } + } } // anonymous + WIRE_DEFINE_OBJECT(address_book_entry, map_address_book_entry); WIRE_DEFINE_OBJECT(transfer_out, map_transfer_out); WIRE_DEFINE_OBJECT(transfer_in, map_transfer_in); WIRE_DEFINE_OBJECT(transaction, map_transaction); @@ -348,6 +444,18 @@ namespace lwsf { namespace internal { namespace backend void write_bytes(wire::writer& dest, const account& source) { map_account(dest, source); } + bool transaction::is_unlocked(const std::uint64_t chain_height, const Monero::NetworkType type) const + { + const std::uint64_t the_height = height.value_or(std::numeric_limits::max()); + if(!is_tx_spendtime_unlocked(chain_height, unlock_time, the_height, type)) + return false; + + if(the_height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE > chain_height) + return false; + + return true; + } + wallet::wallet() : listener(nullptr), client(), @@ -356,7 +464,37 @@ namespace lwsf { namespace internal { namespace backend blockchain_height(0), fee_mask(0), sync() - {} + { + primary.subaccounts[0].minor[0]; + } + + cryptonote::network_type wallet::get_net_type() const + { return convert_net_type(primary.type); } + + crypto::public_key wallet::get_spend_public(const rpc::address_meta& index) const + { + if (index.maj_i == 0 && index.min_i == 0) + return primary.spend.pub; + + // m = Hs(a || index_major || index_minor) + crypto::secret_key m = get_subaddress_secret_key(primary.view.sec, index.maj_i, index.min_i); + + // M = m*G + crypto::public_key M; + crypto::secret_key_to_public_key(m, M); + + // D = B + M + return rct::rct2pk(rct::addKeys(rct::pk2rct(primary.spend.pub), rct::pk2rct(M))); + } + + std::string wallet::get_spend_address(const rpc::address_meta& index) const + { + return cryptonote::get_account_address_as_str( + get_net_type(), + (index.maj_i != 0 || index.min_i != 0), + cryptonote::account_public_address{get_spend_public(index), primary.view.pub} + ); + } expect wallet::to_bytes() const { @@ -387,18 +525,27 @@ namespace lwsf { namespace internal { namespace backend std::error_code wallet::login() { - const boost::lock_guard lock{sync}; + { + const rpc::login_request login{ + primary.address, primary.view.sec, true, primary.generated_locally + }; - const rpc::login_request login{ - primary.address, primary.view.sec, true, primary.generated_locally - }; + const auto response = rpc::invoke(client, login); + if (!response) + return response.error(); - const auto response = rpc::invoke(client, login); - if (!response) - return response.error(); + const boost::lock_guard lock{sync}; + if (response->start_height) + primary.restore_height = *response->start_height; + } - if (response->start_height) - primary.restore_height = *response->start_height; + const rpc::login login{primary.address, primary.view.sec}; + const auto response = rpc::invoke(client, login); + if (response) + { + const boost::lock_guard lock{sync}; + merge_subaddrs(primary, epee::to_span(response->all_subaddrs)); + } return {}; } @@ -439,40 +586,90 @@ namespace lwsf { namespace internal { namespace backend const auto new_txes = merge_response(*this, *txs_response, *outs_response); last_sync = std::chrono::steady_clock::now().time_since_epoch().count(); + const boost::lock_guard lock2{sync_listener}; if (!listener) return {}; - // Call listener functions without holding lock, in case a call is made + // Call listener functions without holding `sync`, in case a call is made // back into the library. const std::uint64_t new_scan_height = std::max(orig_scan_height, primary.scan_height); - const std::shared_ptr listener_copy = listener; lock.unlock(); - listener_copy->refreshed(); - if (!new_txes.empty()) - listener_copy->updated(); + listener->refreshed(); + if (!new_txes.empty() || new_scan_height - orig_scan_height) + listener->updated(); for (std::uint64_t i = orig_scan_height; i < new_scan_height; ++i) - listener_copy->newBlock(i); + listener->newBlock(i); for (const auto& tx : new_txes) { const auto txid = epee::string_tools::pod_to_hex(tx->id); - if (tx->direction == TransactionInfo::Direction::In) + if (tx->direction == Monero::TransactionInfo::Direction_In) { if (tx->height) - listener_copy->moneyReceived(txid, tx->amount); + listener->moneyReceived(txid, tx->amount); else - listener_copy->unconfirmedMoneyReceived(txid, tx->amount); + listener->unconfirmedMoneyReceived(txid, tx->amount); } else - listener_copy->moneySpent(txid, tx->amount); + listener->moneySpent(txid, tx->amount); } return {}; } + std::error_code wallet::add_subaccount(std::string label) + { + for (unsigned i = 0; i < config::subaddr_retry; ++i) + { + std::size_t next = -1; + { + const boost::lock_guard lock{sync}; + for (const auto& account : primary.subaccounts) + { + if (account.first != next + 1) + break; + ++next; + } + ++next; + } + + if (std::numeric_limits::max() < next) + return {error::rpc_failure}; + + const rpc::provision_subaddrs_request request{ + rpc::login{primary.address, primary.view.sec}, std::uint32_t(next), 0, 1, 1, true + }; + const auto response = rpc::invoke(client, request); + if (!response) + return response.error(); + + bool matched = false; + const boost::lock_guard lock{sync}; + for (const auto& major : response->new_subaddrs) + { + auto& account = primary.subaccounts[major.key]; + for (const auto& minors : major.value) + { + for (std::uint32_t i = std::get<0>(minors); i < std::uint64_t(std::get<1>(minors)) + 1; ++i) + { + account.minor[i].label = std::move(label); + label.clear(); + matched = true; + } + } + } + + if (matched) + return {}; + else + merge_subaddrs(primary, epee::to_span(response->all_subaddrs)); + } + return {error::rpc_failure}; + } + std::error_code wallet::send_tx(epee::byte_slice tx_bytes) { const rpc::submit_raw_tx_request request{std::move(tx_bytes)}; diff --git a/src/backend.h b/src/backend.h index 2df5b54..5c523c6 100644 --- a/src/backend.h +++ b/src/backend.h @@ -35,20 +35,22 @@ #include #include #include +#include #include #include #include #include #include -#include "byte_slice.h" // monero/contrib/epee/include -#include "common/expect.h" // moneor/src -#include "crypto/crypto.h" // monero/src -#include "crypto/hash.h" // monero/src -#include "lws_frontend.h" -#include "net/http_client.h" // monero/contrib/epee/include -#include "ringct/rctTypes.h" // monero/src +#include "byte_slice.h" // monero/contrib/epee/include +#include "common/expect.h" // moneor/src +#include "crypto/crypto.h" // monero/src +#include "crypto/hash.h" // monero/src +#include "cryptonote_config.h" // monero/src +#include "net/http_client.h" // monero/contrib/epee/include +#include "ringct/rctTypes.h" // monero/src #include "rpc.h" +#include "wallet/api/wallet2_api.h" // monero/src #include "wire/fwd.h" namespace lwsf { namespace internal { namespace backend @@ -63,6 +65,26 @@ namespace lwsf { namespace internal { namespace backend } }; + struct address_book_entry + { + std::string address; + std::string payment_id; + std::string description; + }; + WIRE_DECLARE_OBJECT(address_book_entry); + + struct subaddress + { + std::string label; + }; + WIRE_DECLARE_OBJECT(subaddress); + + struct sub_account + { + boost::container::flat_map minor; + }; + WIRE_DECLARE_OBJECT(sub_account); + struct transfer_out { std::string address; @@ -73,13 +95,13 @@ namespace lwsf { namespace internal { namespace backend crypto::public_key output_pub; transfer_out() - : address(), amount(0), sender{}, secret(), tx_pub{}, outpub_pub{} + : address(), amount(0), sender{}, secret(), tx_pub{}, output_pub{} {} }; WIRE_DECLARE_OBJECT(transfer_out); struct transfer_in - { + { std::uint64_t global_index; std::uint64_t amount; rpc::address_meta recipient; @@ -104,13 +126,12 @@ namespace lwsf { namespace internal { namespace backend : spends(), receives(), description(), - label(), timestamp(), amount(0), fee(0), height(), unlock_time(0), - direction(TransactionInfo::Direction::Out), + direction(Monero::TransactionInfo::Direction_Out), payment_id(), id{}, prefix{}, @@ -122,20 +143,21 @@ namespace lwsf { namespace internal { namespace backend transaction& operator=(transaction&&) = default; transaction& operator=(const transaction&) = default; + bool is_unlocked(std::uint64_t chain_height, Monero::NetworkType type) const; + /*! flat_map is used here for faster copies/merging. A single allocation is needed in the copy (done every refresh interval), instead of an allocation per key. */ boost::container::flat_map spends; boost::container::flat_map receives; //!< Key is output pub std::string description; - std::string label; std::optional timestamp; std::uint64_t amount; std::uint64_t fee; std::optional height; std::uint64_t unlock_time; - TransactionInfo::Direction direction; - std::variant payment_id; + Monero::TransactionInfo::Direction direction; + std::variant payment_id; crypto::hash id; crypto::hash prefix; bool coinbase; @@ -153,11 +175,15 @@ namespace lwsf { namespace internal { namespace backend struct account { account() = delete; + std::string address; //!> not serialized, recovered on read_bytes + std::vector addressbook; + std::map subaccounts; boost::container::flat_map, memory> txes; + std::map attributes; std::uint64_t scan_height; std::uint64_t restore_height; - NetworkType type; + Monero::NetworkType type; keypair view; keypair spend; bool generated_locally; @@ -166,7 +192,7 @@ namespace lwsf { namespace internal { namespace backend struct wallet { - std::shared_ptr listener; + Monero::WalletListener* listener; rpc::http_client client; account primary; std::atomic last_sync; @@ -174,9 +200,14 @@ namespace lwsf { namespace internal { namespace backend std::uint64_t per_byte_fee; std::uint64_t fee_mask; mutable boost::mutex sync; + boost::mutex sync_listener; wallet(); + cryptonote::network_type get_net_type() const; + crypto::public_key get_spend_public(const rpc::address_meta& index) const; + std::string get_spend_address(const rpc::address_meta& index) const; + //! Serializate `this` wallet to msgpack. Locks contents. expect to_bytes() const; @@ -186,6 +217,8 @@ namespace lwsf { namespace internal { namespace backend //! Attempt std::error_code login(); + std::error_code add_subaccount(std::string label); + //! Refreshes txes information. Strong exception guarantee. Locks contents. std::error_code refresh(bool mandatory = false); diff --git a/src/error.cpp b/src/error.cpp new file mode 100644 index 0000000..4e7db1c --- /dev/null +++ b/src/error.cpp @@ -0,0 +1,59 @@ +// Copyright (c) 2024, The Monero Project +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "error.h" + +namespace lwsf +{ + const char* get_string(const error value) noexcept + { + switch (value) + { + default: + break; + } + return "Unknown wallet error"; + } + + const std::error_category& error_category() noexcept + { + struct category final : std::error_category + { + virtual const char* name() const noexcept override final + { + return "lws::error_category()"; + } + + virtual std::string message(int value) const override final + { + return get_string(error(value)); + } + }; + static const category instance{}; + return instance; + } +} // lwsf diff --git a/src/error.h b/src/error.h new file mode 100644 index 0000000..84fe164 --- /dev/null +++ b/src/error.h @@ -0,0 +1,68 @@ +// Copyright (c) 2024, The Monero Project +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include + +namespace lwsf +{ + enum class error : int + { + none = 0, //!< Must be zero for `expect<..>` + connect_failure, //!< Connection to server failed + crypto_failure, //!< Failure in crypto + invalid_encoding, //!< Invalid percent encoding + invalid_scheme, //!< Invalid network scheme + read_failure, //!< Failed to read file + rpc_failure, //!< RPC failed + unexpected_userinfo,//!< Unexpected user+pass provided + unsupported_format, //!< File format could not be unpacked + write_failure //!< Failed to write file + }; + + //! \return Error message string. + const char* get_string(error value) noexcept; + + //! \return Category for `schema_error`. + const std::error_category& error_category() noexcept; + + //! \return Error code with `value` and `schema_category()`. + inline std::error_code make_error_code(const error value) noexcept + { + return std::error_code{int(value), error_category()}; + } + +} // lwsf + +namespace std +{ + template<> + struct is_error_code_enum + : true_type + {}; +} diff --git a/src/lwsf_config.h b/src/lwsf_config.h index c9b1832..c1655b6 100644 --- a/src/lwsf_config.h +++ b/src/lwsf_config.h @@ -33,7 +33,9 @@ namespace lwsf { namespace config constexpr const std::chrono::seconds connect_timeout{2}; constexpr const std::chrono::seconds daemon_status_cache{10}; constexpr const std::size_t initial_buffer_size = 1024 * 64; // 64 KiB + constexpr const std::size_t max_txes_in_rpc = 2048; + constexpr const std::uint32_t mixin_default = 16; constexpr const std::chrono::seconds refresh_interval{30}; constexpr const std::chrono::seconds rpc_timeout{5}; - constexpr const std::size_t max_txes_in_rpc = 2048; + constexpr const unsigned subaddr_retry{10}; }} // lwsf // config diff --git a/src/pending_transaction.cpp b/src/pending_transaction.cpp new file mode 100644 index 0000000..e51c2e2 --- /dev/null +++ b/src/pending_transaction.cpp @@ -0,0 +1,76 @@ +// Copyright (c) 2024, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "pending_transaction.h" + +#include +#include "backend.h" +#include "byte_slice.h" // monero/contrib/epee/include +#include "cryptonote_basic/cryptonote_format_utils.h" // monero/src +#include "string_tools.h" // monero/contrib/epee/include + + +namespace lwsf { namespace internal +{ + pending_transaction::pending_transaction(std::shared_ptr wallet, cryptonote::transaction&& source, Priority priority) + : wallet_(std::move(wallet)), source_(std::move(source)), error_(), priority_(priority) + { + if (!wallet_) + throw std::invalid_argument{"lwsf::internal::pending_transction cannot be given nullptr backend"}; + } + + pending_transaction::~pending_transaction() + {} + + std::string pending_transaction::errorString() const + { + if (!error_) + return {}; + return error_.message(); + } + + bool pending_transaction::commit(const std::string &filename, bool) + { + // saving to file not yet implemented + if (!filename.empty()) + return false; + + error_ = wallet_->send_tx( + epee::byte_slice{cryptonote::t_serializable_object_to_blob(source_)} + ); + return !error_; + } + + std::uint64_t pending_transaction::fee() const + { return get_tx_fee(source_); } + + std::vector pending_transaction::txid() const + { + return {epee::string_tools::pod_to_hex(get_transaction_hash(source_))}; + } +}} // lwsf // internal diff --git a/src/pending_transaction.h b/src/pending_transaction.h new file mode 100644 index 0000000..ebb9bd4 --- /dev/null +++ b/src/pending_transaction.h @@ -0,0 +1,95 @@ +// Copyright (c) 2024, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include +#include +#include +#include +#include "cryptonote_basic/cryptonote_basic.h" // monero/src +#include "wallet/api/wallet2_api.h" // moneor/src + +namespace lwsf { namespace internal +{ + namespace backend { struct wallet; } + + class pending_transaction final : public Monero::PendingTransaction + { + const std::shared_ptr wallet_; + const cryptonote::transaction source_; + std::error_code error_; + const Priority priority_; + + public: + pending_transaction(std::shared_ptr wallet, cryptonote::transaction&& source, Priority priority); + + pending_transaction(pending_transaction&&) = delete; + pending_transaction(const pending_transaction&) = delete; + + virtual ~pending_transaction() override final; + + pending_transaction& operator=(pending_transaction&&) = delete; + pending_transaction& operator=(const pending_transaction&) = delete; + + virtual int status() const override final { return priority_; } + virtual std::string errorString() const override final; + virtual bool commit(const std::string &filename = "", bool overwrite = false) override final; + virtual std::uint64_t amount() const = 0; + virtual std::uint64_t dust() const override final { return 0; } + virtual std::uint64_t fee() const override final; + virtual std::vector txid() const override final; + virtual std::uint64_t txCount() const override final { return 1; } + virtual std::vector subaddrAccount() const = 0; + virtual std::vector> subaddrIndices() const = 0; + + /** + * @brief multisigSignData + * @return encoded multisig transaction with signers' keys. + * Transfer this data to another wallet participant to sign it. + * Assumed use case is: + * 1. Initiator: + * auto data = pendingTransaction->multisigSignData(); + * 2. Signer1: + * pendingTransaction = wallet->restoreMultisigTransaction(data); + * pendingTransaction->signMultisigTx(); + * auto signed = pendingTransaction->multisigSignData(); + * 3. Signer2: + * pendingTransaction = wallet->restoreMultisigTransaction(signed); + * pendingTransaction->signMultisigTx(); + * pendingTransaction->commit(); + */ + virtual std::string multisigSignData() = 0; + virtual void signMultisigTx() = 0; + /** + * @brief signersKeys + * @return vector of base58-encoded signers' public keys + */ + virtual std::vector signersKeys() const = 0; + }; +}} // lwsf // internal diff --git a/src/rpc.cpp b/src/rpc.cpp index c6da6b4..83c9850 100644 --- a/src/rpc.cpp +++ b/src/rpc.cpp @@ -38,6 +38,7 @@ #include "net/http_client.h" // monero/contrib/epee/include #include "ringct/rctOps.h" // monero/contrib/epee/include #include "wire.h" +#include "wire/adapted/array.h" #include "wire/adapted/crypto.h" #include "wire/field.h" #include "wire/json.h" @@ -103,6 +104,10 @@ namespace lwsf { namespace internal { namespace rpc return response->m_body; } + void write_bytes(wire::writer& dest, const empty&) + { dest.boolean(true); } + void read_bytes(wire::reader& source, const empty&) + { source.boolean(); } void write_bytes(wire::json_writer& dest, const login& self) { @@ -186,7 +191,7 @@ namespace lwsf { namespace internal { namespace rpc WIRE_DLOG_THROW(wire::error::schema::fixed_binary, "Invalid payment_id size"); } else - self.payment_id = nullptr; + self.payment_id = empty{}; self.timestamp.reset(); @@ -214,6 +219,12 @@ namespace lwsf { namespace internal { namespace rpc ); } + void read_bytes(wire::json_reader& source, get_subaddrs& self) + { + using limits = wire::max_element_count<16384>; + wire::object(source, WIRE_FIELD_ARRAY(all_subaddrs, limits)); + } + namespace { // This field is a mess between implementations, this cleans it up a bit @@ -299,6 +310,35 @@ namespace lwsf { namespace internal { namespace rpc } + void read_bytes(wire::json_reader& source, subaddrs& self) + { + using limits = wire::min_element_size<2>; + wire::object(source, WIRE_FIELD(key), WIRE_FIELD_ARRAY(value, limits)); + } + + void write_bytes(wire::json_writer& dest, const provision_subaddrs_request& self) + { + wire::object(dest, + wire::field("address", std::cref(self.creds.address)), + wire::field("view_key", std::cref(self.creds.view_key)), + WIRE_FIELD(maj_i), + WIRE_FIELD(min_i), + WIRE_FIELD(n_maj), + WIRE_FIELD(n_min), + WIRE_FIELD(get_all) + ); + } + + void read_bytes(wire::json_reader& source, provision_subaddrs_response& self) + { + using limits = wire::max_element_count<16384>; + wire::object(source, + WIRE_FIELD_ARRAY(new_subaddrs, limits), + WIRE_FIELD_ARRAY(all_subaddrs, limits) + ); + } + + void write_bytes(wire::json_writer& dest, const submit_raw_tx_request& self) { wire::object(dest, WIRE_FIELD(tx)); diff --git a/src/rpc.h b/src/rpc.h index fcd9367..32e6b72 100644 --- a/src/rpc.h +++ b/src/rpc.h @@ -65,7 +65,6 @@ namespace lwsf { namespace internal { namespace rpc return std::error_code{int(value), error_category()}; } - //! Send `payload` to `client` at uri `endpoint`, and \return payload response expect invoke_payload(http_client& client, boost::string_ref endpoint, epee::byte_slice payload); @@ -88,12 +87,8 @@ namespace lwsf { namespace internal { namespace rpc return out; } - struct empty - { - empty() = delete; - }; - inline void write_bytes(const wire::json_writer&, const empty&) - {} + struct empty {}; + WIRE_DECLARE_OBJECT(empty); struct login { @@ -149,6 +144,10 @@ namespace lwsf { namespace internal { namespace rpc address_meta() noexcept : maj_i(0), min_i(0) {} + + address_meta(const std::uint32_t maj, std::uint32_t min) noexcept + : maj_i(maj), min_i(min) + {} }; WIRE_DECLARE_OBJECT(address_meta); @@ -173,7 +172,7 @@ namespace lwsf { namespace internal { namespace rpc struct transaction { std::vector spent_outputs; - std::variant payment_id; + std::variant payment_id; std::optional timestamp; std::optional fee; uint64_string total_received; @@ -211,6 +210,27 @@ namespace lwsf { namespace internal { namespace rpc void read_bytes(wire::json_reader&, get_address_txs&); + struct subaddrs + { + subaddrs() + : key(0), value() + {} + + std::uint32_t key; + std::vector> value; + }; + void read_bytes(wire::json_reader&, subaddrs&); + + struct get_subaddrs + { + get_subaddrs() = delete; + static constexpr const char* endpoint() noexcept { return "/get_subaddrs"; } + + std::vector all_subaddrs; + }; + void read_bytes(wire::json_reader&, get_subaddrs&); + + struct ringct { ringct() = delete; @@ -273,6 +293,29 @@ namespace lwsf { namespace internal { namespace rpc }; void read_bytes(wire::json_reader&, import_response&); + + struct provision_subaddrs_request + { + provision_subaddrs_request() = delete; + login creds; + std::uint32_t maj_i; + std::uint32_t min_i; + std::uint32_t n_maj; + std::uint32_t n_min; + bool get_all; + }; + void write_bytes(wire::json_writer&, const provision_subaddrs_request&); + + struct provision_subaddrs_response + { + provision_subaddrs_response() = delete; + static constexpr const char* endpoint() noexcept { return "/provision_subaddrs"; } + + std::vector new_subaddrs; + std::vector all_subaddrs; + }; + void read_bytes(wire::json_reader&, provision_subaddrs_response&); + struct submit_raw_tx_request { diff --git a/src/subaddress_account.h b/src/subaddress_account.h new file mode 100644 index 0000000..237ff31 --- /dev/null +++ b/src/subaddress_account.h @@ -0,0 +1,61 @@ +// Copyright (c) 2025, The Monero Project +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include +#include +#include +#include "wallet/api/wallet2_api.h" // monero/src + +namespace lwsf { namespace internal +{ + namespace backend { struct wallet; } + + class subaddress_account final : public ::Monero::SubaddressAccount + { + const std::shared_ptr data_; + std::vector rows_; + + public: + + explicit subaddress_account(std::shared_ptr data); + + subaddress_account(const subaddress_account&) = delete; + subaddress_account(subaddress_account&&) = delete; + virtual ~subaddress_account() override; + subaddress_account& operator=(const subaddress_account&) = delete; + subaddress_account& operator=(subaddress_account&&) = delete; + + virtual std::vector getAll() const override { return rows_; } + virtual void addRow(const std::string &label) override; + virtual void setLabel(uint32_t accountIndex, const std::string &label) override; + virtual void refresh() override; + }; + +}} // lwsf // internal diff --git a/src/transaction_history.cpp b/src/transaction_history.cpp index a961837..a39c3e4 100644 --- a/src/transaction_history.cpp +++ b/src/transaction_history.cpp @@ -30,79 +30,117 @@ #include #include +#include #include +#include "backend.h" #include "transaction_info.h" #include "hex.h" // monero/contrib/epee/include namespace lwsf { namespace internal { + namespace + { + void free_txes(std::vector& txes) noexcept + { + for (auto tx : txes) + delete tx; + txes.clear(); + } + } + transaction_history::transaction_history(std::shared_ptr data) - : data_(std::move(data)) + : data_(std::move(data)), txes_(), by_id_() { if (!data_) - throw std::logic_error{"transaction_history was given nullptr"}; + throw std::invalid_argument{"lwsf::internal::transaction_history cannot be given nullptr"}; } transaction_history::~transaction_history() - {} - - int transaction_history::count() const { - const boost::lock_guard lock{data_->sync}; - if (std::numeric_limits::max() < data_->primary.txes.size()) - throw std::runtime_error{"Exceeded max int size in transaction_history::count"}; - return data_->primary.txes.size(); + free_txes(txes_); } - std::shared_ptr transaction_history::transaction(int index) const + Monero::TransactionInfo* transaction_history::transaction(int index) const { - const boost::lock_guard lock{data_->sync}; - if (index < 0 || data_->primary.txes.size() < unsigned(index)) - throw std::runtime_error{"index provided to transaction invalid"}; - return std::make_shared(data_, data_->primary.txes.nth(unsigned(index))->second); + if (index < 0 || txes_.size() <= unsigned(index)) + return nullptr; + return txes_[index]; } - std::shared_ptr transaction_history::transaction(const std::string &id) const + Monero::TransactionInfo* transaction_history::transaction(const std::string &id) const { crypto::hash binary_id{}; - if (!epee::from_hex::to_buffer(epee::as_mut_byte_span(binary_id), id)) - throw std::runtime_error{"transaction_history given invalid hex id"}; + if (!epee::string_tools::hex_to_pod(id, binary_id)) + return nullptr; - const boost::lock_guard lock{data_->sync}; - const auto iter = data_->primary.txes.find(binary_id); - if (iter != data_->primary.txes.end()) - return std::make_shared(data_, iter->second); - return nullptr; - } - - std::vector> transaction_history::getAll() const - { - std::vector> out; + // hold the lock during the map lookup, this is const and should be thread-safe const boost::lock_guard lock{data_->sync}; - out.reserve(data_->primary.txes.size()); - for (const auto& tx : data_->primary.txes) - out.push_back(std::make_shared(data_, tx.second)); - return out; + auto& info = by_id_[binary_id]; + if (!info) + { + const auto iter = data_->primary.txes.find(binary_id); + if (iter == data_->primary.txes.end()) + return nullptr; + info = std::make_unique(data_, iter->second); + } + return info.get(); } void transaction_history::refresh() { - data_->refresh(true); + data_->refresh(false); + + std::multimap> temp; + { + const boost::lock_guard lock{data_->sync}; + if (std::numeric_limits::max() < data_->primary.txes.size()) + throw std::runtime_error{"lwsf::internal::transaction_history::refresh exceeds max history size"}; + + for (const auto& tx : data_->primary.txes) + temp.emplace(tx.second->height.value_or(std::numeric_limits::max()), tx.second); + } + + // be careful about exceptions and memory leaks. this should be safe + + for (std::size_t i = temp.size(); i < txes_.size(); ++i) + { + const std::unique_ptr destroy{txes_[i]}; + txes_[i] = nullptr; + } + + by_id_.clear(); + txes_.resize(temp.size()); + + try + { + std::size_t i = 0; + for (auto& backend_tx : temp) + { + if (txes_[i]) + static_cast(txes_[i])->update(std::move(backend_tx.second)); + else + txes_[i] = new transaction_info{data_, std::move(backend_tx.second)}; + ++i; + } + } + catch (...) + { + free_txes(txes_); + throw; + } } void transaction_history::setTxNote(const std::string &txid, const std::string ¬e) { crypto::hash binary_id{}; if (!epee::string_tools::hex_to_pod(txid, binary_id)) - throw std::runtime_error{"transaction_history given invalid hex id"}; + return; const boost::lock_guard lock{data_->sync}; auto iter = data_->primary.txes.find(binary_id); - if (iter == data_->primary.txes.end()) - throw std::runtime_error{"transaction_history setTxNote given invalid id"}; - - iter->second->description = note; + if (iter != data_->primary.txes.end()) + iter->second->description = note; } }} // lwsf // internal diff --git a/src/transaction_history.h b/src/transaction_history.h index ed535c9..61ea6be 100644 --- a/src/transaction_history.h +++ b/src/transaction_history.h @@ -29,14 +29,19 @@ #pragma once #include -#include "backend.h" -#include "lws_frontend.h" +#include +#include +#include "crypto/hash.h" // monero/src +#include "wallet/api/wallet2_api.h" // monero/src namespace lwsf { namespace internal { - class transaction_history : public lwsf::TransactionHistory + namespace backend { class wallet; } + class transaction_history : public Monero::TransactionHistory { const std::shared_ptr data_; + std::vector txes_; + mutable std::unordered_map> by_id_; public: explicit transaction_history(std::shared_ptr data); @@ -47,10 +52,10 @@ namespace lwsf { namespace internal transaction_history& operator=(const transaction_history&) = delete; transaction_history& operator=(transaction_history&&) = delete; - virtual int count() const override; - virtual std::shared_ptr transaction(int index) const override; - virtual std::shared_ptr transaction(const std::string &id) const override; - virtual std::vector> getAll() const override; + virtual int count() const override { return txes_.size(); } + virtual Monero::TransactionInfo* transaction(int index) const override; + virtual Monero::TransactionInfo* transaction(const std::string &id) const override; + virtual std::vector getAll() const override { return txes_; } virtual void refresh() override; virtual void setTxNote(const std::string &txid, const std::string ¬e) override; }; diff --git a/src/transaction_info.cpp b/src/transaction_info.cpp index 48c6586..92d2343 100644 --- a/src/transaction_info.cpp +++ b/src/transaction_info.cpp @@ -40,32 +40,99 @@ namespace return epee::to_hex::string(epee::as_byte_span(source)); } - std::string operator()(const std::nullptr_t) const { return {}; } + std::string operator()(const lwsf::internal::rpc::empty&) const { return {}; } }; } namespace lwsf { namespace internal { - transaction_info::transaction_info(std::shared_ptr wallet, std::shared_ptr data) - : wallet_(std::move(wallet)), data_(std::move(data)), transfers_() + void transaction_info::update_transfers() { - if (!wallet_ || !data_) - throw std::logic_error{"internal::transaction_info cannot be given nullptr"}; - + transfers_.clear(); transfers_.reserve(data_->spends.size()); for (const auto& spend : data_->spends) transfers_.emplace_back(spend.second.amount, spend.second.address); } + transaction_info::transaction_info(std::shared_ptr wallet, std::shared_ptr data) + : wallet_(std::move(wallet)), data_(std::move(data)), transfers_() + { + if (!wallet_ || !data_) + throw std::invalid_argument{"lwsf::internal::transaction_info cannot be given nullptr"}; + update_transfers(); + } + transaction_info::~transaction_info() {} + void transaction_info::update(std::shared_ptr data) + { + if (!data) + throw std::invalid_argument{"lwsf::internal::transaction_info::update cannot be given nullptr"}; + data_ = std::move(data); + update_transfers(); + } + std::string transaction_info::description() const { const boost::lock_guard lock{wallet_->sync}; return data_->description; } + std::set transaction_info::subaddrIndex() const + { + std::set out; + const std::uint32_t major = subaddrAccount(); + + for (const auto& receive : data_->receives) + out.insert(receive.second.recipient.min_i); + + for (const auto& spend : data_->spends) + out.insert(spend.second.sender.min_i); + + return out; + } + + std::uint32_t transaction_info::subaddrAccount() const + { + if (data_->direction == Direction_In) + { + if (!data_->receives.empty()) + return data_->receives.begin()->second.recipient.maj_i; + } + else if (!data_->spends.empty()) + return data_->spends.begin()->second.sender.maj_i; + return 0; + } + + std::string transaction_info::label() const + { + try // We could be out-of-sync with another wallet adding subaddresses + { + if (data_->direction == Direction_In) + { + if (!data_->receives.empty()) + { + const auto& receive = data_->receives.begin()->second; + const boost::lock_guard lock{wallet_->sync}; + return wallet_->primary.subaccounts.at(receive.recipient.maj_i).minor.at(receive.recipient.min_i).label; + } + } + else if (!data_->spends.empty()) + { + const auto& spend = data_->spends.begin()->second; + const boost::lock_guard lock{wallet_->sync}; + return wallet_->primary.subaccounts.at(spend.sender.maj_i).minor.at(spend.sender.min_i).label; + } + } + catch (const boost::container::out_of_range&) + {} + catch (const std::out_of_range&) + {} + + return {}; + } + uint64_t transaction_info::confirmations() const { if (!data_->height) diff --git a/src/transaction_info.h b/src/transaction_info.h index f63dee2..1839ca2 100644 --- a/src/transaction_info.h +++ b/src/transaction_info.h @@ -35,18 +35,22 @@ #include #include "backend.h" +#include "wallet/api/wallet2_api.h" // monero/src namespace lwsf { namespace internal { //! \todo isFailed, subaddressIndex, and subaddrAccount - class transaction_info final : public lwsf::TransactionInfo + class transaction_info final : public Monero::TransactionInfo { const std::shared_ptr wallet_; - const std::shared_ptr data_; + std::shared_ptr data_; std::vector transfers_; + void update_transfers(); + public: - explicit transaction_info(std::shared_ptr wallet, std::shared_ptr data); + + explicit transaction_info(std::shared_ptr wallet, std::shared_ptr data); transaction_info(const transaction_info&) = delete; transaction_info(transaction_info&&) = delete; @@ -54,21 +58,23 @@ namespace lwsf { namespace internal transaction_info& operator=(const transaction_info&) = delete; transaction_info& operator=(transaction_info&&) = delete; - virtual Direction direction() const override { return data_->direction; } + void update(std::shared_ptr data); + + virtual int direction() const override { return data_->direction; } virtual bool isPending() const override { return !data_->height; } virtual bool isFailed() const override { return false; } virtual bool isCoinbase() const override { return data_->coinbase; } - virtual uint64_t amount() const override { return data_->amount; } - virtual uint64_t fee() const override { return data_->fee; } - virtual uint64_t blockHeight() const override { return data_->height.value_or(0); } + virtual std::uint64_t amount() const override { return data_->amount; } + virtual std::uint64_t fee() const override { return data_->fee; } + virtual std::uint64_t blockHeight() const override { return data_->height.value_or(std::numeric_limits::max()); } virtual std::string description() const override; - virtual std::set subaddrIndex() const override { return {}; }; - virtual uint32_t subaddrAccount() const override { return 0; } - virtual std::string label() const override { return data_->label; } - virtual uint64_t confirmations() const override; - virtual uint64_t unlockTime() const override { return data_->unlock_time; } + virtual std::set subaddrIndex() const override; + virtual std::uint32_t subaddrAccount() const override; + virtual std::string label() const override; + virtual std::uint64_t confirmations() const override; + virtual std::uint64_t unlockTime() const override { return data_->unlock_time; } virtual std::string hash() const override; - virtual std::time_t timestamp() const override { return data_->timestamp.value_or(std::time_t(0)); } + virtual std::time_t timestamp() const override { return data_->timestamp.value_or(std::numeric_limits::max()); } virtual std::string paymentId() const override; virtual const std::vector& transfers() const override { return transfers_; } }; diff --git a/src/wallet.cpp b/src/wallet.cpp index 6428169..87e34e4 100644 --- a/src/wallet.cpp +++ b/src/wallet.cpp @@ -40,6 +40,7 @@ #include #include #include +#include "address_book.h" #include "backend.h" #include "error.h" #include "hex.h" // monero/contrib/epee/include @@ -48,6 +49,7 @@ #include "net/parse.h" // monero/src #include "net/socks.h" // monero/src #include "net/socks_connect.h" // monero/src +#include "subaddress_account.h" #include "transaction_history.h" #include "wire.h" #include "wire/msgpack.h" @@ -303,7 +305,7 @@ namespace lwsf { namespace internal } } // anonymous - bool wallet::set_error(const std::error_code status) + bool wallet::set_error(const std::error_code status) const { const boost::lock_guard lock{error_sync_}; status_ = status; @@ -311,7 +313,7 @@ namespace lwsf { namespace internal return !status_; } - void wallet::set_critical(const std::exception& e) + void wallet::set_critical(const std::exception& e) const { const boost::lock_guard lock{error_sync_}; exception_error_ = e.what(); @@ -366,7 +368,7 @@ namespace lwsf { namespace internal } } - wallet::wallet(create_tag, NetworkType nettype, std::string filename, std::string password, const std::uint64_t kdf_rounds) + wallet::wallet(create_tag, Monero::NetworkType nettype, std::string filename, std::string password, const std::uint64_t kdf_rounds) : data_(std::make_shared()), filename_(std::move(filename)), password_(std::move(password)), @@ -374,6 +376,8 @@ namespace lwsf { namespace internal status_(), thread_(), iterations_(kdf_rounds), + mixin_(config::mixin_default), + refresh_interval_(config::refresh_interval), refresh_notify_(), error_sync_(), refresh_sync_(), @@ -405,7 +409,7 @@ namespace lwsf { namespace internal store(std::string{}); } - wallet::wallet(open_tag, NetworkType nettype, std::string filename, std::string password, const std::uint64_t kdf_rounds, std::shared_ptr data) + wallet::wallet(open_tag, Monero::NetworkType nettype, std::string filename, std::string password, const std::uint64_t kdf_rounds, std::shared_ptr data) : data_(std::move(data)), filename_(std::move(filename)), password_(std::move(password)), @@ -413,6 +417,8 @@ namespace lwsf { namespace internal status_(), thread_(), iterations_(kdf_rounds), + mixin_(config::mixin_default), + refresh_interval_(config::refresh_interval), refresh_notify_(), error_sync_(), refresh_sync_(), @@ -420,7 +426,7 @@ namespace lwsf { namespace internal mandatory_refresh_(false) { if (!data_) - throw std::logic_error{"backend::wallet cannot be null"}; + throw std::invalid_argument{"lwsf::backend::wallet cannot be null"}; try { @@ -501,7 +507,7 @@ namespace lwsf { namespace internal return true; } - NetworkType wallet::nettype() const { return data_->primary.type; } + Monero::NetworkType wallet::nettype() const { return data_->primary.type; } std::string wallet::secretViewKey() const { @@ -583,7 +589,7 @@ namespace lwsf { namespace internal bool wallet::init(const std::string &daemon_address, uint64_t, const std::string &daemon_username, const std::string &daemon_password, bool use_ssl, bool light_wallet, const std::string &proxy_address) { if (!light_wallet) - throw std::logic_error{"Only light_wallets are supported with this instance"}; + throw std::invalid_argument{"Only light_wallets are supported with this instance"}; // on exceptions, reset state struct on_throw @@ -638,7 +644,7 @@ namespace lwsf { namespace internal return true; } - void wallet::setRefreshFromBlockHeight(uint64_t refresh_from_block_height) override + void wallet::setRefreshFromBlockHeight(uint64_t refresh_from_block_height) { try { set_error(data_->restore_height(refresh_from_block_height)); } catch (const std::exception& e) @@ -672,14 +678,14 @@ namespace lwsf { namespace internal { const std::error_code status = data_->login(); if (!status) - disconnect.reset(); + disconnect.release(); return set_error(status); } set_error(error::connect_failure); return false; } - Wallet::ConnectionStatus wallet::connected() const + Monero::Wallet::ConnectionStatus wallet::connected() const { return data_->client.is_connected() ? ConnectionStatus_Connected : ConnectionStatus_Disconnected; @@ -738,20 +744,185 @@ namespace lwsf { namespace internal refresh_notify_.notify_all(); } + void wallet::setAutoRefreshInterval(int millis) + { + using rep_type = std::chrono::milliseconds::rep; + static_assert(std::numeric_limits::max() <= std::numeric_limits::max()); + if (0 < millis) + { + const boost::lock_guard lock{refresh_sync_}; + refresh_interval_ = std::chrono::milliseconds{millis}; + if (thread_state_ == state::stop) + { + thread_state_ = state::run; + thread_ = boost::thread{[this] () { this->refresh_loop(); }}; + } + } + else + return stop_refresh_loop(); + } + + int wallet::autoRefreshInterval() const + { + return refresh_interval_.count(); + } + uint64_t wallet::estimateTransactionFee(const std::vector> &destinations, - PendingTransaction::Priority priority) const + Monero::PendingTransaction::Priority priority) const { throw std::runtime_error{"Not Implemented yet"}; } - - std::shared_ptr wallet::history() + + bool wallet::exportKeyImages(const std::string &filename, bool all) { - return std::make_shared(data_); + throw std::runtime_error{"exportKeyImages not implemented"}; + } + + bool wallet::importKeyImages(const std::string &filename) + { + throw std::runtime_error{"importKeyImages not implemented"}; } - void wallet::setListener(std::shared_ptr listener) + bool wallet::exportOutputs(const std::string &filename, bool all) + { + throw std::runtime_error{"exportOutputs not implemented"}; + } + + bool wallet::importOutputs(const std::string &filename) + { + throw std::runtime_error{"importOutputs not implemented"}; + } + + bool wallet::scanTransactions(const std::vector &txids) + { + throw std::runtime_error{"scanTransactions not implemented"}; + } + + Monero::AddressBook* wallet::addressBook() + { + if (!addressbook_) + addressbook_ = std::make_unique(data_); + return addressbook_.get(); + } + + Monero::TransactionHistory* wallet::history() + { + if (!history_) + history_ = std::make_unique(data_); + return history_.get(); + } + + Monero::SubaddressAccount* wallet::subaddressAccount() + { + if (!subaddresses_) + subaddresses_ = std::make_unique(data_); + return subaddresses_.get(); + } + + void wallet::setListener(Monero::WalletListener* listener) + { + { + const boost::lock_guard lock{data_->sync_listener}; + data_->listener = listener; + } + listener->onSetWallet(this); + } + + std::uint32_t wallet::defaultMixin() const + { + return mixin_; + } + + void wallet::setDefaultMixin(const std::uint32_t arg) + { + mixin_ = arg; + } + + bool wallet::setCacheAttribute(const std::string &key, const std::string &val) { const boost::lock_guard lock{data_->sync}; - data_->listener = std::move(listener); + data_->primary.attributes.try_emplace(key).first->second = val; + } + + std::string wallet::getCacheAttribute(const std::string &key) const + { + const boost::lock_guard lock{data_->sync}; + const auto iter = data_->primary.attributes.find(key); + if (iter == data_->primary.attributes.end()) + return {}; + return iter->second; + } + + bool wallet::setUserNote(const std::string &txid, const std::string ¬e) + { + crypto::hash binary_id{}; + if (!epee::string_tools::hex_to_pod(txid, binary_id)) + return false; + + const boost::lock_guard lock{data_->sync}; + auto iter = data_->primary.txes.find(binary_id); + if (iter == data_->primary.txes.end()) + return false; + + iter->second->description = note; + return true; + } + + std::string wallet::getUserNote(const std::string &txid) const + { + crypto::hash binary_id{}; + if (!epee::string_tools::hex_to_pod(txid, binary_id)) + { + set_critical(std::runtime_error{"getUserNote given invalid hex id"}); + return {}; + } + + const boost::lock_guard lock{data_->sync}; + auto iter = data_->primary.txes.find(binary_id); + if (iter == data_->primary.txes.end()) + return {}; + return iter->second->description; + } + + std::string wallet::getTxKey(const std::string &txid) const + { + crypto::hash binary_id{}; + if (!epee::string_tools::hex_to_pod(txid, binary_id)) + { + set_critical(std::runtime_error{"getTxKey given invalid hex id"}); + return {}; + } + + const boost::lock_guard lock{data_->sync}; + auto iter = data_->primary.txes.find(binary_id); + if (iter == data_->primary.txes.end()) + { + set_critical(std::runtime_error{"getTxKey tx not found"}); + return {}; + } + + static constexpr const auto hex_size = sizeof(crypto::secret_key) * 2; + + std::string out; + out.reserve(iter->second->spends.size() * hex_size); + + for (const auto& spend : iter->second->spends) + { + if (spend.second.secret) + { + out.insert(out.end(), hex_size, 0); + if (!epee::to_hex::buffer({out.data() + out.size() - hex_size, hex_size}, epee::as_byte_span(unwrap(unwrap(*spend.second.secret))))) + { + set_critical(std::runtime_error{"getTxKey conversion to hex failure"}); + return {}; + } + } + } + + return out; + } + + bool wallet::checkTxKey(const std::string &txid, std::string tx_key, const std::string &address, uint64_t &received, bool &in_pool, uint64_t &confirmations) + { } }} // lwsf // internal diff --git a/src/wallet.h b/src/wallet.h index 70e2214..8957aef 100644 --- a/src/wallet.h +++ b/src/wallet.h @@ -38,6 +38,7 @@ #include #include "cryptonote_basic/account.h" // monero/src #include "net/http_client.h" // monero/contrib/epee/include +#include "wallet/api/wallet2_api.h" // monero/src namespace lwsf { @@ -47,25 +48,30 @@ namespace internal //! \TODO Mark final when completely implemented - class wallet : public lwsf::Wallet + class wallet : public Monero::Wallet { enum class state : std::uint8_t { stop = 0, paused, skip_once, run }; const std::shared_ptr data_; + std::unique_ptr addressbook_; + std::unique_ptr history_; + std::unique_ptr subaddresses_; const std::string filename_; std::string password_; - std::string exception_error_; - std::error_code status_; + mutable std::string exception_error_; + mutable std::error_code status_; boost::thread thread_; const std::uint64_t iterations_; + std::chrono::milliseconds refresh_interval_; + std::uint32_t mixin_; boost::condition_variable refresh_notify_; mutable boost::mutex error_sync_; boost::mutex refresh_sync_; state thread_state_; bool mandatory_refresh_; - bool set_error(std::error_code status); - void set_critical(const std::exception& e); + bool set_error(std::error_code status) const; + void set_critical(const std::exception& e) const; void stop_refresh_loop(); void refresh_loop(); @@ -74,8 +80,8 @@ namespace internal struct create_tag{}; struct open_tag{}; - wallet(create_tag, NetworkType nettype, std::string filename, std::string password, std::uint64_t kdf_rounds); - wallet(open_tag, NetworkType nettpe, std::string filename, std::string password, std::uint64_t kdf_rounds, std::shared_ptr data); + wallet(create_tag, Monero::NetworkType nettype, std::string filename, std::string password, std::uint64_t kdf_rounds); + wallet(open_tag, Monero::NetworkType nettpe, std::string filename, std::string password, std::uint64_t kdf_rounds, std::shared_ptr data); wallet(const wallet&) = delete; wallet(wallet&&) = delete; @@ -98,12 +104,8 @@ namespace internal virtual bool setDevicePin(const std::string &) override { return false; }; virtual bool setDevicePassphrase(const std::string &) override { return false; }; virtual std::string address(uint32_t accountIndex = 0, uint32_t addressIndex = 0) const override; - std::string mainAddress() const { return address(0, 0); } virtual std::string path() const = 0; - virtual NetworkType nettype() const override; - bool mainnet() const { return nettype() == MAINNET; } - bool testnet() const { return nettype() == TESTNET; } - bool stagenet() const { return nettype() == STAGENET; } + virtual Monero::NetworkType nettype() const override; //! returns current hard fork info virtual void hardForkInfo(uint8_t &version, uint64_t &earliest_height) const = 0; //! check if hard fork rules should be used @@ -313,20 +315,20 @@ namespace internal static uint64_t amountFromDouble(double amount); static std::string genPaymentId(); static bool paymentIdValid(const std::string &paiment_id); - static bool addressValid(const std::string &str, NetworkType nettype); + static bool addressValid(const std::string &str, Monero::NetworkType nettype); static bool addressValid(const std::string &str, bool testnet) // deprecated { - return addressValid(str, testnet ? TESTNET : MAINNET); + return addressValid(str, testnet ? Monero::TESTNET : Monero::MAINNET); } - static bool keyValid(const std::string &secret_key_string, const std::string &address_string, bool isViewKey, NetworkType nettype, std::string &error); + static bool keyValid(const std::string &secret_key_string, const std::string &address_string, bool isViewKey, Monero::NetworkType nettype, std::string &error); static bool keyValid(const std::string &secret_key_string, const std::string &address_string, bool isViewKey, bool testnet, std::string &error) // deprecated { - return keyValid(secret_key_string, address_string, isViewKey, testnet ? TESTNET : MAINNET, error); + return keyValid(secret_key_string, address_string, isViewKey, testnet ? Monero::TESTNET : Monero::MAINNET, error); } - static std::string paymentIdFromAddress(const std::string &str, NetworkType nettype); + static std::string paymentIdFromAddress(const std::string &str, Monero::NetworkType nettype); static std::string paymentIdFromAddress(const std::string &str, bool testnet) // deprecated { - return paymentIdFromAddress(str, testnet ? TESTNET : MAINNET); + return paymentIdFromAddress(str, testnet ? Monero::TESTNET : Monero::MAINNET); } static uint64_t maximumAllowedAmount(); // Easylogger wrapper @@ -372,13 +374,13 @@ namespace internal * @brief setAutoRefreshInterval - setup interval for automatic refresh. * @param seconds - interval in millis. if zero or less than zero - automatic refresh disabled; */ - virtual void setAutoRefreshInterval(int millis) = 0; + virtual void setAutoRefreshInterval(int millis) override; /** * @brief autoRefreshInterval - returns automatic refresh interval in millis * @return */ - virtual int autoRefreshInterval() const = 0; + virtual int autoRefreshInterval() const override; /** * @brief addSubaddressAccount - appends a new subaddress account at the end of the last major index of existing subaddress accounts @@ -418,7 +420,7 @@ namespace internal * @brief multisig - returns current state of multisig wallet creation process * @return MultisigState struct */ - virtual MultisigState multisig() const = 0; + virtual Monero::MultisigState multisig() const = 0; /** * @brief getMultisigInfo * @return serialized and signed multisig info string @@ -461,7 +463,7 @@ namespace internal * @param signData encrypted unsigned transaction. Obtained with PendingTransaction::multisigSignData * @return PendingTransaction */ - virtual std::unique_ptr restoreMultisigTransaction(const std::string& signData) = 0; + virtual Monero::PendingTransaction* restoreMultisigTransaction(const std::string& signData) = 0; /*! * \brief createTransactionMultDest creates transaction with multiple destinations. if dst_addr is an integrated address, payment_id is ignored @@ -476,9 +478,9 @@ namespace internal * after object returned */ - virtual std::unique_ptr createTransactionMultDest(const std::vector &dst_addr, const std::string &payment_id, - optional> amount, uint32_t mixin_count, - PendingTransaction::Priority = PendingTransaction::Priority::Low, + virtual Monero::PendingTransaction* createTransactionMultDest(const std::vector &dst_addr, const std::string &payment_id, + Monero::optional> amount, uint32_t mixin_count, + Monero::PendingTransaction::Priority = Monero::PendingTransaction::Priority_Low, uint32_t subaddr_account = 0, std::set subaddr_indices = {}) = 0; @@ -495,9 +497,9 @@ namespace internal * after object returned */ - virtual std::unique_ptr createTransaction(const std::string &dst_addr, const std::string &payment_id, + virtual Monero::PendingTransaction* createTransaction(const std::string &dst_addr, const std::string &payment_id, std::optional amount, uint32_t mixin_count, - PendingTransaction::Priority = PendingTransaction::Priority::Low, + Monero::PendingTransaction::Priority = Monero::PendingTransaction::Priority_Low, uint32_t subaddr_account = 0, std::set subaddr_indices = {}) = 0; @@ -507,14 +509,14 @@ namespace internal * after object returned */ - virtual std::unique_ptr createSweepUnmixableTransaction() = 0; + virtual Monero::PendingTransaction* createSweepUnmixableTransaction() = 0; /*! * \brief loadUnsignedTx - creates transaction from unsigned tx file * \return - UnsignedTransaction object. caller is responsible to check UnsignedTransaction::status() * after object returned */ - virtual std::unique_ptr loadUnsignedTx(const std::string &unsigned_filename) = 0; + virtual Monero::UnsignedTransaction* loadUnsignedTx(const std::string &unsigned_filename) = 0; /*! * \brief submitTransaction - submits transaction in signed tx file @@ -527,7 +529,7 @@ namespace internal * \brief disposeTransaction - destroys transaction object * \param t - pointer to the "PendingTransaction" object. Pointer is not valid after function returned; */ - virtual void disposeTransaction(PendingTransaction * t) override final + virtual void disposeTransaction(Monero::PendingTransaction * t) override final {} /*! @@ -536,7 +538,7 @@ namespace internal * \return Estimated fee. */ virtual uint64_t estimateTransactionFee(const std::vector> &destinations, - PendingTransaction::Priority priority) const override final; + Monero::PendingTransaction::Priority priority) const override final; /*! * \brief exportKeyImages - exports key images to file @@ -544,51 +546,51 @@ namespace internal * \param all - export all key images or only those that have not yet been exported * \return - true on success */ - virtual bool exportKeyImages(const std::string &filename, bool all = false) = 0; + virtual bool exportKeyImages(const std::string &filename, bool all = false) override; /*! * \brief importKeyImages - imports key images from file * \param filename * \return - true on success */ - virtual bool importKeyImages(const std::string &filename) = 0; + virtual bool importKeyImages(const std::string &filename) override; /*! * \brief importOutputs - exports outputs to file * \param filename * \return - true on success */ - virtual bool exportOutputs(const std::string &filename, bool all = false) = 0; + virtual bool exportOutputs(const std::string &filename, bool all = false) override; /*! * \brief importOutputs - imports outputs from file * \param filename * \return - true on success */ - virtual bool importOutputs(const std::string &filename) = 0; + virtual bool importOutputs(const std::string &filename) override; /*! * \brief scanTransactions - scan a list of transaction ids, this operation may reveal the txids to the remote node and affect your privacy * \param txids - list of transaction ids * \return - true on success */ - virtual bool scanTransactions(const std::vector &txids) = 0; + virtual bool scanTransactions(const std::vector &txids) override; - virtual std::shared_ptr history() override; - virtual std::shared_ptr addressBook() = 0; - virtual std::shared_ptr subaddress() = 0; - virtual std::shared_ptr subaddressAccount() = 0; - virtual void setListener(std::shared_ptr) override; + virtual Monero::TransactionHistory* history() override; + virtual Monero::AddressBook* addressBook() override; + virtual Monero::Subaddress* subaddress() = 0; + virtual Monero::SubaddressAccount* subaddressAccount() override; + virtual void setListener(Monero::WalletListener*) override; /*! * \brief defaultMixin - returns number of mixins used in transactions * \return */ - virtual uint32_t defaultMixin() const = 0; + virtual uint32_t defaultMixin() const override; /*! * \brief setDefaultMixin - setum number of mixins to be used for new transactions * \param arg */ - virtual void setDefaultMixin(uint32_t arg) = 0; + virtual void setDefaultMixin(uint32_t arg) override; /*! * \brief setCacheAttribute - attach an arbitrary string to a wallet cache attribute @@ -596,7 +598,7 @@ namespace internal * \param val - the value * \return true if successful, false otherwise */ - virtual bool setCacheAttribute(const std::string &key, const std::string &val) = 0; + virtual bool setCacheAttribute(const std::string &key, const std::string &val) override; /*! * \brief getCacheAttribute - return an arbitrary string attached to a wallet cache attribute * \param key - the key @@ -609,14 +611,14 @@ namespace internal * \param note - the note * \return true if successful, false otherwise */ - virtual bool setUserNote(const std::string &txid, const std::string ¬e) = 0; + virtual bool setUserNote(const std::string &txid, const std::string ¬e) override; /*! * \brief getUserNote - return an arbitrary string note attached to a txid * \param txid - the transaction id to attach the note to * \return the attached note, or empty string if there is none */ - virtual std::string getUserNote(const std::string &txid) const = 0; - virtual std::string getTxKey(const std::string &txid) const = 0; + virtual std::string getUserNote(const std::string &txid) const override; + virtual std::string getTxKey(const std::string &txid) const override; virtual bool checkTxKey(const std::string &txid, std::string tx_key, const std::string &address, uint64_t &received, bool &in_pool, uint64_t &confirmations) = 0; virtual std::string getTxProof(const std::string &txid, const std::string &address, const std::string &message) const = 0; virtual bool checkTxProof(const std::string &txid, const std::string &address, const std::string &message, const std::string &signature, bool &good, uint64_t &received, bool &in_pool, uint64_t &confirmations) = 0; diff --git a/src/wallet_manager.cpp b/src/wallet_manager.cpp index 503628d..ec05518 100644 --- a/src/wallet_manager.cpp +++ b/src/wallet_manager.cpp @@ -37,18 +37,20 @@ #include "backend.h" #include "common/dns_utils.h" // monero/src #include "lwsf_config.h" +#include "lws_frontend.h" #include "net/http_client.h" // monero/contrib/epee/include #include "net/parse.h" // monero/src #include "net/socks_connect.h" // monero/src #include "rpc.h" #include "wallet.h" +#include "wallet/api/wallet2_api.h" // monero/src namespace lwsf { namespace internal { //! \TODO Mark final when completely implemented - class wallet_manager : public lwsf::WalletManager + class wallet_manager : public Monero::WalletManager { rpc::http_client client_; std::string error_; @@ -80,7 +82,7 @@ namespace lwsf : client_(), error_(), cached_{}, cached_last_(std::chrono::seconds{0}) {} - virtual ~wallet_manager() override + virtual ~wallet_manager() /* override */ {} /*! @@ -92,11 +94,11 @@ namespace lwsf * \param kdf_rounds Number of rounds for key derivation function * \return Wallet instance (Wallet::status() needs to be called to check if created successfully) */ - std::unique_ptr createWallet(const std::string &path, const std::string &password, const std::string &language, NetworkType nettype, uint64_t kdf_rounds) override + Monero::Wallet* createWallet(const std::string &path, const std::string &password, const std::string &language, Monero::NetworkType nettype, uint64_t kdf_rounds) override { - return std::make_unique( - wallet::create_tag{}, nettype, path, password, kdf_rounds, std::make_shared() - ); + return new wallet{ + wallet::create_tag{}, nettype, path, password, kdf_rounds + }; } /*! @@ -109,18 +111,18 @@ namespace lwsf * \return Wallet instance (Wallet::status() needs to be called to check if opened successfully) */ - std::shared_ptr openWallet(const std::string &path, const std::string &password, NetworkType nettype, uint64_t kdf_rounds, std::shared_ptr listener) override + Monero::Wallet* openWallet(const std::string &path, const std::string &password, Monero::NetworkType nettype, uint64_t kdf_rounds, Monero::WalletListener* listener) override { auto data = std::make_shared(); data->listener = std::move(listener); - auto out = std::make_shared( + auto out = std::make_unique( wallet::open_tag{}, nettype, path, password, kdf_rounds, data ); // wallet file should be fully loaded in construction of `wallet`. if (data->listener) - data->listener->onSetWallet(out); - return out; + data->listener->onSetWallet(out.get()); + return out.release(); } /*! @@ -134,8 +136,8 @@ namespace lwsf * \param seed_offset Seed offset passphrase (optional) * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) */ - std::unique_ptr recoveryWallet(const std::string &path, const std::string &password, const std::string &mnemonic, - NetworkType nettype = MAINNET, uint64_t restoreHeight = 0, uint64_t kdf_rounds = 1, + Monero::Wallet* recoveryWallet(const std::string &path, const std::string &password, const std::string &mnemonic, + Monero::NetworkType nettype = Monero::MAINNET, uint64_t restoreHeight = 0, uint64_t kdf_rounds = 1, const std::string &seed_offset = {}) override final { //! \TODO Complete @@ -150,7 +152,7 @@ namespace lwsf * \param restoreHeight restore from start height * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) */ - std::unique_ptr recoveryWallet(const std::string &path, const std::string &mnemonic, NetworkType nettype, uint64_t restoreHeight = 0) override + Monero::Wallet* recoveryWallet(const std::string &path, const std::string &mnemonic, Monero::NetworkType nettype, uint64_t restoreHeight = 0) override { } @@ -167,10 +169,10 @@ namespace lwsf * \param kdf_rounds Number of rounds for key derivation function * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) */ - std::unique_ptr createWalletFromKeys(const std::string &path, + Monero::Wallet* createWalletFromKeys(const std::string &path, const std::string &password, const std::string &language, - NetworkType nettype, + Monero::NetworkType nettype, uint64_t restoreHeight, const std::string &addressString, const std::string &viewKeyString, @@ -192,9 +194,9 @@ namespace lwsf * \param spendKeyString spend key (optional) * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) */ - std::unique_ptr createWalletFromKeys(const std::string &path, + Monero::Wallet* createWalletFromKeys(const std::string &path, const std::string &language, - NetworkType nettype, + Monero::NetworkType nettype, uint64_t restoreHeight, const std::string &addressString, const std::string &viewKeyString, @@ -215,14 +217,14 @@ namespace lwsf * \param listener Wallet listener to set to the wallet after creation * \return Wallet instance (Wallet::status() needs to be called to check if recovered successfully) */ - std::unique_ptr createWalletFromDevice(const std::string &path, + Monero::Wallet* createWalletFromDevice(const std::string &path, const std::string &password, - NetworkType nettype, + Monero::NetworkType nettype, const std::string &deviceName, uint64_t restoreHeight, const std::string &subaddressLookahead, uint64_t kdf_rounds, - WalletListener * listener) override + Monero::WalletListener * listener) override { //! \TODO Complete } @@ -232,8 +234,9 @@ namespace lwsf * \param wallet previously opened / created wallet instance * \return None */ - bool closeWallet(std::unique_ptr wallet, const bool store) override + bool closeWallet(Monero::Wallet* const wallet, const bool store) override { + const std::unique_ptr destroy{wallet}; if (wallet && store) wallet->store(wallet->filename()); } @@ -279,7 +282,7 @@ namespace lwsf * for verification only - determines key storage hardware * */ - bool queryWalletDevice(Wallet::Device& device_type, const std::string &keys_file_name, const std::string &password, uint64_t kdf_rounds) const override + bool queryWalletDevice(Monero::Wallet::Device& device_type, const std::string &keys_file_name, const std::string &password, uint64_t kdf_rounds) const override { //! \TODO Complete } @@ -375,9 +378,9 @@ namespace lwsf }; } // internal - std::unique_ptr WalletManagerFactory::getWalletManager() + Monero::WalletManager* WalletManagerFactory::getWalletManager() { - return std::make_unique(); + return new internal::wallet_manager{}; } void WalletManagerFactory::setLogLevel(int level) diff --git a/src/wire/basic_value.cpp b/src/wire/basic_value.cpp new file mode 100644 index 0000000..7c8c732 --- /dev/null +++ b/src/wire/basic_value.cpp @@ -0,0 +1,54 @@ +// Copyright (c) 2022, The Monero Project +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include "basic_value.h" + +#include +#include "wire/read.h" +#include "wire/write.h" + +namespace wire +{ + static void write_bytes(writer& dest, const std::nullptr_t&) + { + throw std::logic_error{"nullptr output not yet defined for wire::writer"}; + } + + void basic_value::reset() + { + value = nullptr; + } + + void read_bytes(reader& source, basic_value& dest) + { + dest = source.basic(); + } + void write_bytes(writer& dest, const basic_value& source) + { + boost::apply_visitor([&dest] (const auto& val) { wire_write::bytes(dest, val); }, source.value); + } +} diff --git a/src/wire/basic_value.h b/src/wire/basic_value.h new file mode 100644 index 0000000..d1e5bfd --- /dev/null +++ b/src/wire/basic_value.h @@ -0,0 +1,64 @@ +// Copyright (c) 2022, The Monero Project +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are +// permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this list of +// conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright notice, this list +// of conditions and the following disclaimer in the documentation and/or other +// materials provided with the distribution. +// +// 3. Neither the name of the copyright holder nor the names of its contributors may be +// used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF +// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#pragma once + +#include +#include +#include +#include + +#include "wire/fwd.h" + +namespace wire +{ + /*! Can hold any non-recursive value. Implements optional field concept + requirements. If used in a `optional_field`, the `nullptr` type/value + determines whether the field name is omitted or present in an object. If used + in a `field` (required), the field name is always present in the object, and + the value could be `null`/`nil`. */ + struct basic_value + { + using variant_type = + std::variant; + + variant_type value; + + // concept requirements for optional fields + + explicit operator bool() const noexcept { return value != variant_type{nullptr}; } + basic_value& emplace() noexcept { return *this; } + + basic_value& operator*() noexcept { return *this; } + const basic_value& operator*() const noexcept { return *this; } + + void reset(); + }; + + void read_bytes(reader& source, basic_value& dest); + void write_bytes(writer& dest, const basic_value& source); +} // wire diff --git a/src/wire/wrapper/variant.h b/src/wire/wrapper/variant.h index c61970d..7d3a2e0 100644 --- a/src/wire/wrapper/variant.h +++ b/src/wire/wrapper/variant.h @@ -31,6 +31,7 @@ #include #include #include +#include #include "wire/error.h" #include "wire/fwd.h" @@ -117,6 +118,10 @@ namespace wire inline const U* get_if(const boost::variant& value) { return boost::get(std::addressof(value)); } + template + inline const U* get_if(const std::variant& value) + { return std::get_if(std::addressof(value)); } + template inline const U* get_if(const variant_& value) { return adapt::get_if(value.get_variant()); } @@ -186,6 +191,14 @@ namespace wire inline const U& get(const boost::variant& value) { return boost::get(value); } + template + inline U& get(std::variant& value) + { return std::get(value); } + + template + inline const U& get(const std::variant& value) + { return std::get(value); } + template inline const U& get(const variant_& value) { return adapt::get(value.get_variant()); }