walletmodel.h 9.41 KB
Newer Older
1
// Copyright (c) 2011-2014 The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

Pavel Janík's avatar
Pavel Janík committed
5
6
#ifndef BITCOIN_QT_WALLETMODEL_H
#define BITCOIN_QT_WALLETMODEL_H
7

8
9
#include "paymentrequestplus.h"
#include "walletmodeltransaction.h"
10

11
#include "support/allocators/secure.h"
12

Cozz Lovan's avatar
Cozz Lovan committed
13
#include <map>
14
15
16
#include <vector>

#include <QObject>
17

18
class AddressTableModel;
19
class OptionsModel;
20
class RecentRequestsTableModel;
21
class TransactionTableModel;
22
class WalletModelTransaction;
23
24

class CCoinControl;
Cozz Lovan's avatar
Cozz Lovan committed
25
26
class CKeyID;
class COutPoint;
27
28
class COutput;
class CPubKey;
29
class CWallet;
30
class uint256;
31

32
33
34
35
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE

36
class SendCoinsRecipient
37
{
38
public:
Cozz Lovan's avatar
Cozz Lovan committed
39
    explicit SendCoinsRecipient() : amount(0), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) { }
40
    explicit SendCoinsRecipient(const QString &addr, const QString &label, const CAmount& amount, const QString &message):
Cozz Lovan's avatar
Cozz Lovan committed
41
        address(addr), label(label), amount(amount), message(message), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) {}
42

43
    // If from an unauthenticated payment request, this is used for storing
44
45
46
47
    // the addresses, e.g. address-A<br />address-B<br />address-C.
    // Info: As we don't need to process addresses in here when using
    // payment requests, we can abuse it for displaying an address list.
    // Todo: This is a hack, should be replaced with a cleaner solution!
48
49
    QString address;
    QString label;
50
    CAmount amount;
51
    // If from a payment request, this is used for storing the memo
52
    QString message;
53
54
55

    // If from a payment request, paymentRequest.IsInitialized() will be true
    PaymentRequestPlus paymentRequest;
56
57
    // Empty if no authentication or invalid signature/cert/etc.
    QString authenticatedMerchant;
58

Cozz Lovan's avatar
Cozz Lovan committed
59
60
    bool fSubtractFeeFromAmount; // memory only

61
    static const int CURRENT_VERSION = 1;
62
63
    int nVersion;

64
    ADD_SERIALIZE_METHODS;
Kamil Domanski's avatar
Kamil Domanski committed
65

66
    template <typename Stream, typename Operation>
67
    inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
68
69
70
        std::string sAddress = address.toStdString();
        std::string sLabel = label.toStdString();
        std::string sMessage = message.toStdString();
71
        std::string sPaymentRequest;
72
73
74
        if (!ser_action.ForRead() && paymentRequest.IsInitialized())
            paymentRequest.SerializeToString(&sPaymentRequest);
        std::string sAuthenticatedMerchant = authenticatedMerchant.toStdString();
75

76
77
        READWRITE(this->nVersion);
        nVersion = this->nVersion;
78
79
        READWRITE(sAddress);
        READWRITE(sLabel);
80
        READWRITE(amount);
81
82
83
84
        READWRITE(sMessage);
        READWRITE(sPaymentRequest);
        READWRITE(sAuthenticatedMerchant);

85
        if (ser_action.ForRead())
86
        {
87
88
89
            address = QString::fromStdString(sAddress);
            label = QString::fromStdString(sLabel);
            message = QString::fromStdString(sMessage);
90
            if (!sPaymentRequest.empty())
91
92
                paymentRequest.parse(QByteArray::fromRawData(sPaymentRequest.data(), sPaymentRequest.size()));
            authenticatedMerchant = QString::fromStdString(sAuthenticatedMerchant);
93
        }
Kamil Domanski's avatar
Kamil Domanski committed
94
    }
95
96
};

97
/** Interface to Bitcoin wallet from Qt view code. */
98
99
100
class WalletModel : public QObject
{
    Q_OBJECT
101

102
public:
103
    explicit WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent = 0);
104
    ~WalletModel();
105

106
    enum StatusCode // Returned by sendCoins
107
108
109
110
111
112
    {
        OK,
        InvalidAmount,
        InvalidAddress,
        AmountExceedsBalance,
        AmountWithFeeExceedsBalance,
113
        DuplicateAddress,
114
        TransactionCreationFailed, // Error returned when wallet is still locked
Cozz Lovan's avatar
Cozz Lovan committed
115
        TransactionCommitFailed,
116
        AbsurdFee,
117
        PaymentRequestExpired
118
119
    };

120
121
122
123
124
125
126
    enum EncryptionStatus
    {
        Unencrypted,  // !wallet->IsCrypted()
        Locked,       // wallet->IsCrypted() && wallet->IsLocked()
        Unlocked      // wallet->IsCrypted() && !wallet->IsLocked()
    };

127
128
129
    OptionsModel *getOptionsModel();
    AddressTableModel *getAddressTableModel();
    TransactionTableModel *getTransactionTableModel();
130
    RecentRequestsTableModel *getRecentRequestsTableModel();
131

132
133
134
    CAmount getBalance(const CCoinControl *coinControl = NULL) const;
    CAmount getUnconfirmedBalance() const;
    CAmount getImmatureBalance() const;
135
    bool haveWatchOnly() const;
136
137
138
    CAmount getWatchBalance() const;
    CAmount getWatchUnconfirmedBalance() const;
    CAmount getWatchImmatureBalance() const;
139
140
    EncryptionStatus getEncryptionStatus() const;

141
142
143
    // Check address for validity
    bool validateAddress(const QString &address);

144
    // Return status record for SendCoins, contains error id + information
145
146
    struct SendCoinsReturn
    {
147
        SendCoinsReturn(StatusCode status = OK):
148
            status(status) {}
149
150
151
        StatusCode status;
    };

152
    // prepare transaction for getting txfee before sending coins
153
    SendCoinsReturn prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
154

155
    // Send coins to a list of recipients
156
    SendCoinsReturn sendCoins(WalletModelTransaction &transaction);
157
158

    // Wallet encryption
159
    bool setWalletEncrypted(bool encrypted, const SecureString &passphrase);
160
    // Passphrase only needed when unlocking
161
162
    bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString());
    bool changePassphrase(const SecureString &oldPass, const SecureString &newPass);
sje397's avatar
sje397 committed
163
164
    // Wallet backup
    bool backupWallet(const QString &filename);
165
166
167
168
169
170
171
172
173
174

    // RAI object for unlocking wallet, returned by requestUnlock()
    class UnlockContext
    {
    public:
        UnlockContext(WalletModel *wallet, bool valid, bool relock);
        ~UnlockContext();

        bool isValid() const { return valid; }

175
176
177
        // Copy operator and constructor transfer the context
        UnlockContext(const UnlockContext& obj) { CopyFrom(obj); }
        UnlockContext& operator=(const UnlockContext& rhs) { CopyFrom(rhs); return *this; }
178
179
180
181
182
183
184
185
186
187
    private:
        WalletModel *wallet;
        bool valid;
        mutable bool relock; // mutable, as it can be set to false by copying

        void CopyFrom(const UnlockContext& rhs);
    };

    UnlockContext requestUnlock();

Cozz Lovan's avatar
Cozz Lovan committed
188
189
    bool getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
    void getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs);
Gavin Andresen's avatar
Gavin Andresen committed
190
    bool isSpent(const COutPoint& outpoint) const;
Cozz Lovan's avatar
Cozz Lovan committed
191
192
193
194
195
196
197
    void listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const;

    bool isLockedCoin(uint256 hash, unsigned int n) const;
    void lockCoin(COutPoint& output);
    void unlockCoin(COutPoint& output);
    void listLockedCoins(std::vector<COutPoint>& vOutpts);

198
199
200
    void loadReceiveRequests(std::vector<std::string>& vReceiveRequests);
    bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest);

201
202
private:
    CWallet *wallet;
203
    bool fHaveWatchOnly;
204
    bool fForceCheckBalanceChanged;
205
206
207
208
209
210
211

    // Wallet has an options model for wallet-specific options
    // (transaction fee, for example)
    OptionsModel *optionsModel;

    AddressTableModel *addressTableModel;
    TransactionTableModel *transactionTableModel;
212
    RecentRequestsTableModel *recentRequestsTableModel;
213

214
    // Cache some values to be able to detect changes
215
216
217
218
219
220
    CAmount cachedBalance;
    CAmount cachedUnconfirmedBalance;
    CAmount cachedImmatureBalance;
    CAmount cachedWatchOnlyBalance;
    CAmount cachedWatchUnconfBalance;
    CAmount cachedWatchImmatureBalance;
221
    EncryptionStatus cachedEncryptionStatus;
222
223
224
    int cachedNumBlocks;

    QTimer *pollTimer;
225

226
227
    void subscribeToCoreSignals();
    void unsubscribeFromCoreSignals();
228
229
    void checkBalanceChanged();

230
signals:
231
    // Signal that balance in wallet changed
232
233
    void balanceChanged(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
                        const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance);
234
235

    // Encryption status of wallet changed
236
    void encryptionStatusChanged(int status);
237
238
239
240

    // Signal emitted when wallet needs to be unlocked
    // It is valid behaviour for listeners to keep the wallet locked after this signal;
    // this means that the unlocking failed or was cancelled.
241
    void requireUnlock();
242

243
    // Fired when a message should be reported to the user
244
    void message(const QString &title, const QString &message, unsigned int style);
245

246
247
248
    // Coins sent: from wallet, to recipient, in (serialized) transaction:
    void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction);

Cozz Lovan's avatar
Cozz Lovan committed
249
250
251
    // Show progress dialog e.g. for rescan
    void showProgress(const QString &title, int nProgress);

252
253
254
    // Watch-only address added
    void notifyWatchonlyChanged(bool fHaveWatchonly);

255
public slots:
256
257
258
    /* Wallet status might have changed */
    void updateStatus();
    /* New transaction, or transaction changed status */
259
    void updateTransaction();
260
    /* New, updated or removed address book entry */
261
    void updateAddressBook(const QString &address, const QString &label, bool isMine, const QString &purpose, int status);
262
    /* Watch-only added */
263
    void updateWatchOnlyFlag(bool fHaveWatchonly);
264
265
    /* Current, immature or unconfirmed balance might have changed - emit 'balanceChanged' if so */
    void pollBalanceChanged();
266
267
};

Pavel Janík's avatar
Pavel Janík committed
268
#endif // BITCOIN_QT_WALLETMODEL_H