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

5
6
7
#ifndef WALLETMODEL_H
#define WALLETMODEL_H

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

11
#include "allocators.h" /* for SecureString */
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:
39
    explicit SendCoinsRecipient() : amount(0), nVersion(SendCoinsRecipient::CURRENT_VERSION) { }
40
    explicit SendCoinsRecipient(const QString &addr, const QString &label, quint64 amount, const QString &message):
41
        address(addr), label(label), amount(amount), message(message), nVersion(SendCoinsRecipient::CURRENT_VERSION) {}
42

43
44
45
46
47
    // If from an insecure payment request, this is used for storing
    // the addresses, e.g. address-A<br />address-B<br />address-C.
    // Info: As we don't need to process addresses in here when using
    // payment requests, we can abuse it for displaying an address list.
    // Todo: This is a hack, should be replaced with a cleaner solution!
48
49
50
    QString address;
    QString label;
    qint64 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

59
    static const int CURRENT_VERSION = 1;
60
61
62
    int nVersion;

    IMPLEMENT_SERIALIZE
Kamil Domanski's avatar
Kamil Domanski committed
63
64
65
66
67
68
69

    template <typename T, typename Stream, typename Operation>
    inline static size_t SerializationOp(T thisPtr, Stream& s, Operation ser_action, int nType, int nVersion) {
        size_t nSerSize = 0;
        bool fRead = boost::is_same<Operation, CSerActionUnserialize>();

        SendCoinsRecipient* pthis = const_cast<SendCoinsRecipient*>(thisPtr);
70
71
72
73
74
75
76
77
78
79
80
81
82

        std::string sAddress = pthis->address.toStdString();
        std::string sLabel = pthis->label.toStdString();
        std::string sMessage = pthis->message.toStdString();
        std::string sPaymentRequest;
        if (!fRead && pthis->paymentRequest.IsInitialized())
            pthis->paymentRequest.SerializeToString(&sPaymentRequest);
        std::string sAuthenticatedMerchant = pthis->authenticatedMerchant.toStdString();

        READWRITE(pthis->nVersion);
        nVersion = pthis->nVersion;
        READWRITE(sAddress);
        READWRITE(sLabel);
Kamil Domanski's avatar
Kamil Domanski committed
83
        READWRITE(thisPtr->amount);
84
85
86
87
88
89
90
91
92
93
94
95
96
        READWRITE(sMessage);
        READWRITE(sPaymentRequest);
        READWRITE(sAuthenticatedMerchant);

        if (fRead)
        {
            pthis->address = QString::fromStdString(sAddress);
            pthis->label = QString::fromStdString(sLabel);
            pthis->message = QString::fromStdString(sMessage);
            if (!sPaymentRequest.empty())
                pthis->paymentRequest.parse(QByteArray::fromRawData(sPaymentRequest.data(), sPaymentRequest.size()));
            pthis->authenticatedMerchant = QString::fromStdString(sAuthenticatedMerchant);
        }
Kamil Domanski's avatar
Kamil Domanski committed
97
98
99

        return nSerSize;
    }
100
101
};

102
/** Interface to Bitcoin wallet from Qt view code. */
103
104
105
class WalletModel : public QObject
{
    Q_OBJECT
106

107
public:
108
    explicit WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent = 0);
109
    ~WalletModel();
110

111
    enum StatusCode // Returned by sendCoins
112
113
114
115
116
117
    {
        OK,
        InvalidAmount,
        InvalidAddress,
        AmountExceedsBalance,
        AmountWithFeeExceedsBalance,
118
        DuplicateAddress,
119
        TransactionCreationFailed, // Error returned when wallet is still locked
120
        TransactionCommitFailed
121
122
    };

123
124
125
126
127
128
129
    enum EncryptionStatus
    {
        Unencrypted,  // !wallet->IsCrypted()
        Locked,       // wallet->IsCrypted() && wallet->IsLocked()
        Unlocked      // wallet->IsCrypted() && !wallet->IsLocked()
    };

130
131
132
    OptionsModel *getOptionsModel();
    AddressTableModel *getAddressTableModel();
    TransactionTableModel *getTransactionTableModel();
133
    RecentRequestsTableModel *getRecentRequestsTableModel();
134

135
    qint64 getBalance(const CCoinControl *coinControl = NULL) const;
136
    qint64 getUnconfirmedBalance() const;
137
    qint64 getImmatureBalance() const;
138
    bool haveWatchOnly() const;
139
140
141
    qint64 getWatchBalance() const;
    qint64 getWatchUnconfirmedBalance() const;
    qint64 getWatchImmatureBalance() const;
142
    EncryptionStatus getEncryptionStatus() const;
143
    bool processingQueuedTransactions() { return fProcessingQueuedTransactions; }
144

145
146
147
    // Check address for validity
    bool validateAddress(const QString &address);

148
    // Return status record for SendCoins, contains error id + information
149
150
    struct SendCoinsReturn
    {
151
        SendCoinsReturn(StatusCode status = OK):
152
            status(status) {}
153
154
155
        StatusCode status;
    };

156
    // prepare transaction for getting txfee before sending coins
157
    SendCoinsReturn prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL);
158

159
    // Send coins to a list of recipients
160
    SendCoinsReturn sendCoins(WalletModelTransaction &transaction);
161
162

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

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

        bool isValid() const { return valid; }

179
180
181
        // Copy operator and constructor transfer the context
        UnlockContext(const UnlockContext& obj) { CopyFrom(obj); }
        UnlockContext& operator=(const UnlockContext& rhs) { CopyFrom(rhs); return *this; }
182
183
184
185
186
187
188
189
190
191
    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
192
193
    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
194
    bool isSpent(const COutPoint& outpoint) const;
Cozz Lovan's avatar
Cozz Lovan committed
195
196
197
198
199
200
201
    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);

202
203
204
    void loadReceiveRequests(std::vector<std::string>& vReceiveRequests);
    bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest);

205
206
private:
    CWallet *wallet;
207
    bool fProcessingQueuedTransactions;
208
    bool fHaveWatchOnly;
209
210
211
212
213
214
215

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

    AddressTableModel *addressTableModel;
    TransactionTableModel *transactionTableModel;
216
    RecentRequestsTableModel *recentRequestsTableModel;
217

218
    // Cache some values to be able to detect changes
219
220
    qint64 cachedBalance;
    qint64 cachedUnconfirmedBalance;
221
    qint64 cachedImmatureBalance;
222
223
224
    qint64 cachedWatchOnlyBalance;
    qint64 cachedWatchUnconfBalance;
    qint64 cachedWatchImmatureBalance;
225
    EncryptionStatus cachedEncryptionStatus;
226
227
228
    int cachedNumBlocks;

    QTimer *pollTimer;
229

230
231
    void subscribeToCoreSignals();
    void unsubscribeFromCoreSignals();
232
233
    void checkBalanceChanged();

234
signals:
235
    // Signal that balance in wallet changed
236
237
    void balanceChanged(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance,
                        qint64 watchOnlyBalance, qint64 watchUnconfBalance, qint64 watchImmatureBalance);
238
239

    // Encryption status of wallet changed
240
    void encryptionStatusChanged(int status);
241
242
243
244

    // 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.
245
    void requireUnlock();
246

247
    // Fired when a message should be reported to the user
248
    void message(const QString &title, const QString &message, unsigned int style);
249

250
251
252
    // Coins sent: from wallet, to recipient, in (serialized) transaction:
    void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction);

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

256
257
258
    // Watch-only address added
    void notifyWatchonlyChanged(bool fHaveWatchonly);

259
public slots:
260
261
262
263
264
    /* Wallet status might have changed */
    void updateStatus();
    /* New transaction, or transaction changed status */
    void updateTransaction(const QString &hash, int status);
    /* New, updated or removed address book entry */
265
    void updateAddressBook(const QString &address, const QString &label, bool isMine, const QString &purpose, int status);
266
267
    /* Watchonly added */
    void updateWatchOnlyFlag(bool fHaveWatchonly);
268
269
    /* Current, immature or unconfirmed balance might have changed - emit 'balanceChanged' if so */
    void pollBalanceChanged();
270
271
    /* Needed to update fProcessingQueuedTransactions through a QueuedConnection */
    void setProcessingQueuedTransactions(bool value) { fProcessingQueuedTransactions = value; }
272
273
274
};

#endif // WALLETMODEL_H