-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.cpp
executable file
·2261 lines (1816 loc) · 64.6 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2008 Satoshi Nakamoto
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "headers.h"
#include "sha.h"
//
// Global state
//
map<uint256, CTransaction> mapTransactions;
CCriticalSection cs_mapTransactions;
unsigned int nTransactionsUpdated = 0;
/// mapNextTx is only used anymore to track disk tx outpoints used by memory txes
map<COutPoint, CInPoint> mapNextTx;
map<uint256, CBlockIndex*> mapBlockIndex;
const uint256 hashGenesisBlock("0x000006b15d1327d67e971d1de9116bd60a3a01556c91b6ebaa416ebc0cfaa646");
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
uint256 hashTimeChainBest = 0;
CBlockIndex* pindexBest = NULL;
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
map<uint256, CWalletTx> mapWallet;
vector<pair<uint256, bool> > vWalletUpdated;
CCriticalSection cs_mapWallet;
map<vector<unsigned char>, CPrivKey> mapKeys;
map<uint160, vector<unsigned char> > mapPubKeys;
CCriticalSection cs_mapKeys;
CKey keyUser;
int fGenerateBitcoins;
//////////////////////////////////////////////////////////////////////////////
//
// mapKeys
//
bool AddKey(const CKey& key)
{
CRITICAL_BLOCK(cs_mapKeys)
{
mapKeys[key.GetPubKey()] = key.GetPrivKey();
mapPubKeys[Hash160(key.GetPubKey())] = key.GetPubKey();
}
return CWalletDB().WriteKey(key.GetPubKey(), key.GetPrivKey());
}
vector<unsigned char> GenerateNewKey()
{
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw runtime_error("GenerateNewKey() : AddKey failed\n");
return key.GetPubKey();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapWallet
//
bool AddToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
CRITICAL_BLOCK(cs_mapWallet)
{
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
bool fInsertedNew = ret.second;
//// debug print
printf("AddToWallet %s %d\n", wtxIn.GetHash().ToString().c_str(), fInsertedNew);
if (!fInsertedNew)
{
// Merge
bool fUpdated = false;
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
if (wtxIn.fSpent && wtxIn.fSpent != wtx.fSpent)
{
wtx.fSpent = wtxIn.fSpent;
fUpdated = true;
}
if (!fUpdated)
return true;
}
// Write to disk
if (!wtx.WriteToDisk())
return false;
// Notify UI
vWalletUpdated.push_back(make_pair(hash, fInsertedNew));
}
// Refresh UI
MainFrameRepaint();
return true;
}
bool AddToWalletIfMine(const CTransaction& tx, const CBlock* pblock)
{
if (tx.IsMine())
{
CWalletTx wtx(tx);
if (pblock)
{
wtx.hashBlock = pblock->GetHash();
wtx.nTime = pblock->nTime;
}
else
{
wtx.nTime = GetAdjustedTime();
}
return AddToWallet(wtx);
}
return true;
}
void ReacceptWalletTransactions()
{
// Reaccept any txes of ours that aren't already in a block
CRITICAL_BLOCK(cs_mapWallet)
{
CTxDB txdb("r");
foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{
CWalletTx& wtx = item.second;
if (!txdb.ContainsTx(wtx.GetHash()))
wtx.AcceptWalletTransaction(txdb, false);
}
}
}
void RelayWalletTransactions()
{
static int64 nLastTime;
if (GetTime() - nLastTime < 15 * 60)
return;
nLastTime = GetTime();
// Rebroadcast any of our txes that aren't in a block yet
CRITICAL_BLOCK(cs_mapWallet)
{
CTxDB txdb("r");
foreach(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
item.second.RelayWalletTransaction(txdb);
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction
//
bool CTxIn::IsMine() const
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (prevout.n < prev.vout.size())
if (prev.vout[prevout.n].IsMine())
return true;
}
return false;
}
int64 CTxIn::GetDebit() const
{
map<uint256, CWalletTx>::iterator mi = mapWallet.find(prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (prevout.n < prev.vout.size())
if (prev.vout[prevout.n].IsMine())
return prev.vout[prevout.n].nValue;
}
return 0;
}
int CMerkleTx::SetMerkleBranch()
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
// Load the block this tx is in
CDiskTxPos pos;
if (!CTxDB("r").ReadTxPos(GetHash(), pos))
return 0;
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, true))
return 0;
// Update the tx's hashBlock
hashBlock = block.GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < block.vtx.size(); nIndex++)
if (block.vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == block.vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = block.GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
{
vtxPrev.clear();
const int COPY_DEPTH = 3;
if (SetMerkleBranch() < COPY_DEPTH)
{
vector<uint256> vWorkQueue;
foreach(const CTxIn& txin, vin)
vWorkQueue.push_back(txin.prevout.hash);
map<uint256, const CMerkleTx*> mapWalletPrev;
set<uint256> setAlreadyDone;
for (int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hash = vWorkQueue[i];
if (setAlreadyDone.count(hash))
continue;
setAlreadyDone.insert(hash);
CMerkleTx tx;
if (mapWallet.count(hash))
{
tx = mapWallet[hash];
foreach(const CMerkleTx& txWalletPrev, mapWallet[hash].vtxPrev)
mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
}
else if (mapWalletPrev.count(hash))
{
tx = *mapWalletPrev[hash];
}
else if (!fClient && txdb.ReadDiskTx(hash, tx))
{
;
}
else
{
printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
continue;
}
int nDepth = tx.SetMerkleBranch();
vtxPrev.push_back(tx);
if (nDepth < COPY_DEPTH)
foreach(const CTxIn& txin, tx.vin)
vWorkQueue.push_back(txin.prevout.hash);
}
}
reverse(vtxPrev.begin(), vtxPrev.end());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb, map<uint256, CTransaction>& mapTestPool, bool fTest)
{
// Relinquish previous transactions' posNext pointers
if (!IsCoinBase())
{
foreach(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
CAutoFile fileout = NULL;
CTransaction txPrevBuf;
CTransaction& txPrev = (fTest ? mapTestPool[prevout.hash] : txPrevBuf);
if (txPrev.IsNull())
{
// Get prev tx from disk
// Version -1 tells unserialize to set version so we write back same version
fileout.SetVersion(-1);
if (!txdb.ReadDiskTx(prevout.hash, txPrev, &fileout))
return false;
}
if (prevout.n >= txPrev.vout.size())
return false;
// Relinquish posNext pointer
txPrev.vout[prevout.n].posNext.SetNull();
// Write back
if (!fTest)
fileout << txPrev;
}
}
if (fTest)
{
// Put a blocked-off copy of this transaction in the test pool
CTransaction& txPool = mapTestPool[GetHash()];
txPool = *this;
foreach(CTxOut& txout, txPool.vout)
txout.posNext = CDiskTxPos(1, 1, 1);
}
else
{
// Remove transaction from index
if (!txdb.EraseTxPos(*this))
return false;
// Resurect single transaction objects
if (!IsCoinBase())
AcceptTransaction(txdb, false);
}
return true;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, map<uint256, CTransaction>& mapTestPool, CDiskTxPos posThisTx, int nHeight,
bool fTest, bool fMemoryTx, bool fIgnoreDiskConflicts, int64& nFees)
{
// Take over previous transactions' posNext pointers
if (!IsCoinBase())
{
int64 nValueIn = 0;
for (int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
CAutoFile fileout = NULL;
CTransaction txPrevBuf;
CTransaction& txPrev = (fTest ? mapTestPool[prevout.hash] : txPrevBuf);
if (txPrev.IsNull() && fTest && fMemoryTx && mapTransactions.count(prevout.hash))
{
// Get prev tx from single transactions in memory
txPrev = mapTransactions[prevout.hash];
}
else if (txPrev.IsNull())
{
// Get prev tx from disk
// Version -1 tells unserialize to set version so we write back same version
fileout.SetVersion(-1);
if (!txdb.ReadDiskTx(prevout.hash, txPrev, &fileout))
return error("ConnectInputs() : prev tx not found");
// If tx will only be connected in a reorg,
// then these outpoints will be checked at that time
if (fIgnoreDiskConflicts)
foreach(CTxOut& txout, txPrev.vout)
txout.posNext.SetNull();
}
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i))
return error("ConnectInputs() : VerifySignature failed");
// Check for conflicts
if (!txPrev.vout[prevout.n].posNext.IsNull())
return error("ConnectInputs() : prev tx already used");
// Flag outpoints as used
txPrev.vout[prevout.n].posNext = posThisTx;
// Write back
if (!fTest)
fileout << txPrev;
nValueIn += txPrev.vout[prevout.n].nValue;
}
// Tally transaction fees
int64 nTransactionFee = nValueIn - GetValueOut();
if (nTransactionFee < 0)
return false;
nFees += nTransactionFee;
}
if (fTest)
{
// Add transaction to test pool
mapTestPool[GetHash()] = *this;
}
else
{
// Add transaction to disk index
if (!txdb.WriteTxPos(*this, posThisTx, nHeight))
return false;
// Delete redundant single transaction objects
CRITICAL_BLOCK(cs_mapTransactions)
{
foreach(const CTxIn& txin, vin)
mapNextTx.erase(txin.prevout);
mapTransactions.erase(GetHash());
}
}
return true;
}
bool CTransaction::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
{
// Coinbase is only valid in a block, not as a loose transaction
if (IsCoinBase())
return error("AcceptTransaction() : coinbase as individual tx");
if (!CheckTransaction())
return error("AcceptTransaction() : CheckTransaction failed");
uint256 hash = GetHash();
if (mapTransactions.count(hash))
return false;
// Check for conflicts with in-memory transactions
// and allow replacing with a newer version of the same transaction
CTransaction* ptxOld = NULL;
for (int i = 0; i < vin.size(); i++)
{
COutPoint outpoint = vin[i].prevout;
if (mapNextTx.count(outpoint))
{
if (ptxOld == NULL)
{
ptxOld = mapNextTx[outpoint].ptx;
if (!IsUpdate(*ptxOld))
return false;
}
else if (ptxOld != mapNextTx[outpoint].ptx)
return false;
}
}
// Check against previous transactions
map<uint256, CTransaction> mapTestPool;
int64 nFees = 0;
if (fCheckInputs)
if (!TestConnectInputs(txdb, mapTestPool, true, false, nFees))
return error("AcceptTransaction() : TestConnectInputs failed");
// Store transaction in memory
CRITICAL_BLOCK(cs_mapTransactions)
{
if (ptxOld)
{
printf("mapTransaction.erase(%s) replacing with new version\n", ptxOld->GetHash().ToString().c_str());
mapTransactions.erase(ptxOld->GetHash());
}
//printf("mapTransaction.insert(%s)\n ", hash.ToString().c_str());
//print();
mapTransactions[hash] = *this;
for (int i = 0; i < vin.size(); i++)
mapNextTx[vin[i].prevout] = CInPoint(&mapTransactions[hash], i);
}
// If updated, erase old tx from wallet
if (ptxOld)
CRITICAL_BLOCK(cs_mapWallet)
mapWallet.erase(ptxOld->GetHash());
nTransactionsUpdated++;
return true;
}
int CMerkleTx::IsInMainChain() const
{
if (hashBlock == 0)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Get merkle root
CBlock block;
if (!block.ReadFromDisk(pindex, false))
return 0;
// Make sure the merkle branch connects to this block
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != block.hashMerkleRoot)
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CMerkleTx::AcceptTransaction(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptTransaction(txdb, false);
}
else
{
return CTransaction::AcceptTransaction(txdb, fCheckInputs);
}
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
foreach(CMerkleTx& tx, vtxPrev)
{
uint256 hash = tx.GetHash();
if (!mapTransactions.count(hash) && !txdb.ContainsTx(hash))
tx.AcceptTransaction(txdb, fCheckInputs);
}
return AcceptTransaction(txdb, fCheckInputs);
}
void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
{
foreach(CMerkleTx& tx, vtxPrev)
{
uint256 hash = tx.GetHash();
if (!txdb.ContainsTx(hash))
RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx);
}
uint256 hash = GetHash();
if (!txdb.ContainsTx(hash))
RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this);
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool CBlock::ReadFromDisk(const CBlockIndex* pblockindex, bool fReadTransactions)
{
return ReadFromDisk(pblockindex->nFile, pblockindex->nBlockPos, fReadTransactions);
}
int64 GetBlockValue(int64 nFees)
{
int64 nSubsidy = 10000 * CENT;
for (int i = 100000; i <= nBestHeight; i += 100000)
nSubsidy /= 2;
return nSubsidy + nFees;
}
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast)
{
const unsigned int nTargetTimespan = 30 * 24 * 60 * 60;
const unsigned int nTargetSpacing = 15 * 60;
const unsigned int nIntervals = nTargetTimespan / nTargetSpacing;
// Cache
static const CBlockIndex* pindexLastCache;
static unsigned int nBitsCache;
static CCriticalSection cs_cache;
CRITICAL_BLOCK(cs_cache)
if (pindexLast && pindexLast == pindexLastCache)
return nBitsCache;
// Go back 30 days
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < nIntervals; i++)
pindexFirst = pindexFirst->pprev;
if (pindexFirst == NULL)
return MINPROOFOFWORK;
// Load first and last block
CBlock blockFirst;
if (!blockFirst.ReadFromDisk(pindexFirst, false))
throw runtime_error("GetNextWorkRequired() : blockFirst.ReadFromDisk failed\n");
CBlock blockLast;
if (!blockLast.ReadFromDisk(pindexLast, false))
throw runtime_error("GetNextWorkRequired() : blockLast.ReadFromDisk failed\n");
// Limit one change per timespan
unsigned int nBits = blockLast.nBits;
if (blockFirst.nBits == blockLast.nBits)
{
unsigned int nTimespan = blockLast.nTime - blockFirst.nTime;
if (nTimespan > nTargetTimespan * 2 && nBits >= MINPROOFOFWORK)
nBits--;
else if (nTimespan < nTargetTimespan / 2)
nBits++;
}
CRITICAL_BLOCK(cs_cache)
{
pindexLastCache = pindexLast;
nBitsCache = nBits;
}
return nBits;
}
uint256 GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->hashPrevBlock;
}
bool CBlock::TestDisconnectBlock(CTxDB& txdb, map<uint256, CTransaction>& mapTestPool)
{
foreach(CTransaction& tx, vtx)
if (!tx.TestDisconnectInputs(txdb, mapTestPool))
return false;
return true;
}
bool CBlock::TestConnectBlock(CTxDB& txdb, map<uint256, CTransaction>& mapTestPool)
{
int64 nFees = 0;
foreach(CTransaction& tx, vtx)
if (!tx.TestConnectInputs(txdb, mapTestPool, false, false, nFees))
return false;
if (vtx[0].GetValueOut() != GetBlockValue(nFees))
return false;
return true;
}
bool CBlock::DisconnectBlock()
{
CTxDB txdb;
foreach(CTransaction& tx, vtx)
if (!tx.DisconnectInputs(txdb))
return false;
return true;
}
bool CBlock::ConnectBlock(unsigned int nFile, unsigned int nBlockPos, int nHeight)
{
//// issue here: it doesn't know the version
unsigned int nTxPos = nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK) - 1 + GetSizeOfCompactSize(vtx.size());
CTxDB txdb;
foreach(CTransaction& tx, vtx)
{
CDiskTxPos posThisTx(nFile, nBlockPos, nTxPos);
nTxPos += ::GetSerializeSize(tx, SER_DISK);
if (!tx.ConnectInputs(txdb, posThisTx, nHeight))
return false;
}
txdb.Close();
// Watch for transactions paying to me
foreach(CTransaction& tx, vtx)
AddToWalletIfMine(tx, this);
return true;
}
bool Reorganize(CBlockIndex* pindexNew, bool fWriteDisk)
{
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
if (!(pfork = pfork->pprev))
return false;
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return false;
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
// Pretest the reorg
if (fWriteDisk)
{
CTxDB txdb("r");
map<uint256, CTransaction> mapTestPool;
foreach(CBlockIndex* pindex, vDisconnect)
if (!pindex->TestDisconnectBlock(txdb, mapTestPool))
return false;
bool fValid = true;
foreach(CBlockIndex* pindex, vConnect)
{
fValid = fValid && pindex->TestConnectBlock(txdb, mapTestPool);
if (!fValid)
{
// Invalid block, delete the rest of this branch
CBlock block;
block.ReadFromDisk(pindex, false);
pindex->EraseBlockFromDisk();
mapBlockIndex.erase(block.GetHash());
delete pindex;
}
}
if (!fValid)
return false;
}
// Disconnect shorter branch
foreach(CBlockIndex* pindex, vDisconnect)
{
if (fWriteDisk && !pindex->DisconnectBlock())
return false;
if (pindex->pprev)
pindex->pprev->pnext = NULL;
}
// Connect longer branch
foreach(CBlockIndex* pindex, vConnect)
{
if (fWriteDisk && !pindex->ConnectBlock())
return false;
if (pindex->pprev)
pindex->pprev->pnext = pindex;
}
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, bool fWriteDisk)
{
uint256 hash = GetHash();
// Add to block index
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos);
if (!pindexNew)
return false;
mapBlockIndex[hash] = pindexNew;
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi != mapBlockIndex.end())
{
pindexNew->pprev = (*mi).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// New best
if (pindexNew->nHeight > nBestHeight)
{
if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
{
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashTimeChainBest)
{
// Adding to current best branch
if (fWriteDisk)
if (!pindexNew->ConnectBlock())
return false;
pindexNew->pprev->pnext = pindexNew;
}
else
{
// New best branch
if (!Reorganize(pindexNew, fWriteDisk))
return false;
}
// New best link
nBestHeight = pindexNew->nHeight;
hashTimeChainBest = hash;
pindexBest = pindexNew;
nTransactionsUpdated++;
// Relay wallet transactions that haven't gotten in yet
if (fWriteDisk && nTime > GetAdjustedTime() - 30 * 60)
RelayWalletTransactions();
}
MainFrameRepaint();
return true;
}
template<typename Stream>
bool ScanMessageStart(Stream& s)
{
// Scan ahead to the next pchMessageStart, which should normally be immediately
// at the file pointer. Leaves file pointer at end of pchMessageStart.
s.clear(0);
short prevmask = s.exceptions(0);
const char* p = BEGIN(pchMessageStart);
try
{
loop
{
char c;
s.read(&c, 1);
if (s.fail())
{
s.clear(0);
s.exceptions(prevmask);
return false;
}
if (*p != c)
p = BEGIN(pchMessageStart);
if (*p == c)
{
if (++p == END(pchMessageStart))
{
s.clear(0);
s.exceptions(prevmask);
return true;
}
}
}
}
catch (...)
{
s.clear(0);
s.exceptions(prevmask);
return false;
}
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if (nFile == -1)
return NULL;
FILE* file = fopen(strprintf("blk%04d.dat", nFile).c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
loop
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < 0x7F000000 - MAX_SIZE)
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
//
// Load from disk
//
for (nCurrentBlockFile = 1;; nCurrentBlockFile++)
{
CAutoFile filein = OpenBlockFile(nCurrentBlockFile, 0, "rb");
if (filein == NULL)