Decrease minimum TX fee to 0.0005 BTC.
[novacoin.git] / src / main.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4
5 class COutPoint;
6 class CInPoint;
7 class CDiskTxPos;
8 class CCoinBase;
9 class CTxIn;
10 class CTxOut;
11 class CTransaction;
12 class CBlock;
13 class CBlockIndex;
14 class CWalletTx;
15 class CKeyItem;
16
17 static const unsigned int MAX_BLOCK_SIZE = 1000000;
18 static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
19 static const int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
20 static const int64 COIN = 100000000;
21 static const int64 CENT = 1000000;
22 static const int64 MIN_TX_FEE = 50000;
23 static const int64 MAX_MONEY = 21000000 * COIN;
24 inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
25 static const int COINBASE_MATURITY = 100;
26 #ifdef USE_UPNP
27 static const int fHaveUPnP = true;
28 #else
29 static const int fHaveUPnP = false;
30 #endif
31
32
33
34
35
36
37 extern CCriticalSection cs_main;
38 extern map<uint256, CBlockIndex*> mapBlockIndex;
39 extern uint256 hashGenesisBlock;
40 extern CBigNum bnProofOfWorkLimit;
41 extern CBlockIndex* pindexGenesisBlock;
42 extern int nBestHeight;
43 extern CBigNum bnBestChainWork;
44 extern CBigNum bnBestInvalidWork;
45 extern uint256 hashBestChain;
46 extern CBlockIndex* pindexBest;
47 extern unsigned int nTransactionsUpdated;
48 extern map<uint256, int> mapRequestCount;
49 extern CCriticalSection cs_mapRequestCount;
50 extern map<string, string> mapAddressBook;
51 extern CCriticalSection cs_mapAddressBook;
52 extern vector<unsigned char> vchDefaultKey;
53 extern double dHashesPerSec;
54 extern int64 nHPSTimerStart;
55
56 // Settings
57 extern int fGenerateBitcoins;
58 extern int64 nTransactionFee;
59 extern CAddress addrIncoming;
60 extern int fLimitProcessors;
61 extern int nLimitProcessors;
62 extern int fMinimizeToTray;
63 extern int fMinimizeOnClose;
64 extern int fUseUPnP;
65
66
67
68
69
70
71
72 bool CheckDiskSpace(uint64 nAdditionalBytes=0);
73 FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
74 FILE* AppendBlockFile(unsigned int& nFileRet);
75 bool AddKey(const CKey& key);
76 vector<unsigned char> GenerateNewKey();
77 bool AddToWallet(const CWalletTx& wtxIn);
78 void WalletUpdateSpent(const COutPoint& prevout);
79 int ScanForWalletTransactions(CBlockIndex* pindexStart);
80 void ReacceptWalletTransactions();
81 bool LoadBlockIndex(bool fAllowNew=true);
82 void PrintBlockTree();
83 bool ProcessMessages(CNode* pfrom);
84 bool ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv);
85 bool SendMessages(CNode* pto, bool fSendTrickle);
86 int64 GetBalance();
87 bool CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
88 bool CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet);
89 bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
90 bool BroadcastTransaction(CWalletTx& wtxNew);
91 string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
92 string SendMoneyToBitcoinAddress(string strAddress, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
93 void GenerateBitcoins(bool fGenerate);
94 void ThreadBitcoinMiner(void* parg);
95 CBlock* CreateNewBlock(CReserveKey& reservekey);
96 void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce, int64& nPrevTime);
97 void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
98 bool CheckWork(CBlock* pblock, CReserveKey& reservekey);
99 void BitcoinMiner();
100 bool CheckProofOfWork(uint256 hash, unsigned int nBits);
101 bool IsInitialBlockDownload();
102 string GetWarnings(string strFor);
103
104
105
106
107
108
109
110
111
112
113
114
115 class CDiskTxPos
116 {
117 public:
118     unsigned int nFile;
119     unsigned int nBlockPos;
120     unsigned int nTxPos;
121
122     CDiskTxPos()
123     {
124         SetNull();
125     }
126
127     CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
128     {
129         nFile = nFileIn;
130         nBlockPos = nBlockPosIn;
131         nTxPos = nTxPosIn;
132     }
133
134     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
135     void SetNull() { nFile = -1; nBlockPos = 0; nTxPos = 0; }
136     bool IsNull() const { return (nFile == -1); }
137
138     friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
139     {
140         return (a.nFile     == b.nFile &&
141                 a.nBlockPos == b.nBlockPos &&
142                 a.nTxPos    == b.nTxPos);
143     }
144
145     friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
146     {
147         return !(a == b);
148     }
149
150     string ToString() const
151     {
152         if (IsNull())
153             return strprintf("null");
154         else
155             return strprintf("(nFile=%d, nBlockPos=%d, nTxPos=%d)", nFile, nBlockPos, nTxPos);
156     }
157
158     void print() const
159     {
160         printf("%s", ToString().c_str());
161     }
162 };
163
164
165
166
167 class CInPoint
168 {
169 public:
170     CTransaction* ptx;
171     unsigned int n;
172
173     CInPoint() { SetNull(); }
174     CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
175     void SetNull() { ptx = NULL; n = -1; }
176     bool IsNull() const { return (ptx == NULL && n == -1); }
177 };
178
179
180
181
182 class COutPoint
183 {
184 public:
185     uint256 hash;
186     unsigned int n;
187
188     COutPoint() { SetNull(); }
189     COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
190     IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
191     void SetNull() { hash = 0; n = -1; }
192     bool IsNull() const { return (hash == 0 && n == -1); }
193
194     friend bool operator<(const COutPoint& a, const COutPoint& b)
195     {
196         return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
197     }
198
199     friend bool operator==(const COutPoint& a, const COutPoint& b)
200     {
201         return (a.hash == b.hash && a.n == b.n);
202     }
203
204     friend bool operator!=(const COutPoint& a, const COutPoint& b)
205     {
206         return !(a == b);
207     }
208
209     string ToString() const
210     {
211         return strprintf("COutPoint(%s, %d)", hash.ToString().substr(0,10).c_str(), n);
212     }
213
214     void print() const
215     {
216         printf("%s\n", ToString().c_str());
217     }
218 };
219
220
221
222
223 //
224 // An input of a transaction.  It contains the location of the previous
225 // transaction's output that it claims and a signature that matches the
226 // output's public key.
227 //
228 class CTxIn
229 {
230 public:
231     COutPoint prevout;
232     CScript scriptSig;
233     unsigned int nSequence;
234
235     CTxIn()
236     {
237         nSequence = UINT_MAX;
238     }
239
240     explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
241     {
242         prevout = prevoutIn;
243         scriptSig = scriptSigIn;
244         nSequence = nSequenceIn;
245     }
246
247     CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=UINT_MAX)
248     {
249         prevout = COutPoint(hashPrevTx, nOut);
250         scriptSig = scriptSigIn;
251         nSequence = nSequenceIn;
252     }
253
254     IMPLEMENT_SERIALIZE
255     (
256         READWRITE(prevout);
257         READWRITE(scriptSig);
258         READWRITE(nSequence);
259     )
260
261     bool IsFinal() const
262     {
263         return (nSequence == UINT_MAX);
264     }
265
266     friend bool operator==(const CTxIn& a, const CTxIn& b)
267     {
268         return (a.prevout   == b.prevout &&
269                 a.scriptSig == b.scriptSig &&
270                 a.nSequence == b.nSequence);
271     }
272
273     friend bool operator!=(const CTxIn& a, const CTxIn& b)
274     {
275         return !(a == b);
276     }
277
278     string ToString() const
279     {
280         string str;
281         str += strprintf("CTxIn(");
282         str += prevout.ToString();
283         if (prevout.IsNull())
284             str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
285         else
286             str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
287         if (nSequence != UINT_MAX)
288             str += strprintf(", nSequence=%u", nSequence);
289         str += ")";
290         return str;
291     }
292
293     void print() const
294     {
295         printf("%s\n", ToString().c_str());
296     }
297
298     bool IsMine() const;
299     int64 GetDebit() const;
300 };
301
302
303
304
305 //
306 // An output of a transaction.  It contains the public key that the next input
307 // must be able to sign with to claim it.
308 //
309 class CTxOut
310 {
311 public:
312     int64 nValue;
313     CScript scriptPubKey;
314
315     CTxOut()
316     {
317         SetNull();
318     }
319
320     CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
321     {
322         nValue = nValueIn;
323         scriptPubKey = scriptPubKeyIn;
324     }
325
326     IMPLEMENT_SERIALIZE
327     (
328         READWRITE(nValue);
329         READWRITE(scriptPubKey);
330     )
331
332     void SetNull()
333     {
334         nValue = -1;
335         scriptPubKey.clear();
336     }
337
338     bool IsNull()
339     {
340         return (nValue == -1);
341     }
342
343     uint256 GetHash() const
344     {
345         return SerializeHash(*this);
346     }
347
348     bool IsMine() const
349     {
350         return ::IsMine(scriptPubKey);
351     }
352
353     int64 GetCredit() const
354     {
355         if (!MoneyRange(nValue))
356             throw runtime_error("CTxOut::GetCredit() : value out of range");
357         return (IsMine() ? nValue : 0);
358     }
359
360     bool IsChange() const
361     {
362         // On a debit transaction, a txout that's mine but isn't in the address book is change
363         vector<unsigned char> vchPubKey;
364         if (ExtractPubKey(scriptPubKey, true, vchPubKey))
365             CRITICAL_BLOCK(cs_mapAddressBook)
366                 if (!mapAddressBook.count(PubKeyToAddress(vchPubKey)))
367                     return true;
368         return false;
369     }
370
371     int64 GetChange() const
372     {
373         if (!MoneyRange(nValue))
374             throw runtime_error("CTxOut::GetChange() : value out of range");
375         return (IsChange() ? nValue : 0);
376     }
377
378     friend bool operator==(const CTxOut& a, const CTxOut& b)
379     {
380         return (a.nValue       == b.nValue &&
381                 a.scriptPubKey == b.scriptPubKey);
382     }
383
384     friend bool operator!=(const CTxOut& a, const CTxOut& b)
385     {
386         return !(a == b);
387     }
388
389     string ToString() const
390     {
391         if (scriptPubKey.size() < 6)
392             return "CTxOut(error)";
393         return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
394     }
395
396     void print() const
397     {
398         printf("%s\n", ToString().c_str());
399     }
400 };
401
402
403
404
405 //
406 // The basic transaction that is broadcasted on the network and contained in
407 // blocks.  A transaction can contain multiple inputs and outputs.
408 //
409 class CTransaction
410 {
411 public:
412     int nVersion;
413     vector<CTxIn> vin;
414     vector<CTxOut> vout;
415     unsigned int nLockTime;
416
417
418     CTransaction()
419     {
420         SetNull();
421     }
422
423     IMPLEMENT_SERIALIZE
424     (
425         READWRITE(this->nVersion);
426         nVersion = this->nVersion;
427         READWRITE(vin);
428         READWRITE(vout);
429         READWRITE(nLockTime);
430     )
431
432     void SetNull()
433     {
434         nVersion = 1;
435         vin.clear();
436         vout.clear();
437         nLockTime = 0;
438     }
439
440     bool IsNull() const
441     {
442         return (vin.empty() && vout.empty());
443     }
444
445     uint256 GetHash() const
446     {
447         return SerializeHash(*this);
448     }
449
450     bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
451     {
452         // Time based nLockTime implemented in 0.1.6
453         if (nLockTime == 0)
454             return true;
455         if (nBlockHeight == 0)
456             nBlockHeight = nBestHeight;
457         if (nBlockTime == 0)
458             nBlockTime = GetAdjustedTime();
459         if ((int64)nLockTime < (nLockTime < 500000000 ? (int64)nBlockHeight : nBlockTime))
460             return true;
461         foreach(const CTxIn& txin, vin)
462             if (!txin.IsFinal())
463                 return false;
464         return true;
465     }
466
467     bool IsNewerThan(const CTransaction& old) const
468     {
469         if (vin.size() != old.vin.size())
470             return false;
471         for (int i = 0; i < vin.size(); i++)
472             if (vin[i].prevout != old.vin[i].prevout)
473                 return false;
474
475         bool fNewer = false;
476         unsigned int nLowest = UINT_MAX;
477         for (int i = 0; i < vin.size(); i++)
478         {
479             if (vin[i].nSequence != old.vin[i].nSequence)
480             {
481                 if (vin[i].nSequence <= nLowest)
482                 {
483                     fNewer = false;
484                     nLowest = vin[i].nSequence;
485                 }
486                 if (old.vin[i].nSequence < nLowest)
487                 {
488                     fNewer = true;
489                     nLowest = old.vin[i].nSequence;
490                 }
491             }
492         }
493         return fNewer;
494     }
495
496     bool IsCoinBase() const
497     {
498         return (vin.size() == 1 && vin[0].prevout.IsNull());
499     }
500
501     int GetSigOpCount() const
502     {
503         int n = 0;
504         foreach(const CTxIn& txin, vin)
505             n += txin.scriptSig.GetSigOpCount();
506         foreach(const CTxOut& txout, vout)
507             n += txout.scriptPubKey.GetSigOpCount();
508         return n;
509     }
510
511     bool IsStandard() const
512     {
513         foreach(const CTxIn& txin, vin)
514             if (!txin.scriptSig.IsPushOnly())
515                 return error("nonstandard txin: %s", txin.scriptSig.ToString().c_str());
516         foreach(const CTxOut& txout, vout)
517             if (!::IsStandard(txout.scriptPubKey))
518                 return error("nonstandard txout: %s", txout.scriptPubKey.ToString().c_str());
519         return true;
520     }
521
522     bool IsMine() const
523     {
524         foreach(const CTxOut& txout, vout)
525             if (txout.IsMine())
526                 return true;
527         return false;
528     }
529
530     bool IsFromMe() const
531     {
532         return (GetDebit() > 0);
533     }
534
535     int64 GetDebit() const
536     {
537         int64 nDebit = 0;
538         foreach(const CTxIn& txin, vin)
539         {
540             nDebit += txin.GetDebit();
541             if (!MoneyRange(nDebit))
542                 throw runtime_error("CTransaction::GetDebit() : value out of range");
543         }
544         return nDebit;
545     }
546
547     int64 GetCredit() const
548     {
549         int64 nCredit = 0;
550         foreach(const CTxOut& txout, vout)
551         {
552             nCredit += txout.GetCredit();
553             if (!MoneyRange(nCredit))
554                 throw runtime_error("CTransaction::GetCredit() : value out of range");
555         }
556         return nCredit;
557     }
558
559     int64 GetChange() const
560     {
561         if (IsCoinBase())
562             return 0;
563         int64 nChange = 0;
564         foreach(const CTxOut& txout, vout)
565         {
566             nChange += txout.GetChange();
567             if (!MoneyRange(nChange))
568                 throw runtime_error("CTransaction::GetChange() : value out of range");
569         }
570         return nChange;
571     }
572
573     int64 GetValueOut() const
574     {
575         int64 nValueOut = 0;
576         foreach(const CTxOut& txout, vout)
577         {
578             nValueOut += txout.nValue;
579             if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
580                 throw runtime_error("CTransaction::GetValueOut() : value out of range");
581         }
582         return nValueOut;
583     }
584
585     static bool AllowFree(double dPriority)
586     {
587         // Large (in bytes) low-priority (new, small-coin) transactions
588         // need a fee.
589         return dPriority > COIN * 144 / 250;
590     }
591
592     int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true) const
593     {
594         // Base fee is 1 cent per kilobyte
595         unsigned int nBytes = ::GetSerializeSize(*this, SER_NETWORK);
596         unsigned int nNewBlockSize = nBlockSize + nBytes;
597         int64 nMinFee = (1 + (int64)nBytes / 1000) * MIN_TX_FEE;
598
599         if (fAllowFree)
600         {
601             if (nBlockSize == 1)
602             {
603                 // Transactions under 10K are free
604                 // (about 4500bc if made of 50bc inputs)
605                 if (nBytes < 10000)
606                     nMinFee = 0;
607             }
608             else
609             {
610                 // Free transaction area
611                 if (nNewBlockSize < 27000)
612                     nMinFee = 0;
613             }
614         }
615
616         // To limit dust spam, require MIN_TX_FEE if any output is less than 0.01
617         if (nMinFee < MIN_TX_FEE)
618             foreach(const CTxOut& txout, vout)
619                 if (txout.nValue < CENT)
620                     nMinFee = MIN_TX_FEE;
621
622         // Raise the price as the block approaches full
623         if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
624         {
625             if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
626                 return MAX_MONEY;
627             nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
628         }
629
630         if (!MoneyRange(nMinFee))
631             nMinFee = MAX_MONEY;
632         return nMinFee;
633     }
634
635
636     bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
637     {
638         CAutoFile filein = OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb");
639         if (!filein)
640             return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
641
642         // Read transaction
643         if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
644             return error("CTransaction::ReadFromDisk() : fseek failed");
645         filein >> *this;
646
647         // Return file pointer
648         if (pfileRet)
649         {
650             if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
651                 return error("CTransaction::ReadFromDisk() : second fseek failed");
652             *pfileRet = filein.release();
653         }
654         return true;
655     }
656
657     friend bool operator==(const CTransaction& a, const CTransaction& b)
658     {
659         return (a.nVersion  == b.nVersion &&
660                 a.vin       == b.vin &&
661                 a.vout      == b.vout &&
662                 a.nLockTime == b.nLockTime);
663     }
664
665     friend bool operator!=(const CTransaction& a, const CTransaction& b)
666     {
667         return !(a == b);
668     }
669
670
671     string ToString() const
672     {
673         string str;
674         str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%d, vout.size=%d, nLockTime=%d)\n",
675             GetHash().ToString().substr(0,10).c_str(),
676             nVersion,
677             vin.size(),
678             vout.size(),
679             nLockTime);
680         for (int i = 0; i < vin.size(); i++)
681             str += "    " + vin[i].ToString() + "\n";
682         for (int i = 0; i < vout.size(); i++)
683             str += "    " + vout[i].ToString() + "\n";
684         return str;
685     }
686
687     void print() const
688     {
689         printf("%s", ToString().c_str());
690     }
691
692
693     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
694     bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
695     bool ReadFromDisk(COutPoint prevout);
696     bool DisconnectInputs(CTxDB& txdb);
697     bool ConnectInputs(CTxDB& txdb, map<uint256, CTxIndex>& mapTestPool, CDiskTxPos posThisTx,
698                        CBlockIndex* pindexBlock, int64& nFees, bool fBlock, bool fMiner, int64 nMinFee=0);
699     bool ClientConnectInputs();
700     bool CheckTransaction() const;
701     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
702     bool AcceptToMemoryPool(bool fCheckInputs=true, bool* pfMissingInputs=NULL)
703     {
704         CTxDB txdb("r");
705         return AcceptToMemoryPool(txdb, fCheckInputs, pfMissingInputs);
706     }
707 protected:
708     bool AddToMemoryPoolUnchecked();
709 public:
710     bool RemoveFromMemoryPool();
711 };
712
713
714
715
716
717 //
718 // A transaction with a merkle branch linking it to the block chain
719 //
720 class CMerkleTx : public CTransaction
721 {
722 public:
723     uint256 hashBlock;
724     vector<uint256> vMerkleBranch;
725     int nIndex;
726
727     // memory only
728     mutable char fMerkleVerified;
729
730
731     CMerkleTx()
732     {
733         Init();
734     }
735
736     CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
737     {
738         Init();
739     }
740
741     void Init()
742     {
743         hashBlock = 0;
744         nIndex = -1;
745         fMerkleVerified = false;
746     }
747
748
749     IMPLEMENT_SERIALIZE
750     (
751         nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
752         nVersion = this->nVersion;
753         READWRITE(hashBlock);
754         READWRITE(vMerkleBranch);
755         READWRITE(nIndex);
756     )
757
758
759     int SetMerkleBranch(const CBlock* pblock=NULL);
760     int GetDepthInMainChain(int& nHeightRet) const;
761     int GetDepthInMainChain() const { int nHeight; return GetDepthInMainChain(nHeight); }
762     bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
763     int GetBlocksToMaturity() const;
764     bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
765     bool AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); }
766 };
767
768
769
770
771 //
772 // A transaction with a bunch of additional info that only the owner cares
773 // about.  It includes any unrecorded transactions needed to link it back
774 // to the block chain.
775 //
776 class CWalletTx : public CMerkleTx
777 {
778 public:
779     vector<CMerkleTx> vtxPrev;
780     map<string, string> mapValue;
781     vector<pair<string, string> > vOrderForm;
782     unsigned int fTimeReceivedIsTxTime;
783     unsigned int nTimeReceived;  // time received by this node
784     char fFromMe;
785     string strFromAccount;
786     vector<char> vfSpent;
787
788     // memory only
789     mutable char fDebitCached;
790     mutable char fCreditCached;
791     mutable char fAvailableCreditCached;
792     mutable char fChangeCached;
793     mutable int64 nDebitCached;
794     mutable int64 nCreditCached;
795     mutable int64 nAvailableCreditCached;
796     mutable int64 nChangeCached;
797
798     // memory only UI hints
799     mutable unsigned int nTimeDisplayed;
800     mutable int nLinesDisplayed;
801     mutable char fConfirmedDisplayed;
802
803
804     CWalletTx()
805     {
806         Init();
807     }
808
809     CWalletTx(const CMerkleTx& txIn) : CMerkleTx(txIn)
810     {
811         Init();
812     }
813
814     CWalletTx(const CTransaction& txIn) : CMerkleTx(txIn)
815     {
816         Init();
817     }
818
819     void Init()
820     {
821         vtxPrev.clear();
822         mapValue.clear();
823         vOrderForm.clear();
824         fTimeReceivedIsTxTime = false;
825         nTimeReceived = 0;
826         fFromMe = false;
827         strFromAccount.clear();
828         vfSpent.clear();
829         fDebitCached = false;
830         fCreditCached = false;
831         fAvailableCreditCached = false;
832         fChangeCached = false;
833         nDebitCached = 0;
834         nCreditCached = 0;
835         nAvailableCreditCached = 0;
836         nChangeCached = 0;
837         nTimeDisplayed = 0;
838         nLinesDisplayed = 0;
839         fConfirmedDisplayed = false;
840     }
841
842     IMPLEMENT_SERIALIZE
843     (
844         CWalletTx* pthis = const_cast<CWalletTx*>(this);
845         if (fRead)
846             pthis->Init();
847         char fSpent = false;
848
849         if (!fRead)
850         {
851             pthis->mapValue["fromaccount"] = pthis->strFromAccount;
852
853             string str;
854             foreach(char f, vfSpent)
855             {
856                 str += (f ? '1' : '0');
857                 if (f)
858                     fSpent = true;
859             }
860             pthis->mapValue["spent"] = str;
861         }
862
863         nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
864         READWRITE(vtxPrev);
865         READWRITE(mapValue);
866         READWRITE(vOrderForm);
867         READWRITE(fTimeReceivedIsTxTime);
868         READWRITE(nTimeReceived);
869         READWRITE(fFromMe);
870         READWRITE(fSpent);
871
872         if (fRead)
873         {
874             pthis->strFromAccount = pthis->mapValue["fromaccount"];
875
876             if (mapValue.count("spent"))
877                 foreach(char c, pthis->mapValue["spent"])
878                     pthis->vfSpent.push_back(c != '0');
879             else
880                 pthis->vfSpent.assign(vout.size(), fSpent);
881         }
882
883         pthis->mapValue.erase("fromaccount");
884         pthis->mapValue.erase("version");
885         pthis->mapValue.erase("spent");
886     )
887
888     // marks certain txout's as spent
889     // returns true if any update took place
890     bool UpdateSpent(const vector<char>& vfNewSpent)
891     {
892         bool fReturn = false;
893         for (int i=0; i < vfNewSpent.size(); i++)
894         {
895             if (i == vfSpent.size())
896                 break;
897
898             if (vfNewSpent[i] && !vfSpent[i])
899             {
900                 vfSpent[i] = true;
901                 fReturn = true;
902                 fAvailableCreditCached = false;
903             }
904         }
905         return fReturn;
906     }
907
908     void MarkDirty()
909     {
910         fCreditCached = false;
911         fAvailableCreditCached = false;
912         fDebitCached = false;
913         fChangeCached = false;
914     }
915
916     void MarkSpent(unsigned int nOut)
917     {
918         if (nOut >= vout.size())
919             throw runtime_error("CWalletTx::MarkSpent() : nOut out of range");
920         vfSpent.resize(vout.size());
921         if (!vfSpent[nOut])
922         {
923             vfSpent[nOut] = true;
924             fAvailableCreditCached = false;
925         }
926     }
927
928     bool IsSpent(unsigned int nOut) const
929     {
930         if (nOut >= vout.size())
931             throw runtime_error("CWalletTx::IsSpent() : nOut out of range");
932         if (nOut >= vfSpent.size())
933             return false;
934         return (!!vfSpent[nOut]);
935     }
936
937     int64 GetDebit() const
938     {
939         if (vin.empty())
940             return 0;
941         if (fDebitCached)
942             return nDebitCached;
943         nDebitCached = CTransaction::GetDebit();
944         fDebitCached = true;
945         return nDebitCached;
946     }
947
948     int64 GetCredit(bool fUseCache=true) const
949     {
950         // Must wait until coinbase is safely deep enough in the chain before valuing it
951         if (IsCoinBase() && GetBlocksToMaturity() > 0)
952             return 0;
953
954         // GetBalance can assume transactions in mapWallet won't change
955         if (fUseCache && fCreditCached)
956             return nCreditCached;
957         nCreditCached = CTransaction::GetCredit();
958         fCreditCached = true;
959         return nCreditCached;
960     }
961
962     int64 GetAvailableCredit(bool fUseCache=true) const
963     {
964         // Must wait until coinbase is safely deep enough in the chain before valuing it
965         if (IsCoinBase() && GetBlocksToMaturity() > 0)
966             return 0;
967
968         if (fUseCache && fAvailableCreditCached)
969             return nAvailableCreditCached;
970
971         int64 nCredit = 0;
972         for (int i = 0; i < vout.size(); i++)
973         {
974             if (!IsSpent(i))
975             {
976                 const CTxOut &txout = vout[i];
977                 nCredit += txout.GetCredit();
978                 if (!MoneyRange(nCredit))
979                     throw runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
980             }
981         }
982
983         nAvailableCreditCached = nCredit;
984         fAvailableCreditCached = true;
985         return nCredit;
986     }
987
988
989     int64 GetChange() const
990     {
991         if (fChangeCached)
992             return nChangeCached;
993         nChangeCached = CTransaction::GetChange();
994         fChangeCached = true;
995         return nChangeCached;
996     }
997
998     void GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<string /* address */, int64> >& listReceived,
999                     list<pair<string /* address */, int64> >& listSent, int64& nFee, string& strSentAccount) const;
1000
1001     void GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, 
1002                            int64& nSent, int64& nFee) const;
1003
1004     bool IsFromMe() const
1005     {
1006         return (GetDebit() > 0);
1007     }
1008
1009     bool IsConfirmed() const
1010     {
1011         // Quick answer in most cases
1012         if (!IsFinal())
1013             return false;
1014         if (GetDepthInMainChain() >= 1)
1015             return true;
1016         if (!IsFromMe()) // using wtx's cached debit
1017             return false;
1018
1019         // If no confirmations but it's from us, we can still
1020         // consider it confirmed if all dependencies are confirmed
1021         map<uint256, const CMerkleTx*> mapPrev;
1022         vector<const CMerkleTx*> vWorkQueue;
1023         vWorkQueue.reserve(vtxPrev.size()+1);
1024         vWorkQueue.push_back(this);
1025         for (int i = 0; i < vWorkQueue.size(); i++)
1026         {
1027             const CMerkleTx* ptx = vWorkQueue[i];
1028
1029             if (!ptx->IsFinal())
1030                 return false;
1031             if (ptx->GetDepthInMainChain() >= 1)
1032                 continue;
1033             if (!ptx->IsFromMe())
1034                 return false;
1035
1036             if (mapPrev.empty())
1037                 foreach(const CMerkleTx& tx, vtxPrev)
1038                     mapPrev[tx.GetHash()] = &tx;
1039
1040             foreach(const CTxIn& txin, ptx->vin)
1041             {
1042                 if (!mapPrev.count(txin.prevout.hash))
1043                     return false;
1044                 vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
1045             }
1046         }
1047         return true;
1048     }
1049
1050     bool WriteToDisk()
1051     {
1052         return CWalletDB().WriteTx(GetHash(), *this);
1053     }
1054
1055
1056     int64 GetTxTime() const;
1057     int GetRequestCount() const;
1058
1059     void AddSupportingTransactions(CTxDB& txdb);
1060
1061     bool AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs=true);
1062     bool AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); }
1063
1064     void RelayWalletTransaction(CTxDB& txdb);
1065     void RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); }
1066 };
1067
1068
1069
1070
1071 //
1072 // A txdb record that contains the disk location of a transaction and the
1073 // locations of transactions that spend its outputs.  vSpent is really only
1074 // used as a flag, but having the location is very helpful for debugging.
1075 //
1076 class CTxIndex
1077 {
1078 public:
1079     CDiskTxPos pos;
1080     vector<CDiskTxPos> vSpent;
1081
1082     CTxIndex()
1083     {
1084         SetNull();
1085     }
1086
1087     CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
1088     {
1089         pos = posIn;
1090         vSpent.resize(nOutputs);
1091     }
1092
1093     IMPLEMENT_SERIALIZE
1094     (
1095         if (!(nType & SER_GETHASH))
1096             READWRITE(nVersion);
1097         READWRITE(pos);
1098         READWRITE(vSpent);
1099     )
1100
1101     void SetNull()
1102     {
1103         pos.SetNull();
1104         vSpent.clear();
1105     }
1106
1107     bool IsNull()
1108     {
1109         return pos.IsNull();
1110     }
1111
1112     friend bool operator==(const CTxIndex& a, const CTxIndex& b)
1113     {
1114         return (a.pos    == b.pos &&
1115                 a.vSpent == b.vSpent);
1116     }
1117
1118     friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
1119     {
1120         return !(a == b);
1121     }
1122     int GetDepthInMainChain() const;
1123 };
1124
1125
1126
1127
1128
1129 //
1130 // Nodes collect new transactions into a block, hash them into a hash tree,
1131 // and scan through nonce values to make the block's hash satisfy proof-of-work
1132 // requirements.  When they solve the proof-of-work, they broadcast the block
1133 // to everyone and the block is added to the block chain.  The first transaction
1134 // in the block is a special one that creates a new coin owned by the creator
1135 // of the block.
1136 //
1137 // Blocks are appended to blk0001.dat files on disk.  Their location on disk
1138 // is indexed by CBlockIndex objects in memory.
1139 //
1140 class CBlock
1141 {
1142 public:
1143     // header
1144     int nVersion;
1145     uint256 hashPrevBlock;
1146     uint256 hashMerkleRoot;
1147     unsigned int nTime;
1148     unsigned int nBits;
1149     unsigned int nNonce;
1150
1151     // network and disk
1152     vector<CTransaction> vtx;
1153
1154     // memory only
1155     mutable vector<uint256> vMerkleTree;
1156
1157
1158     CBlock()
1159     {
1160         SetNull();
1161     }
1162
1163     IMPLEMENT_SERIALIZE
1164     (
1165         READWRITE(this->nVersion);
1166         nVersion = this->nVersion;
1167         READWRITE(hashPrevBlock);
1168         READWRITE(hashMerkleRoot);
1169         READWRITE(nTime);
1170         READWRITE(nBits);
1171         READWRITE(nNonce);
1172
1173         // ConnectBlock depends on vtx being last so it can calculate offset
1174         if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
1175             READWRITE(vtx);
1176         else if (fRead)
1177             const_cast<CBlock*>(this)->vtx.clear();
1178     )
1179
1180     void SetNull()
1181     {
1182         nVersion = 1;
1183         hashPrevBlock = 0;
1184         hashMerkleRoot = 0;
1185         nTime = 0;
1186         nBits = 0;
1187         nNonce = 0;
1188         vtx.clear();
1189         vMerkleTree.clear();
1190     }
1191
1192     bool IsNull() const
1193     {
1194         return (nBits == 0);
1195     }
1196
1197     uint256 GetHash() const
1198     {
1199         return Hash(BEGIN(nVersion), END(nNonce));
1200     }
1201
1202     int64 GetBlockTime() const
1203     {
1204         return (int64)nTime;
1205     }
1206
1207     int GetSigOpCount() const
1208     {
1209         int n = 0;
1210         foreach(const CTransaction& tx, vtx)
1211             n += tx.GetSigOpCount();
1212         return n;
1213     }
1214
1215
1216     uint256 BuildMerkleTree() const
1217     {
1218         vMerkleTree.clear();
1219         foreach(const CTransaction& tx, vtx)
1220             vMerkleTree.push_back(tx.GetHash());
1221         int j = 0;
1222         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1223         {
1224             for (int i = 0; i < nSize; i += 2)
1225             {
1226                 int i2 = min(i+1, nSize-1);
1227                 vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
1228                                            BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
1229             }
1230             j += nSize;
1231         }
1232         return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
1233     }
1234
1235     vector<uint256> GetMerkleBranch(int nIndex) const
1236     {
1237         if (vMerkleTree.empty())
1238             BuildMerkleTree();
1239         vector<uint256> vMerkleBranch;
1240         int j = 0;
1241         for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
1242         {
1243             int i = min(nIndex^1, nSize-1);
1244             vMerkleBranch.push_back(vMerkleTree[j+i]);
1245             nIndex >>= 1;
1246             j += nSize;
1247         }
1248         return vMerkleBranch;
1249     }
1250
1251     static uint256 CheckMerkleBranch(uint256 hash, const vector<uint256>& vMerkleBranch, int nIndex)
1252     {
1253         if (nIndex == -1)
1254             return 0;
1255         foreach(const uint256& otherside, vMerkleBranch)
1256         {
1257             if (nIndex & 1)
1258                 hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
1259             else
1260                 hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
1261             nIndex >>= 1;
1262         }
1263         return hash;
1264     }
1265
1266
1267     bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
1268     {
1269         // Open history file to append
1270         CAutoFile fileout = AppendBlockFile(nFileRet);
1271         if (!fileout)
1272             return error("CBlock::WriteToDisk() : AppendBlockFile failed");
1273
1274         // Write index header
1275         unsigned int nSize = fileout.GetSerializeSize(*this);
1276         fileout << FLATDATA(pchMessageStart) << nSize;
1277
1278         // Write block
1279         nBlockPosRet = ftell(fileout);
1280         if (nBlockPosRet == -1)
1281             return error("CBlock::WriteToDisk() : ftell failed");
1282         fileout << *this;
1283
1284         // Flush stdio buffers and commit to disk before returning
1285         fflush(fileout);
1286         if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
1287         {
1288 #ifdef __WXMSW__
1289             _commit(_fileno(fileout));
1290 #else
1291             fsync(fileno(fileout));
1292 #endif
1293         }
1294
1295         return true;
1296     }
1297
1298     bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
1299     {
1300         SetNull();
1301
1302         // Open history file to read
1303         CAutoFile filein = OpenBlockFile(nFile, nBlockPos, "rb");
1304         if (!filein)
1305             return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
1306         if (!fReadTransactions)
1307             filein.nType |= SER_BLOCKHEADERONLY;
1308
1309         // Read block
1310         filein >> *this;
1311
1312         // Check the header
1313         if (!CheckProofOfWork(GetHash(), nBits))
1314             return error("CBlock::ReadFromDisk() : errors in block header");
1315
1316         return true;
1317     }
1318
1319
1320
1321     void print() const
1322     {
1323         printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%d)\n",
1324             GetHash().ToString().substr(0,20).c_str(),
1325             nVersion,
1326             hashPrevBlock.ToString().substr(0,20).c_str(),
1327             hashMerkleRoot.ToString().substr(0,10).c_str(),
1328             nTime, nBits, nNonce,
1329             vtx.size());
1330         for (int i = 0; i < vtx.size(); i++)
1331         {
1332             printf("  ");
1333             vtx[i].print();
1334         }
1335         printf("  vMerkleTree: ");
1336         for (int i = 0; i < vMerkleTree.size(); i++)
1337             printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
1338         printf("\n");
1339     }
1340
1341
1342     bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1343     bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex);
1344     bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
1345     bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
1346     bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
1347     bool CheckBlock() const;
1348     bool AcceptBlock();
1349 };
1350
1351
1352
1353
1354
1355
1356 //
1357 // The block chain is a tree shaped structure starting with the
1358 // genesis block at the root, with each block potentially having multiple
1359 // candidates to be the next block.  pprev and pnext link a path through the
1360 // main/longest chain.  A blockindex may have multiple pprev pointing back
1361 // to it, but pnext will only point forward to the longest branch, or will
1362 // be null if the block is not part of the longest chain.
1363 //
1364 class CBlockIndex
1365 {
1366 public:
1367     const uint256* phashBlock;
1368     CBlockIndex* pprev;
1369     CBlockIndex* pnext;
1370     unsigned int nFile;
1371     unsigned int nBlockPos;
1372     int nHeight;
1373     CBigNum bnChainWork;
1374
1375     // block header
1376     int nVersion;
1377     uint256 hashMerkleRoot;
1378     unsigned int nTime;
1379     unsigned int nBits;
1380     unsigned int nNonce;
1381
1382
1383     CBlockIndex()
1384     {
1385         phashBlock = NULL;
1386         pprev = NULL;
1387         pnext = NULL;
1388         nFile = 0;
1389         nBlockPos = 0;
1390         nHeight = 0;
1391         bnChainWork = 0;
1392
1393         nVersion       = 0;
1394         hashMerkleRoot = 0;
1395         nTime          = 0;
1396         nBits          = 0;
1397         nNonce         = 0;
1398     }
1399
1400     CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
1401     {
1402         phashBlock = NULL;
1403         pprev = NULL;
1404         pnext = NULL;
1405         nFile = nFileIn;
1406         nBlockPos = nBlockPosIn;
1407         nHeight = 0;
1408         bnChainWork = 0;
1409
1410         nVersion       = block.nVersion;
1411         hashMerkleRoot = block.hashMerkleRoot;
1412         nTime          = block.nTime;
1413         nBits          = block.nBits;
1414         nNonce         = block.nNonce;
1415     }
1416
1417     CBlock GetBlockHeader() const
1418     {
1419         CBlock block;
1420         block.nVersion       = nVersion;
1421         if (pprev)
1422             block.hashPrevBlock = pprev->GetBlockHash();
1423         block.hashMerkleRoot = hashMerkleRoot;
1424         block.nTime          = nTime;
1425         block.nBits          = nBits;
1426         block.nNonce         = nNonce;
1427         return block;
1428     }
1429
1430     uint256 GetBlockHash() const
1431     {
1432         return *phashBlock;
1433     }
1434
1435     int64 GetBlockTime() const
1436     {
1437         return (int64)nTime;
1438     }
1439
1440     CBigNum GetBlockWork() const
1441     {
1442         CBigNum bnTarget;
1443         bnTarget.SetCompact(nBits);
1444         if (bnTarget <= 0)
1445             return 0;
1446         return (CBigNum(1)<<256) / (bnTarget+1);
1447     }
1448
1449     bool IsInMainChain() const
1450     {
1451         return (pnext || this == pindexBest);
1452     }
1453
1454     bool CheckIndex() const
1455     {
1456         return CheckProofOfWork(GetBlockHash(), nBits);
1457     }
1458
1459     bool EraseBlockFromDisk()
1460     {
1461         // Open history file
1462         CAutoFile fileout = OpenBlockFile(nFile, nBlockPos, "rb+");
1463         if (!fileout)
1464             return false;
1465
1466         // Overwrite with empty null block
1467         CBlock block;
1468         block.SetNull();
1469         fileout << block;
1470
1471         return true;
1472     }
1473
1474     enum { nMedianTimeSpan=11 };
1475
1476     int64 GetMedianTimePast() const
1477     {
1478         int64 pmedian[nMedianTimeSpan];
1479         int64* pbegin = &pmedian[nMedianTimeSpan];
1480         int64* pend = &pmedian[nMedianTimeSpan];
1481
1482         const CBlockIndex* pindex = this;
1483         for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
1484             *(--pbegin) = pindex->GetBlockTime();
1485
1486         sort(pbegin, pend);
1487         return pbegin[(pend - pbegin)/2];
1488     }
1489
1490     int64 GetMedianTime() const
1491     {
1492         const CBlockIndex* pindex = this;
1493         for (int i = 0; i < nMedianTimeSpan/2; i++)
1494         {
1495             if (!pindex->pnext)
1496                 return GetBlockTime();
1497             pindex = pindex->pnext;
1498         }
1499         return pindex->GetMedianTimePast();
1500     }
1501
1502
1503
1504     string ToString() const
1505     {
1506         return strprintf("CBlockIndex(nprev=%08x, pnext=%08x, nFile=%d, nBlockPos=%-6d nHeight=%d, merkle=%s, hashBlock=%s)",
1507             pprev, pnext, nFile, nBlockPos, nHeight,
1508             hashMerkleRoot.ToString().substr(0,10).c_str(),
1509             GetBlockHash().ToString().substr(0,20).c_str());
1510     }
1511
1512     void print() const
1513     {
1514         printf("%s\n", ToString().c_str());
1515     }
1516 };
1517
1518
1519
1520 //
1521 // Used to marshal pointers into hashes for db storage.
1522 //
1523 class CDiskBlockIndex : public CBlockIndex
1524 {
1525 public:
1526     uint256 hashPrev;
1527     uint256 hashNext;
1528
1529     CDiskBlockIndex()
1530     {
1531         hashPrev = 0;
1532         hashNext = 0;
1533     }
1534
1535     explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
1536     {
1537         hashPrev = (pprev ? pprev->GetBlockHash() : 0);
1538         hashNext = (pnext ? pnext->GetBlockHash() : 0);
1539     }
1540
1541     IMPLEMENT_SERIALIZE
1542     (
1543         if (!(nType & SER_GETHASH))
1544             READWRITE(nVersion);
1545
1546         READWRITE(hashNext);
1547         READWRITE(nFile);
1548         READWRITE(nBlockPos);
1549         READWRITE(nHeight);
1550
1551         // block header
1552         READWRITE(this->nVersion);
1553         READWRITE(hashPrev);
1554         READWRITE(hashMerkleRoot);
1555         READWRITE(nTime);
1556         READWRITE(nBits);
1557         READWRITE(nNonce);
1558     )
1559
1560     uint256 GetBlockHash() const
1561     {
1562         CBlock block;
1563         block.nVersion        = nVersion;
1564         block.hashPrevBlock   = hashPrev;
1565         block.hashMerkleRoot  = hashMerkleRoot;
1566         block.nTime           = nTime;
1567         block.nBits           = nBits;
1568         block.nNonce          = nNonce;
1569         return block.GetHash();
1570     }
1571
1572
1573     string ToString() const
1574     {
1575         string str = "CDiskBlockIndex(";
1576         str += CBlockIndex::ToString();
1577         str += strprintf("\n                hashBlock=%s, hashPrev=%s, hashNext=%s)",
1578             GetBlockHash().ToString().c_str(),
1579             hashPrev.ToString().substr(0,20).c_str(),
1580             hashNext.ToString().substr(0,20).c_str());
1581         return str;
1582     }
1583
1584     void print() const
1585     {
1586         printf("%s\n", ToString().c_str());
1587     }
1588 };
1589
1590
1591
1592
1593
1594
1595
1596
1597 //
1598 // Describes a place in the block chain to another node such that if the
1599 // other node doesn't have the same branch, it can find a recent common trunk.
1600 // The further back it is, the further before the fork it may be.
1601 //
1602 class CBlockLocator
1603 {
1604 protected:
1605     vector<uint256> vHave;
1606 public:
1607
1608     CBlockLocator()
1609     {
1610     }
1611
1612     explicit CBlockLocator(const CBlockIndex* pindex)
1613     {
1614         Set(pindex);
1615     }
1616
1617     explicit CBlockLocator(uint256 hashBlock)
1618     {
1619         map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
1620         if (mi != mapBlockIndex.end())
1621             Set((*mi).second);
1622     }
1623
1624     IMPLEMENT_SERIALIZE
1625     (
1626         if (!(nType & SER_GETHASH))
1627             READWRITE(nVersion);
1628         READWRITE(vHave);
1629     )
1630
1631     void SetNull()
1632     {
1633         vHave.clear();
1634     }
1635
1636     bool IsNull()
1637     {
1638         return vHave.empty();
1639     }
1640
1641     void Set(const CBlockIndex* pindex)
1642     {
1643         vHave.clear();
1644         int nStep = 1;
1645         while (pindex)
1646         {
1647             vHave.push_back(pindex->GetBlockHash());
1648
1649             // Exponentially larger steps back
1650             for (int i = 0; pindex && i < nStep; i++)
1651                 pindex = pindex->pprev;
1652             if (vHave.size() > 10)
1653                 nStep *= 2;
1654         }
1655         vHave.push_back(hashGenesisBlock);
1656     }
1657
1658     int GetDistanceBack()
1659     {
1660         // Retrace how far back it was in the sender's branch
1661         int nDistance = 0;
1662         int nStep = 1;
1663         foreach(const uint256& hash, vHave)
1664         {
1665             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1666             if (mi != mapBlockIndex.end())
1667             {
1668                 CBlockIndex* pindex = (*mi).second;
1669                 if (pindex->IsInMainChain())
1670                     return nDistance;
1671             }
1672             nDistance += nStep;
1673             if (nDistance > 10)
1674                 nStep *= 2;
1675         }
1676         return nDistance;
1677     }
1678
1679     CBlockIndex* GetBlockIndex()
1680     {
1681         // Find the first block the caller has in the main chain
1682         foreach(const uint256& hash, vHave)
1683         {
1684             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1685             if (mi != mapBlockIndex.end())
1686             {
1687                 CBlockIndex* pindex = (*mi).second;
1688                 if (pindex->IsInMainChain())
1689                     return pindex;
1690             }
1691         }
1692         return pindexGenesisBlock;
1693     }
1694
1695     uint256 GetBlockHash()
1696     {
1697         // Find the first block the caller has in the main chain
1698         foreach(const uint256& hash, vHave)
1699         {
1700             map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
1701             if (mi != mapBlockIndex.end())
1702             {
1703                 CBlockIndex* pindex = (*mi).second;
1704                 if (pindex->IsInMainChain())
1705                     return hash;
1706             }
1707         }
1708         return hashGenesisBlock;
1709     }
1710
1711     int GetHeight()
1712     {
1713         CBlockIndex* pindex = GetBlockIndex();
1714         if (!pindex)
1715             return 0;
1716         return pindex->nHeight;
1717     }
1718 };
1719
1720
1721
1722
1723
1724
1725 //
1726 // Private key that includes an expiration date in case it never gets used.
1727 //
1728 class CWalletKey
1729 {
1730 public:
1731     CPrivKey vchPrivKey;
1732     int64 nTimeCreated;
1733     int64 nTimeExpires;
1734     string strComment;
1735     //// todo: add something to note what created it (user, getnewaddress, change)
1736     ////   maybe should have a map<string, string> property map
1737
1738     CWalletKey(int64 nExpires=0)
1739     {
1740         nTimeCreated = (nExpires ? GetTime() : 0);
1741         nTimeExpires = nExpires;
1742     }
1743
1744     IMPLEMENT_SERIALIZE
1745     (
1746         if (!(nType & SER_GETHASH))
1747             READWRITE(nVersion);
1748         READWRITE(vchPrivKey);
1749         READWRITE(nTimeCreated);
1750         READWRITE(nTimeExpires);
1751         READWRITE(strComment);
1752     )
1753 };
1754
1755
1756
1757
1758
1759
1760 //
1761 // Account information.
1762 // Stored in wallet with key "acc"+string account name
1763 //
1764 class CAccount
1765 {
1766 public:
1767     vector<unsigned char> vchPubKey;
1768
1769     CAccount()
1770     {
1771         SetNull();
1772     }
1773
1774     void SetNull()
1775     {
1776         vchPubKey.clear();
1777     }
1778
1779     IMPLEMENT_SERIALIZE
1780     (
1781         if (!(nType & SER_GETHASH))
1782             READWRITE(nVersion);
1783         READWRITE(vchPubKey);
1784     )
1785 };
1786
1787
1788
1789 //
1790 // Internal transfers.
1791 // Database key is acentry<account><counter>
1792 //
1793 class CAccountingEntry
1794 {
1795 public:
1796     string strAccount;
1797     int64 nCreditDebit;
1798     int64 nTime;
1799     string strOtherAccount;
1800     string strComment;
1801
1802     CAccountingEntry()
1803     {
1804         SetNull();
1805     }
1806
1807     void SetNull()
1808     {
1809         nCreditDebit = 0;
1810         nTime = 0;
1811         strAccount.clear();
1812         strOtherAccount.clear();
1813         strComment.clear();
1814     }
1815
1816     IMPLEMENT_SERIALIZE
1817     (
1818         if (!(nType & SER_GETHASH))
1819             READWRITE(nVersion);
1820         // Note: strAccount is serialized as part of the key, not here.
1821         READWRITE(nCreditDebit);
1822         READWRITE(nTime);
1823         READWRITE(strOtherAccount);
1824         READWRITE(strComment);
1825     )
1826 };
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836 //
1837 // Alerts are for notifying old versions if they become too obsolete and
1838 // need to upgrade.  The message is displayed in the status bar.
1839 // Alert messages are broadcast as a vector of signed data.  Unserializing may
1840 // not read the entire buffer if the alert is for a newer version, but older
1841 // versions can still relay the original data.
1842 //
1843 class CUnsignedAlert
1844 {
1845 public:
1846     int nVersion;
1847     int64 nRelayUntil;      // when newer nodes stop relaying to newer nodes
1848     int64 nExpiration;
1849     int nID;
1850     int nCancel;
1851     set<int> setCancel;
1852     int nMinVer;            // lowest version inclusive
1853     int nMaxVer;            // highest version inclusive
1854     set<string> setSubVer;  // empty matches all
1855     int nPriority;
1856
1857     // Actions
1858     string strComment;
1859     string strStatusBar;
1860     string strReserved;
1861
1862     IMPLEMENT_SERIALIZE
1863     (
1864         READWRITE(this->nVersion);
1865         nVersion = this->nVersion;
1866         READWRITE(nRelayUntil);
1867         READWRITE(nExpiration);
1868         READWRITE(nID);
1869         READWRITE(nCancel);
1870         READWRITE(setCancel);
1871         READWRITE(nMinVer);
1872         READWRITE(nMaxVer);
1873         READWRITE(setSubVer);
1874         READWRITE(nPriority);
1875
1876         READWRITE(strComment);
1877         READWRITE(strStatusBar);
1878         READWRITE(strReserved);
1879     )
1880
1881     void SetNull()
1882     {
1883         nVersion = 1;
1884         nRelayUntil = 0;
1885         nExpiration = 0;
1886         nID = 0;
1887         nCancel = 0;
1888         setCancel.clear();
1889         nMinVer = 0;
1890         nMaxVer = 0;
1891         setSubVer.clear();
1892         nPriority = 0;
1893
1894         strComment.clear();
1895         strStatusBar.clear();
1896         strReserved.clear();
1897     }
1898
1899     string ToString() const
1900     {
1901         string strSetCancel;
1902         foreach(int n, setCancel)
1903             strSetCancel += strprintf("%d ", n);
1904         string strSetSubVer;
1905         foreach(string str, setSubVer)
1906             strSetSubVer += "\"" + str + "\" ";
1907         return strprintf(
1908                 "CAlert(\n"
1909                 "    nVersion     = %d\n"
1910                 "    nRelayUntil  = %"PRI64d"\n"
1911                 "    nExpiration  = %"PRI64d"\n"
1912                 "    nID          = %d\n"
1913                 "    nCancel      = %d\n"
1914                 "    setCancel    = %s\n"
1915                 "    nMinVer      = %d\n"
1916                 "    nMaxVer      = %d\n"
1917                 "    setSubVer    = %s\n"
1918                 "    nPriority    = %d\n"
1919                 "    strComment   = \"%s\"\n"
1920                 "    strStatusBar = \"%s\"\n"
1921                 ")\n",
1922             nVersion,
1923             nRelayUntil,
1924             nExpiration,
1925             nID,
1926             nCancel,
1927             strSetCancel.c_str(),
1928             nMinVer,
1929             nMaxVer,
1930             strSetSubVer.c_str(),
1931             nPriority,
1932             strComment.c_str(),
1933             strStatusBar.c_str());
1934     }
1935
1936     void print() const
1937     {
1938         printf("%s", ToString().c_str());
1939     }
1940 };
1941
1942 class CAlert : public CUnsignedAlert
1943 {
1944 public:
1945     vector<unsigned char> vchMsg;
1946     vector<unsigned char> vchSig;
1947
1948     CAlert()
1949     {
1950         SetNull();
1951     }
1952
1953     IMPLEMENT_SERIALIZE
1954     (
1955         READWRITE(vchMsg);
1956         READWRITE(vchSig);
1957     )
1958
1959     void SetNull()
1960     {
1961         CUnsignedAlert::SetNull();
1962         vchMsg.clear();
1963         vchSig.clear();
1964     }
1965
1966     bool IsNull() const
1967     {
1968         return (nExpiration == 0);
1969     }
1970
1971     uint256 GetHash() const
1972     {
1973         return SerializeHash(*this);
1974     }
1975
1976     bool IsInEffect() const
1977     {
1978         return (GetAdjustedTime() < nExpiration);
1979     }
1980
1981     bool Cancels(const CAlert& alert) const
1982     {
1983         if (!IsInEffect())
1984             return false; // this was a no-op before 31403
1985         return (alert.nID <= nCancel || setCancel.count(alert.nID));
1986     }
1987
1988     bool AppliesTo(int nVersion, string strSubVerIn) const
1989     {
1990         return (IsInEffect() &&
1991                 nMinVer <= nVersion && nVersion <= nMaxVer &&
1992                 (setSubVer.empty() || setSubVer.count(strSubVerIn)));
1993     }
1994
1995     bool AppliesToMe() const
1996     {
1997         return AppliesTo(VERSION, ::pszSubVer);
1998     }
1999
2000     bool RelayTo(CNode* pnode) const
2001     {
2002         if (!IsInEffect())
2003             return false;
2004         // returns true if wasn't already contained in the set
2005         if (pnode->setKnown.insert(GetHash()).second)
2006         {
2007             if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
2008                 AppliesToMe() ||
2009                 GetAdjustedTime() < nRelayUntil)
2010             {
2011                 pnode->PushMessage("alert", *this);
2012                 return true;
2013             }
2014         }
2015         return false;
2016     }
2017
2018     bool CheckSignature()
2019     {
2020         CKey key;
2021         if (!key.SetPubKey(ParseHex("04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284")))
2022             return error("CAlert::CheckSignature() : SetPubKey failed");
2023         if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
2024             return error("CAlert::CheckSignature() : verify signature failed");
2025
2026         // Now unserialize the data
2027         CDataStream sMsg(vchMsg);
2028         sMsg >> *(CUnsignedAlert*)this;
2029         return true;
2030     }
2031
2032     bool ProcessAlert();
2033 };
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044 extern map<uint256, CTransaction> mapTransactions;
2045 extern map<uint256, CWalletTx> mapWallet;
2046 extern vector<uint256> vWalletUpdated;
2047 extern CCriticalSection cs_mapWallet;
2048 extern map<vector<unsigned char>, CPrivKey> mapKeys;
2049 extern map<uint160, vector<unsigned char> > mapPubKeys;
2050 extern CCriticalSection cs_mapKeys;
2051 extern CKey keyUser;