Several different changes (still WIP):

* Reverted back to standard `::Monero::` interface
  * Added some previsouly missing functions
  * Fixed several bugs
This commit is contained in:
Lee *!* Clagett
2025-03-30 17:37:10 -04:00
parent 1c3370cc6f
commit 8a0d23eabc
24 changed files with 1699 additions and 325 deletions
+118 -116
View File
@@ -38,10 +38,12 @@
#include <stdexcept>
#include <cstdint>
#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<uint32_t> subaddrAccount() const = 0;
virtual std::vector<std::set<uint32_t>> 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<std::string> 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<std::string> onDevicePinRequest() {
throw std::runtime_error("Not supported");
}
/**
* @brief called by device when passphrase entry is needed
*/
* /
virtual optional<std::string> 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> 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<std::string>& 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<std::string> &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<std::string>& 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<PendingTransaction> 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<PendingTransaction> createTransactionMultDest(const std::vector<std::string> &dst_addr, const std::string &payment_id,
optional<std::vector<uint64_t>> 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<PendingTransaction> createTransaction(const std::string &dst_addr, const std::string &payment_id,
optional<uint64_t> 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<PendingTransaction> 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<UnsignedTransaction> 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 <address, amount> pairs.
* \return Estimated fee.
*/
* /
virtual uint64_t estimateTransactionFee(const std::vector<std::pair<std::string, uint64_t>> &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<std::string> &txids) = 0;
virtual std::shared_ptr<TransactionHistory> 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 &note) = 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<std::string> &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<Wallet> createWallet(const std::string &path, const std::string &password, const std::string &language, NetworkType nettype, uint64_t kdf_rounds = 1) = 0;
std::unique_ptr<Wallet> 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<Wallet> openWallet(const std::string &path, const std::string &password, NetworkType nettype, uint64_t kdf_rounds = 1, std::shared_ptr<WalletListener> listener = nullptr) = 0;
std::shared_ptr<Wallet> 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<Wallet> 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<Wallet> recoveryWallet(const std::string &path, const std::string &mnemonic, NetworkType nettype, uint64_t restoreHeight = 0) = 0;
std::unique_ptr<Wallet> 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<Wallet> 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<Wallet> 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<Wallet> 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> 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<std::string> 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<WalletManager> getWalletManager();
static Monero::WalletManager* getWalletManager();
static void setLogLevel(int level);
static void setLogCategories(const std::string &categories);
};
+2
View File
@@ -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
+203
View File
@@ -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 <boost/thread/lock_guard.hpp>
#include <utility>
#include "backend.h"
#include "cryptonote_basic/cryptonote_basic_impl.h"
namespace lwsf { namespace internal {
namespace
{
void clear_addresses(std::vector<Monero::AddressBookRow*>& 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<address_book, force_refresh_>;
}
void address_book::clear_status()
{
error_string_.clear();
error_ = Status_Ok;
}
address_book::address_book(std::shared_ptr<backend::wallet> 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<Monero::AddressBookRow>(addresses_.size(), dst_addr, payment_id, description);
addresses_.push_back(row.get());
row.release();
const boost::lock_guard<boost::mutex> 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<Monero::AddressBookRow> destroy{addresses_[rowId]};
addresses_[rowId] = nullptr;
addresses_.erase(addresses_.begin() + rowId);
const boost::lock_guard<boost::mutex> 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<Monero::AddressBookRow> destroy{addresses_[index]};
addresses_[index] = nullptr;
addresses_[index] = new Monero::AddressBookRow{
index, destroy->getAddress(), destroy->getPaymentId(), description
};
const boost::lock_guard<boost::mutex> 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<boost::mutex> 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<int>::max();
static_assert(int_max <= std::numeric_limits<std::size_t>::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
+70
View File
@@ -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 <cstdint>
#include <memory>
#include <string>
#include <vector>
#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<backend::wallet> data_;
std::vector<Monero::AddressBookRow*> addresses_;
std::string error_string_;
ErrorCode error_;
void clear_status();
public:
explicit address_book(std::shared_ptr<backend::wallet> 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<Monero::AddressBookRow*> 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
+230 -33
View File
@@ -30,6 +30,7 @@
#include <boost/thread/lock_guard.hpp>
#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<typename F, typename T>
void map_address_book_entry(F& format, T& self)
{
wire::object(format,
WIRE_FIELD(address),
WIRE_FIELD(payment_id),
WIRE_FIELD(description)
);
}
template<typename F, typename T>
void map_subaddress(F& format, T& self)
{
wire::object(format, WIRE_FIELD(label));
}
template<typename F, typename T>
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<typename F, typename T>
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<typename F, typename T>
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<transaction>();
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<const rpc::subaddrs> 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<std::uint32_t, sub_account> 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<std::uint64_t>::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<epee::byte_slice> wallet::to_bytes() const
{
@@ -387,18 +525,27 @@ namespace lwsf { namespace internal { namespace backend
std::error_code wallet::login()
{
const boost::lock_guard<boost::mutex> 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<rpc::login_response>(client, login);
if (!response)
return response.error();
const auto response = rpc::invoke<rpc::login_response>(client, login);
if (!response)
return response.error();
const boost::lock_guard<boost::mutex> 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<rpc::get_subaddrs>(client, login);
if (response)
{
const boost::lock_guard<boost::mutex> 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<boost::mutex> 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<WalletListener> 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<boost::mutex> lock{sync};
for (const auto& account : primary.subaccounts)
{
if (account.first != next + 1)
break;
++next;
}
++next;
}
if (std::numeric_limits<std::uint32_t>::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<rpc::provision_subaddrs_response>(client, request);
if (!response)
return response.error();
bool matched = false;
const boost::lock_guard<boost::mutex> 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)};
+49 -16
View File
@@ -35,20 +35,22 @@
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <map>
#include <memory>
#include <optional>
#include <type_traits>
#include <variant>
#include <vector>
#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<std::uint32_t, subaddress> 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<crypto::key_image, transfer_out, memory> spends;
boost::container::flat_map<crypto::public_key, transfer_in, memory> receives; //!< Key is output pub
std::string description;
std::string label;
std::optional<std::time_t> timestamp;
std::uint64_t amount;
std::uint64_t fee;
std::optional<std::uint64_t> height;
std::uint64_t unlock_time;
TransactionInfo::Direction direction;
std::variant<std::nullptr_t, crypto::hash8, crypto::hash> payment_id;
Monero::TransactionInfo::Direction direction;
std::variant<rpc::empty, crypto::hash8, crypto::hash> 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<address_book_entry> addressbook;
std::map<std::uint32_t, sub_account> subaccounts;
boost::container::flat_map<crypto::hash, std::shared_ptr<transaction>, memory> txes;
std::map<std::string, std::string> 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<WalletListener> listener;
Monero::WalletListener* listener;
rpc::http_client client;
account primary;
std::atomic<std::chrono::steady_clock::time_point::duration::rep> 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<epee::byte_slice> 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);
+59
View File
@@ -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
+68
View File
@@ -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 <system_error>
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<lwsf::error>
: true_type
{};
}
+3 -1
View File
@@ -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
+76
View File
@@ -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 <stdexcept>
#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<backend::wallet> 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<std::string> pending_transaction::txid() const
{
return {epee::string_tools::pod_to_hex(get_transaction_hash(source_))};
}
}} // lwsf // internal
+95
View File
@@ -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 <cstdint>
#include <memory>
#include <string>
#include <system_error>
#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<backend::wallet> wallet_;
const cryptonote::transaction source_;
std::error_code error_;
const Priority priority_;
public:
pending_transaction(std::shared_ptr<backend::wallet> 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<std::string> txid() const override final;
virtual std::uint64_t txCount() const override final { return 1; }
virtual std::vector<uint32_t> subaddrAccount() const = 0;
virtual std::vector<std::set<uint32_t>> 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<std::string> signersKeys() const = 0;
};
}} // lwsf // internal
+41 -1
View File
@@ -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));
+51 -8
View File
@@ -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<std::string> 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<transaction_spend> spent_outputs;
std::variant<std::nullptr_t, crypto::hash8, crypto::hash> payment_id;
std::variant<empty, crypto::hash8, crypto::hash> payment_id;
std::optional<std::time_t> timestamp;
std::optional<uint64_string> 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<std::array<std::uint32_t, 2>> 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<subaddrs> 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<subaddrs> new_subaddrs;
std::vector<subaddrs> all_subaddrs;
};
void read_bytes(wire::json_reader&, provision_subaddrs_response&);
struct submit_raw_tx_request
{
+61
View File
@@ -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 <cstdint>
#include <memory>
#include <vector>
#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<backend::wallet> data_;
std::vector<Monero::SubaddressAccountRow*> rows_;
public:
explicit subaddress_account(std::shared_ptr<backend::wallet> 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<Monero::SubaddressAccountRow*> 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
+75 -37
View File
@@ -30,79 +30,117 @@
#include <boost/thread/lock_guard.hpp>
#include <limits>
#include <map>
#include <stdexcept>
#include "backend.h"
#include "transaction_info.h"
#include "hex.h" // monero/contrib/epee/include
namespace lwsf { namespace internal
{
namespace
{
void free_txes(std::vector<Monero::TransactionInfo*>& txes) noexcept
{
for (auto tx : txes)
delete tx;
txes.clear();
}
}
transaction_history::transaction_history(std::shared_ptr<backend::wallet> 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<boost::mutex> lock{data_->sync};
if (std::numeric_limits<int>::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<TransactionInfo> transaction_history::transaction(int index) const
Monero::TransactionInfo* transaction_history::transaction(int index) const
{
const boost::lock_guard<boost::mutex> 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<transaction_info>(data_, data_->primary.txes.nth(unsigned(index))->second);
if (index < 0 || txes_.size() <= unsigned(index))
return nullptr;
return txes_[index];
}
std::shared_ptr<TransactionInfo> 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<boost::mutex> lock{data_->sync};
const auto iter = data_->primary.txes.find(binary_id);
if (iter != data_->primary.txes.end())
return std::make_shared<transaction_info>(data_, iter->second);
return nullptr;
}
std::vector<std::shared_ptr<TransactionInfo>> transaction_history::getAll() const
{
std::vector<std::shared_ptr<TransactionInfo>> out;
// hold the lock during the map lookup, this is const and should be thread-safe
const boost::lock_guard<boost::mutex> lock{data_->sync};
out.reserve(data_->primary.txes.size());
for (const auto& tx : data_->primary.txes)
out.push_back(std::make_shared<transaction_info>(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<transaction_info>(data_, iter->second);
}
return info.get();
}
void transaction_history::refresh()
{
data_->refresh(true);
data_->refresh(false);
std::multimap<std::uint64_t, std::shared_ptr<const backend::transaction>> temp;
{
const boost::lock_guard<boost::mutex> lock{data_->sync};
if (std::numeric_limits<int>::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<std::uint64_t>::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<Monero::TransactionInfo> 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<transaction_info*>(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 &note)
{
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<boost::mutex> 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
+12 -7
View File
@@ -29,14 +29,19 @@
#pragma once
#include <memory>
#include "backend.h"
#include "lws_frontend.h"
#include <unordered_map>
#include <vector>
#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<backend::wallet> data_;
std::vector<Monero::TransactionInfo*> txes_;
mutable std::unordered_map<crypto::hash, std::unique_ptr<Monero::TransactionInfo>> by_id_;
public:
explicit transaction_history(std::shared_ptr<backend::wallet> 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<TransactionInfo> transaction(int index) const override;
virtual std::shared_ptr<TransactionInfo> transaction(const std::string &id) const override;
virtual std::vector<std::shared_ptr<TransactionInfo>> 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<Monero::TransactionInfo*> getAll() const override { return txes_; }
virtual void refresh() override;
virtual void setTxNote(const std::string &txid, const std::string &note) override;
};
+73 -6
View File
@@ -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<backend::wallet> wallet, std::shared_ptr<backend::transaction> 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<backend::wallet> wallet, std::shared_ptr<const backend::transaction> 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<const backend::transaction> 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<boost::mutex> lock{wallet_->sync};
return data_->description;
}
std::set<std::uint32_t> transaction_info::subaddrIndex() const
{
std::set<std::uint32_t> 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<boost::mutex> 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<boost::mutex> 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)
+19 -13
View File
@@ -35,18 +35,22 @@
#include <vector>
#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<backend::wallet> wallet_;
const std::shared_ptr<backend::transaction> data_;
std::shared_ptr<const backend::transaction> data_;
std::vector<Transfer> transfers_;
void update_transfers();
public:
explicit transaction_info(std::shared_ptr<backend::wallet> wallet, std::shared_ptr<backend::transaction> data);
explicit transaction_info(std::shared_ptr<backend::wallet> wallet, std::shared_ptr<const backend::transaction> 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<const backend::transaction> 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<std::uint64_t>::max()); }
virtual std::string description() const override;
virtual std::set<uint32_t> 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<uint32_t> 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<std::time_t>::max()); }
virtual std::string paymentId() const override;
virtual const std::vector<Transfer>& transfers() const override { return transfers_; }
};
+187 -16
View File
@@ -40,6 +40,7 @@
#include <sodium/randombytes.h>
#include <sodium/crypto_aead_chacha20poly1305.h>
#include <string_view>
#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<boost::mutex> 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<boost::mutex> 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<backend::wallet>()),
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<backend::wallet> data)
wallet::wallet(open_tag, Monero::NetworkType nettype, std::string filename, std::string password, const std::uint64_t kdf_rounds, std::shared_ptr<backend::wallet> 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<int>::max() <= std::numeric_limits<rep_type>::max());
if (0 < millis)
{
const boost::lock_guard<boost::mutex> 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<std::pair<std::string, uint64_t>> &destinations,
PendingTransaction::Priority priority) const
Monero::PendingTransaction::Priority priority) const
{
throw std::runtime_error{"Not Implemented yet"};
}
std::shared_ptr<TransactionHistory> wallet::history()
bool wallet::exportKeyImages(const std::string &filename, bool all)
{
return std::make_shared<transaction_history>(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<WalletListener> 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<std::string> &txids)
{
throw std::runtime_error{"scanTransactions not implemented"};
}
Monero::AddressBook* wallet::addressBook()
{
if (!addressbook_)
addressbook_ = std::make_unique<address_book>(data_);
return addressbook_.get();
}
Monero::TransactionHistory* wallet::history()
{
if (!history_)
history_ = std::make_unique<transaction_history>(data_);
return history_.get();
}
Monero::SubaddressAccount* wallet::subaddressAccount()
{
if (!subaddresses_)
subaddresses_ = std::make_unique<subaddress_account>(data_);
return subaddresses_.get();
}
void wallet::setListener(Monero::WalletListener* listener)
{
{
const boost::lock_guard<boost::mutex> 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<boost::mutex> 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<boost::mutex> 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 &note)
{
crypto::hash binary_id{};
if (!epee::string_tools::hex_to_pod(txid, binary_id))
return false;
const boost::lock_guard<boost::mutex> 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<boost::mutex> 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<boost::mutex> 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
+49 -47
View File
@@ -38,6 +38,7 @@
#include <string>
#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<backend::wallet> data_;
std::unique_ptr<Monero::AddressBook> addressbook_;
std::unique_ptr<Monero::TransactionHistory> history_;
std::unique_ptr<Monero::SubaddressAccount> 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<backend::wallet> 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<backend::wallet> 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<PendingTransaction> 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<PendingTransaction> createTransactionMultDest(const std::vector<std::string> &dst_addr, const std::string &payment_id,
optional<std::vector<uint64_t>> amount, uint32_t mixin_count,
PendingTransaction::Priority = PendingTransaction::Priority::Low,
virtual Monero::PendingTransaction* createTransactionMultDest(const std::vector<std::string> &dst_addr, const std::string &payment_id,
Monero::optional<std::vector<uint64_t>> amount, uint32_t mixin_count,
Monero::PendingTransaction::Priority = Monero::PendingTransaction::Priority_Low,
uint32_t subaddr_account = 0,
std::set<uint32_t> subaddr_indices = {}) = 0;
@@ -495,9 +497,9 @@ namespace internal
* after object returned
*/
virtual std::unique_ptr<PendingTransaction> 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<uint64_t> amount, uint32_t mixin_count,
PendingTransaction::Priority = PendingTransaction::Priority::Low,
Monero::PendingTransaction::Priority = Monero::PendingTransaction::Priority_Low,
uint32_t subaddr_account = 0,
std::set<uint32_t> subaddr_indices = {}) = 0;
@@ -507,14 +509,14 @@ namespace internal
* after object returned
*/
virtual std::unique_ptr<PendingTransaction> 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<UnsignedTransaction> 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<std::pair<std::string, uint64_t>> &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<std::string> &txids) = 0;
virtual bool scanTransactions(const std::vector<std::string> &txids) override;
virtual std::shared_ptr<TransactionHistory> history() override;
virtual std::shared_ptr<AddressBook> addressBook() = 0;
virtual std::shared_ptr<Subaddress> subaddress() = 0;
virtual std::shared_ptr<SubaddressAccount> subaddressAccount() = 0;
virtual void setListener(std::shared_ptr<WalletListener>) 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 &note) = 0;
virtual bool setUserNote(const std::string &txid, const std::string &note) 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;
+27 -24
View File
@@ -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<Wallet> 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>(
wallet::create_tag{}, nettype, path, password, kdf_rounds, std::make_shared<backend::wallet>()
);
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<Wallet> openWallet(const std::string &path, const std::string &password, NetworkType nettype, uint64_t kdf_rounds, std::shared_ptr<WalletListener> 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<backend::wallet>();
data->listener = std::move(listener);
auto out = std::make_shared<wallet>(
auto out = std::make_unique<wallet>(
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<Wallet> 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<Wallet> 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<Wallet> 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<Wallet> 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<Wallet> 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> wallet, const bool store) override
bool closeWallet(Monero::Wallet* const wallet, const bool store) override
{
const std::unique_ptr<Monero::Wallet> 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<WalletManager> WalletManagerFactory::getWalletManager()
Monero::WalletManager* WalletManagerFactory::getWalletManager()
{
return std::make_unique<internal::wallet_manager>();
return new internal::wallet_manager{};
}
void WalletManagerFactory::setLogLevel(int level)
+54
View File
@@ -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 <stdexcept>
#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);
}
}
+64
View File
@@ -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 <cstddef>
#include <cstdint>
#include <string>
#include <variant>
#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<std::nullptr_t, bool, std::uintmax_t, std::intmax_t, double, std::string>;
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
+13
View File
@@ -31,6 +31,7 @@
#include <boost/variant/variant_fwd.hpp>
#include <functional>
#include <utility>
#include <variant>
#include "wire/error.h"
#include "wire/fwd.h"
@@ -117,6 +118,10 @@ namespace wire
inline const U* get_if(const boost::variant<T...>& value)
{ return boost::get<U>(std::addressof(value)); }
template<typename U, typename... T>
inline const U* get_if(const std::variant<T...>& value)
{ return std::get_if<U>(std::addressof(value)); }
template<typename U, typename T>
inline const U* get_if(const variant_<T>& value)
{ return adapt::get_if<U>(value.get_variant()); }
@@ -186,6 +191,14 @@ namespace wire
inline const U& get(const boost::variant<T...>& value)
{ return boost::get<U>(value); }
template<typename U, typename... T>
inline U& get(std::variant<T...>& value)
{ return std::get<U>(value); }
template<typename U, typename... T>
inline const U& get(const std::variant<T...>& value)
{ return std::get<U>(value); }
template<typename U, typename T>
inline const U& get(const variant_<T>& value)
{ return adapt::get<U>(value.get_variant()); }