forked from bcosorg/bcos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlockChain.cpp
1873 lines (1629 loc) · 59.3 KB
/
BlockChain.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
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file BlockChain.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "BlockChain.h"
#if ETH_PROFILING_GPERF
#include <gperftools/profiler.h>
#endif
#include <boost/timer.hpp>
#include <boost/filesystem.hpp>
#include <json_spirit/JsonSpiritHeaders.h>
#include <libdevcore/Common.h>
#include <libdevcore/Assertions.h>
#include <libdevcore/RLP.h>
#include <libdevcore/TrieHash.h>
#include <libdevcore/FileSystem.h>
#include <libethcore/Exceptions.h>
#include <libethcore/BlockHeader.h>
#include <libethcore/CommonJS.h>
#include "State.h"
#include "Block.h"
#include "Utility.h"
#include "Defaults.h"
#include "NodeConnParamsManagerApi.h"
#include <libdevcore/easylog.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
namespace js = json_spirit;
namespace fs = boost::filesystem;
#define ETH_CATCH 1
#define ETH_TIMED_IMPORTS 1
u256 BlockChain::maxBlockLimit = 1000;
std::ostream& dev::eth::operator<<(std::ostream& _out, BlockChain const& _bc)
{
string cmp = toBigEndianString(_bc.currentHash());
auto it = _bc.m_blocksDB->NewIterator(_bc.m_readOptions);
for (it->SeekToFirst(); it->Valid(); it->Next())
if (it->key().ToString() != "best")
{
try {
BlockHeader d(bytesConstRef(it->value()));
_out << toHex(it->key().ToString()) << ": " << d.number() << " @ " << d.parentHash() << (cmp == it->key().ToString() ? " BEST" : "") << std::endl;
}
catch (...) {
LOG(WARNING) << "Invalid DB entry:" << toHex(it->key().ToString()) << " -> " << toHex(bytesConstRef(it->value()));
}
}
delete it;
return _out;
}
ldb::Slice dev::eth::toSlice(h256 const& _h, unsigned _sub)
{
#if ALL_COMPILERS_ARE_CPP11_COMPLIANT
static thread_local FixedHash<33> h = _h;
h[32] = (uint8_t)_sub;
return (ldb::Slice)h.ref();
#else
static boost::thread_specific_ptr<FixedHash<33>> t_h;
if (!t_h.get())
t_h.reset(new FixedHash<33>);
*t_h = FixedHash<33>(_h);
(*t_h)[32] = (uint8_t)_sub;
return (ldb::Slice)t_h->ref();
#endif //ALL_COMPILERS_ARE_CPP11_COMPLIANT
}
ldb::Slice dev::eth::toSlice(uint64_t _n, unsigned _sub)
{
#if ALL_COMPILERS_ARE_CPP11_COMPLIANT
static thread_local FixedHash<33> h;
toBigEndian(_n, bytesRef(h.data() + 24, 8));
h[32] = (uint8_t)_sub;
return (ldb::Slice)h.ref();
#else
static boost::thread_specific_ptr<FixedHash<33>> t_h;
if (!t_h.get())
t_h.reset(new FixedHash<33>);
bytesRef ref(t_h->data() + 24, 8);
toBigEndian(_n, ref);
(*t_h)[32] = (uint8_t)_sub;
return (ldb::Slice)t_h->ref();
#endif
}
namespace dev
{
class WriteBatchNoter: public ldb::WriteBatch::Handler
{
virtual void Put(ldb::Slice const& _key, ldb::Slice const& _value) { LOG(TRACE) << "Put" << toHex(bytesConstRef(_key)) << "=>" << toHex(bytesConstRef(_value)); }
virtual void Delete(ldb::Slice const& _key) { LOG(TRACE) << "Delete" << toHex(bytesConstRef(_key)); }
};
}
#if ETH_DEBUG&&0
static const chrono::system_clock::duration c_collectionDuration = chrono::seconds(15);
static const unsigned c_collectionQueueSize = 2;
static const unsigned c_maxCacheSize = 1024 * 1024 * 1;
static const unsigned c_minCacheSize = 1;
#else
/// Duration between flushes.
static const chrono::system_clock::duration c_collectionDuration = chrono::seconds(60);
/// Length of death row (total time in cache is multiple of this and collection duration).
static const unsigned c_collectionQueueSize = 20;
/// Max size, above which we start forcing cache reduction.
static const unsigned c_maxCacheSize = 1024 * 1024 * 64;
/// Min size, below which we don't bother flushing it.
static const unsigned c_minCacheSize = 1024 * 1024 * 32;
#endif
BlockChain::BlockChain(std::shared_ptr<Interface> _interface, ChainParams const& _p, std::string const& _dbPath, WithExisting _we, ProgressCallback const& _pc):
m_dbPath(_dbPath),
m_pnoncecheck(make_shared<NonceCheck>())
{
init(_p, _dbPath);
open(_dbPath, _we, _pc);
m_pnoncecheck->init(*this );
m_interface = _interface;
}
BlockChain::~BlockChain()
{
close();
}
bool BlockChain::isBlockLimitOk(Transaction const&_ts) const
{
if ( (_ts.blockLimit() == Invalid256) || ( number() >= _ts.blockLimit() ) || (_ts.blockLimit() > (number() + BlockChain::maxBlockLimit) ) )
{
LOG(TRACE) << "BlockChain::isBlockLimitOk Fail! t.sha3()=" << _ts.sha3() << ",t.blockLimit=" << _ts.blockLimit() << ",number()=" << number() << ",maxBlockLimit=" << BlockChain::maxBlockLimit;
return false;
}
return true;
}
bool BlockChain::isNonceOk(Transaction const&_ts, bool _needinsert) const
{
if ( (_ts.randomid() == Invalid256) || ( !m_pnoncecheck ) || (! m_pnoncecheck->ok(_ts, _needinsert) ) )
{
LOG(TRACE) << "BlockChain::isNonceOk Fail! t.sha3()=" << _ts.sha3() << ",t.nonce=" << _ts.randomid();
return false;
}
return true;
}
u256 BlockChain::filterCheck(const Transaction & _t, FilterCheckScene _checkscene) const
{
return m_interface->filterCheck(_t, _checkscene);
}
void BlockChain::updateSystemContract(std::shared_ptr<Block> block)
{
m_interface->updateSystemContract(block);
}
void BlockChain::updateCache(Address address) const {
m_interface->updateCache(address);
}
BlockHeader const& BlockChain::genesis() const
{
UpgradableGuard l(x_genesis);
if (!m_genesis)
{
auto gb = m_params.genesisBlock();
UpgradeGuard ul(l);
m_genesis = BlockHeader(gb);
m_genesisHeaderBytes = BlockHeader::extractHeader(&gb).data().toBytes();
m_genesisHash = m_genesis.hash();
}
return m_genesis;
}
void BlockChain::init(ChainParams const& _p, std::string const& _path)
{
// initialise deathrow.
m_cacheUsage.resize(c_collectionQueueSize);
m_lastCollection = chrono::system_clock::now();
// Initialise with the genesis as the last block on the longest chain.
m_params = _p;
m_sealEngine.reset(m_params.createSealEngine());
m_genesis.clear();
genesis();
// remove the next line real soon. we don't need to be supporting this forever.
upgradeDatabase(_path, genesisHash());
}
unsigned BlockChain::open(std::string const& _path, WithExisting _we)
{
string path = _path.empty() ? Defaults::get()->m_dbPath : _path;
string chainPath = path + "/" + toHex(m_genesisHash.ref().cropped(0, 4));
string extrasPath = chainPath + "/" + toString(c_databaseVersion);
fs::create_directories(extrasPath);
DEV_IGNORE_EXCEPTIONS(fs::permissions(extrasPath, fs::owner_all));
bytes status = contents(extrasPath + "/minor");
unsigned lastMinor = c_minorProtocolVersion;
if (!status.empty())
DEV_IGNORE_EXCEPTIONS(lastMinor = (unsigned)RLP(status));
if (c_minorProtocolVersion != lastMinor)
{
LOG(TRACE) << "Killing extras database (DB minor version:" << lastMinor << " != our miner version: " << c_minorProtocolVersion << ").";
DEV_IGNORE_EXCEPTIONS(boost::filesystem::remove_all(extrasPath + "/details.old"));
boost::filesystem::rename(extrasPath + "/extras", extrasPath + "/extras.old");
boost::filesystem::remove_all(extrasPath + "/state");
writeFile(extrasPath + "/minor", rlp(c_minorProtocolVersion));
lastMinor = (unsigned)RLP(status);
}
if (_we == WithExisting::Kill)
{
LOG(TRACE) << "Killing blockchain & extras database (WithExisting::Kill).";
boost::filesystem::remove_all(chainPath + "/blocks");
boost::filesystem::remove_all(extrasPath + "/extras");
}
ldb::Options o;
o.create_if_missing = true;
o.max_open_files = 256;
#if ETH_ODBC
LOG(INFO) << "state ethodbc is defined " << std::endl;
m_blocksDB = nullptr;
m_extrasDB = nullptr;
m_blocksDB = ldb::LvlDbInterfaceFactory::create(leveldb::DBUseType::blockType);
if (m_blocksDB != nullptr)
{
LOG(INFO) << "block ethodbc is defined " << std::endl;
}
else
{
LOG(INFO) << "block ethodbc is not defined " << std::endl;
}
m_extrasDB = ldb::LvlDbInterfaceFactory::create(leveldb::DBUseType::extrasType);
if (m_extrasDB != nullptr)
{
LOG(INFO) << "extras ethodbc is defined " << std::endl;
}
else
{
LOG(INFO) << "extras ethodbc is not defined " << std::endl;
}
#else
ldb::DB::Open(o, chainPath + "/blocks", &m_blocksDB);
ldb::DB::Open(o, extrasPath + "/extras", &m_extrasDB);
if (!m_blocksDB || !m_extrasDB)
{
if (boost::filesystem::space(chainPath + "/blocks").available < 1024)
{
LOG(WARNING) << "Not enough available space found on hard drive. Please free some up and then re-run. Bailing.";
BOOST_THROW_EXCEPTION(NotEnoughAvailableSpace());
}
else
{
LOG(WARNING) <<
"Database " <<
(chainPath + "/blocks") <<
"or " <<
(extrasPath + "/extras") <<
"already open. You appear to have another instance of ethereum running. Bailing.";
BOOST_THROW_EXCEPTION(DatabaseAlreadyOpen());
}
}
#endif
if (_we != WithExisting::Verify && !details(m_genesisHash))
{
BlockHeader gb(m_params.genesisBlock());
// Insert details of genesis block.
m_details[m_genesisHash] = BlockDetails(0, gb.difficulty(), h256(), {});
auto r = m_details[m_genesisHash].rlp();
m_extrasDB->Put(m_writeOptions, toSlice(m_genesisHash, ExtraDetails), (ldb::Slice)dev::ref(r));
assert(isKnown(gb.hash()));
}
#if ETH_PARANOIA
checkConsistency();
#endif
// TODO: Implement ability to rebuild details map from DB.
std::string l;
m_extrasDB->Get(m_readOptions, ldb::Slice("best"), &l);
m_lastBlockHash = l.empty() ? m_genesisHash : *(h256*)l.data();
m_lastBlockNumber = number(m_lastBlockHash);
LOG(TRACE) << "Opened blockchain DB. Latest: " << currentHash() << (lastMinor == c_minorProtocolVersion ? "(rebuild not needed)" : "*** REBUILD NEEDED ***");
return lastMinor;
}
void BlockChain::open(std::string const& _path, WithExisting _we, ProgressCallback const& _pc)
{
if (open(_path, _we) != c_minorProtocolVersion || _we == WithExisting::Verify)
rebuild(_path, _pc);
}
void BlockChain::reopen(ChainParams const& _p, WithExisting _we, ProgressCallback const& _pc)
{
close();
init(_p, m_dbPath);
open(m_dbPath, _we, _pc);
}
void BlockChain::close()
{
LOG(TRACE) << "Closing blockchain DB";
// Not thread safe...
delete m_extrasDB;
delete m_blocksDB;
m_lastBlockHash = m_genesisHash;
m_lastBlockNumber = 0;
m_details.clear();
m_blocks.clear();
m_logBlooms.clear();
m_receipts.clear();
m_transactionAddresses.clear();
m_blockHashes.clear();
m_blocksBlooms.clear();
m_cacheUsage.clear();
m_inUse.clear();
m_lastLastHashes.clear();
}
void BlockChain::rebuild(std::string const& _path, std::function<void(unsigned, unsigned)> const& _progress)
{
string path = _path.empty() ? Defaults::get()->m_dbPath : _path;
string chainPath = path + "/" + toHex(m_genesisHash.ref().cropped(0, 4));
string extrasPath = chainPath + "/" + toString(c_databaseVersion);
#if ETH_PROFILING_GPERF
ProfilerStart("BlockChain_rebuild.log");
#endif
unsigned originalNumber = m_lastBlockNumber;
///////////////////////////////
// TODO
// - KILL ALL STATE/CHAIN
// - REINSERT ALL BLOCKS
///////////////////////////////
// Keep extras DB around, but under a temp name
delete m_extrasDB;
m_extrasDB = nullptr;
boost::filesystem::rename(extrasPath + "/extras", extrasPath + "/extras.old");
ldb::DB* oldExtrasDB;
ldb::Options o;
o.create_if_missing = true;
ldb::DB::Open(o, extrasPath + "/extras.old", &oldExtrasDB);
ldb::DB::Open(o, extrasPath + "/extras", &m_extrasDB);
// Open a fresh state DB
Block s = genesisBlock(State::openDB(path, m_genesisHash, WithExisting::Kill));
// Clear all memos ready for replay.
m_details.clear();
m_logBlooms.clear();
m_receipts.clear();
m_transactionAddresses.clear();
m_blockHashes.clear();
m_blocksBlooms.clear();
m_lastLastHashes.clear();
m_lastBlockHash = genesisHash();
m_lastBlockNumber = 0;
m_details[m_lastBlockHash].totalDifficulty = s.info().difficulty();
m_extrasDB->Put(m_writeOptions, toSlice(m_lastBlockHash, ExtraDetails), (ldb::Slice)dev::ref(m_details[m_lastBlockHash].rlp()));
h256 lastHash = m_lastBlockHash;
Timer t;
for (unsigned d = 1; d <= originalNumber; ++d)
{
if (!(d % 1000))
{
LOG(ERROR) << "\n1000 blocks in " << t.elapsed() << "s = " << (1000.0 / t.elapsed()) << "b/s" << endl;
t.restart();
}
try
{
bytes b = block(queryExtras<BlockHash, uint64_t, ExtraBlockHash>(d, m_blockHashes, x_blockHashes, NullBlockHash, oldExtrasDB).value);
BlockHeader bi(&b);
if (bi.parentHash() != lastHash)
{
LOG(WARNING) << "DISJOINT CHAIN DETECTED; " << bi.hash() << "#" << d << " -> parent is" << bi.parentHash() << "; expected" << lastHash << "#" << (d - 1);
return;
}
lastHash = bi.hash();
import(b, s.db(), 0);
}
catch (...)
{
// Failed to import - stop here.
break;
}
if (_progress)
_progress(d, originalNumber);
}
#if ETH_PROFILING_GPERF
ProfilerStop();
#endif
delete oldExtrasDB;
boost::filesystem::remove_all(path + "/extras.old");
}
string BlockChain::dumpDatabase() const
{
stringstream ss;
ss << m_lastBlockHash << endl;
ldb::Iterator* i = m_extrasDB->NewIterator(m_readOptions);
for (i->SeekToFirst(); i->Valid(); i->Next())
ss << toHex(bytesConstRef(i->key())) << "/" << toHex(bytesConstRef(i->value())) << endl;
return ss.str();
}
LastHashes BlockChain::lastHashes(h256 const& _parent) const
{
Guard l(x_lastLastHashes);
if (m_lastLastHashes.empty() || m_lastLastHashes.front() != _parent)
{
m_lastLastHashes.resize(256);
m_lastLastHashes[0] = _parent;
for (unsigned i = 0; i < 255; ++i)
m_lastLastHashes[i + 1] = m_lastLastHashes[i] ? info(m_lastLastHashes[i]).parentHash() : h256();
}
return m_lastLastHashes;
}
void BlockChain::addBlockCache(Block block, u256 td) const {
DEV_WRITE_GUARDED(x_blockcache)
{
if ( m_blockCache.size() > 10 )
m_blockCache.clear();
m_blockCache.insert(std::make_pair(block.info().hash(), std::make_pair(block, td)));
}
}
std::pair<Block, u256> BlockChain::getBlockCache(h256 const& hash) const {
DEV_READ_GUARDED(x_blockcache)
{
auto it = m_blockCache.find(hash);
if (it == m_blockCache.end()) {
return std::make_pair(Block(0), 0);
}
return it->second;
}
}
tuple<ImportRoute, bool, unsigned> BlockChain::sync(BlockQueue& _bq, OverlayDB const& _stateDB, unsigned _max)
{
// _bq.tick(*this);
VerifiedBlocks blocks;
_bq.drain(blocks, _max);
h256s fresh;
h256s dead;
h256s badBlocks;
Transactions goodTransactions;
unsigned count = 0;
uint64_t startimport=0;
uint64_t endimport=0;
for (VerifiedBlock const& block : blocks)
{
do {
try
{
// Nonce & uncle nonces already verified in verification thread at this point.
ImportRoute r;
DEV_TIMED_ABOVE("BLOCKSTAT 超时500ms " +toString(block.verified.info.hash(WithoutSeal))+ toString(block.verified.info.number()), 500)
//DEV_BLOCK_STAT_LOG(block.verified.info.hash(WithoutSeal), block.verified.info.number(), utcTime(), "BeforeImport");
startimport=utcTime();
r = import(block.verified, _stateDB, (ImportRequirements::Everything & ~ImportRequirements::ValidSeal & ~ImportRequirements::CheckUncles) != 0);
endimport=utcTime();
cblockstat<<block.verified.info.hash(WithoutSeal)<<","<<block.verified.info.number()<<",trans"<<r.goodTranactions.size()<<" 上链耗时"<<endimport-startimport<<"ms";
if((endimport-startimport) > COnChainTimeLimit)
{
LOGCOMWARNING<<WarningMap.at(OnChainTimeWarning)<<"|blockNumber:"<<block.verified.info.number()<<" onChainTime:"<< endimport-startimport <<"ms";
}
fresh += r.liveBlocks;
dead += r.deadBlocks;
goodTransactions.reserve(goodTransactions.size() + r.goodTranactions.size());
std::move(std::begin(r.goodTranactions), std::end(r.goodTranactions), std::back_inserter(goodTransactions));
++count;
}
catch (dev::eth::UnknownParent)
{
LOG(WARNING) << "ODD: Import queue contains block with unknown parent.";// << LogTag::Error << boost::current_exception_diagnostic_information();
// NOTE: don't reimport since the queue should guarantee everything in the right order.
// Can't continue - chain bad.
badBlocks.push_back(block.verified.info.hash());
}
catch (dev::eth::FutureTime)
{
LOG(WARNING) << "ODD: Import queue contains a block with future time.";
this_thread::sleep_for(chrono::seconds(1));
continue;
}
catch (dev::eth::TransientError)
{
this_thread::sleep_for(chrono::milliseconds(100));
continue;
}
catch (dev::eth::AlreadyHaveBlock)
{
LOG(WARNING) << "ODD: Try to import one already have block. blk=" << block.verified.info.number() << ",hash=" << block.verified.info.hash(WithoutSeal);
continue;
}
catch (Exception& ex)
{
if (m_onBad)
m_onBad(ex);
// NOTE: don't reimport since the queue should guarantee everything in the right order.
// Can't continue - chain bad.
badBlocks.push_back(block.verified.info.hash());
}
} while (false);
}
return make_tuple(ImportRoute{dead, fresh, goodTransactions}, _bq.doneDrain(badBlocks), count);
}
pair<ImportResult, ImportRoute> BlockChain::attemptImport(bytes const& _block, OverlayDB const& _stateDB, bool _mustBeNew) noexcept
{
try
{
return make_pair(ImportResult::Success, import(verifyBlock(&_block, m_onBad, ImportRequirements::OutOfOrderChecks), _stateDB, _mustBeNew));
}
catch (UnknownParent&)
{
return make_pair(ImportResult::UnknownParent, ImportRoute());
}
catch (AlreadyHaveBlock&)
{
return make_pair(ImportResult::AlreadyKnown, ImportRoute());
}
catch (FutureTime&)
{
return make_pair(ImportResult::FutureTimeKnown, ImportRoute());
}
catch (Exception& ex)
{
if (m_onBad)
m_onBad(ex);
return make_pair(ImportResult::Malformed, ImportRoute());
}
}
ImportRoute BlockChain::import(bytes const& _block, OverlayDB const& _db, bool _mustBeNew)
{
// VERIFY: populates from the block and checks the block is internally coherent.
VerifiedBlockRef block;
#if ETH_CATCH
try
#endif
{
block = verifyBlock(&_block, m_onBad, ImportRequirements::OutOfOrderChecks);
}
#if ETH_CATCH
catch (Exception& ex)
{
// LOG(TRACE) << " Malformed block: " << diagnostic_information(ex);
ex << errinfo_phase(2);
ex << errinfo_now(time(0));
throw;
}
#endif
return import(block, _db, _mustBeNew);
}
void BlockChain::insert(bytes const& _block, bytesConstRef _receipts, bool _mustBeNew)
{
// VERIFY: populates from the block and checks the block is internally coherent.
VerifiedBlockRef block;
#if ETH_CATCH
try
#endif
{
block = verifyBlock(&_block, m_onBad, ImportRequirements::OutOfOrderChecks);
}
#if ETH_CATCH
catch (Exception& ex)
{
// LOG(TRACE) << " Malformed block: " << diagnostic_information(ex);
ex << errinfo_phase(2);
ex << errinfo_now(time(0));
throw;
}
#endif
insert(block, _receipts, _mustBeNew);
}
void BlockChain::insert(VerifiedBlockRef _block, bytesConstRef _receipts, bool _mustBeNew)
{
// Check block doesn't already exist first!
if (isKnown(_block.info.hash()) && _mustBeNew)
{
LOG(TRACE) << _block.info.hash() << ": Not new.";
BOOST_THROW_EXCEPTION(AlreadyHaveBlock());
}
// Work out its number as the parent's number + 1
if (!isKnown(_block.info.parentHash(), false))
{
LOG(TRACE) << _block.info.hash() << ": Unknown parent " << _block.info.parentHash();
// We don't know the parent (yet) - discard for now. It'll get resent to us if we find out about its ancestry later on.
BOOST_THROW_EXCEPTION(UnknownParent());
}
// Check receipts
vector<bytesConstRef> receipts;
for (auto i : RLP(_receipts))
receipts.push_back(i.data());
h256 receiptsRoot = orderedTrieRoot(receipts);
if (_block.info.receiptsRoot() != receiptsRoot)
{
LOG(TRACE) << _block.info.hash() << ": Invalid receipts root " << _block.info.receiptsRoot() << " not " << receiptsRoot;
// We don't know the parent (yet) - discard for now. It'll get resent to us if we find out about its ancestry later on.
BOOST_THROW_EXCEPTION(InvalidReceiptsStateRoot());
}
auto pd = details(_block.info.parentHash());
if (!pd)
{
auto pdata = pd.rlp();
LOG(DEBUG) << "Details is returning false despite block known:" << RLP(pdata);
auto parentBlock = block(_block.info.parentHash());
LOG(DEBUG) << "isKnown:" << isKnown(_block.info.parentHash());
LOG(DEBUG) << "last/number:" << m_lastBlockNumber << m_lastBlockHash << _block.info.number();
LOG(DEBUG) << "Block:" << BlockHeader(&parentBlock);
LOG(DEBUG) << "RLP:" << RLP(parentBlock);
LOG(DEBUG) << "DATABASE CORRUPTION: CRITICAL FAILURE";
exit(-1);
}
// Check it's not crazy
if (_block.info.timestamp() > utcTime() && !m_params.otherParams.count("allowFutureBlocks"))
{
LOG(TRACE) << _block.info.hash() << ": Future time " << _block.info.timestamp() << " (now at " << utcTime() << ")";
// Block has a timestamp in the future. This is no good.
BOOST_THROW_EXCEPTION(FutureTime());
}
// Verify parent-critical parts,
verifyBlock(_block.block, m_onBad, ImportRequirements::InOrderChecks | ImportRequirements::CheckMinerSignatures);
// OK - we're happy. Insert into database.
ldb::WriteBatch blocksBatch;
ldb::WriteBatch extrasBatch;
BlockLogBlooms blb;
for (auto i : RLP(_receipts))
blb.blooms.push_back(TransactionReceipt(i.data()).bloom());
// ensure parent is cached for later addition.
// TODO: this is a bit horrible would be better refactored into an enveloping UpgradableGuard
// together with an "ensureCachedWithUpdatableLock(l)" method.
// This is safe in practice since the caches don't get flushed nearly often enough to be
// done here.
details(_block.info.parentHash());
DEV_WRITE_GUARDED(x_details)
{
if (!dev::contains(m_details[_block.info.parentHash()].children, _block.info.hash()))
m_details[_block.info.parentHash()].children.push_back(_block.info.hash());
}
blocksBatch.Put(toSlice(_block.info.hash()), ldb::Slice(_block.block));
DEV_READ_GUARDED(x_details)
extrasBatch.Put(toSlice(_block.info.parentHash(), ExtraDetails), (ldb::Slice)dev::ref(m_details[_block.info.parentHash()].rlp()));
BlockDetails bd((unsigned)pd.number + 1, pd.totalDifficulty + _block.info.difficulty(), _block.info.parentHash(), {});
extrasBatch.Put(toSlice(_block.info.hash(), ExtraDetails), (ldb::Slice)dev::ref(bd.rlp()));
extrasBatch.Put(toSlice(_block.info.hash(), ExtraLogBlooms), (ldb::Slice)dev::ref(blb.rlp()));
extrasBatch.Put(toSlice(_block.info.hash(), ExtraReceipts), (ldb::Slice)_receipts);
ldb::Status o = m_blocksDB->Write(m_writeOptions, &blocksBatch);
if (!o.ok())
{
LOG(WARNING) << "Error writing to blockchain database: " << o.ToString();
WriteBatchNoter n;
blocksBatch.Iterate(&n);
LOG(WARNING) << "Fail writing to blockchain database. Bombing out.";
exit(-1);
}
o = m_extrasDB->Write(m_writeOptions, &extrasBatch);
if (!o.ok())
{
LOG(WARNING) << "Error writing to extras database: " << o.ToString();
WriteBatchNoter n;
extrasBatch.Iterate(&n);
LOG(WARNING) << "Fail writing to extras database. Bombing out.";
exit(-1);
}
}
void BlockChain::checkBlockValid(h256 const& _hash, bytes const& _block, OverlayDB const& _db) const {
VerifiedBlockRef block = verifyBlock(&_block, m_onBad, ImportRequirements::Everything);
if (_hash != block.info.hash()) {
LOG(WARNING) << "hash error, " << block.info.hash() << "," << _hash;
BOOST_THROW_EXCEPTION(HashError());
}
// 禁止叔块
if (block.info.number() <= info().number()) {
LOG(WARNING) << "height error, h=" << block.info.number() << ", curr=" << info().number();
BOOST_THROW_EXCEPTION(HeightError());
}
if (isKnown(block.info.hash())) {
LOG(WARNING) << block.info.hash() << ": Not new.";
BOOST_THROW_EXCEPTION(AlreadyHaveBlock());
}
if (!isKnown(block.info.parentHash(), false) || !details(block.info.parentHash())) {
LOG(WARNING) << block.info.hash() << ": Unknown parent " << block.info.parentHash();
// We don't know the parent (yet) - discard for now. It'll get resent to us if we find out about its ancestry later on.
BOOST_THROW_EXCEPTION(UnknownParent() << errinfo_hash256(block.info.parentHash()));
}
// Check it's not crazy
if (block.info.timestamp() > utcTime() && !m_params.otherParams.count("allowFutureBlocks"))
{
LOG(WARNING) << block.info.hash() << ": Future time " << block.info.timestamp() << " (now at " << utcTime() << ")";
// Block has a timestamp in the future. This is no good.
BOOST_THROW_EXCEPTION(FutureTime());
}
std::map<std::string, NodeConnParams> all_node;
NodeConnManagerSingleton::GetInstance().getAllNodeConnInfo(static_cast<int>(block.info.number() - 1), all_node);
unsigned miner_num = 0;
for (auto iter = all_node.begin(); iter != all_node.end(); ++iter) {
if (iter->second._iIdentityType == EN_ACCOUNT_TYPE_MINER) {
++miner_num;
}
}
h512s miner_list;
miner_list.resize(miner_num);
for (auto iter = all_node.begin(); iter != all_node.end(); ++iter) {
if (iter->second._iIdentityType == EN_ACCOUNT_TYPE_MINER) {
auto idx = static_cast<unsigned>(iter->second._iIdx);
if (idx >= miner_num) {
LOG(WARNING) << "idx out of bound, idx=" << idx << ",miner_num=" << miner_num;
BOOST_THROW_EXCEPTION(MinerListError());
}
miner_list[idx] = jsToPublic(toJS(iter->second._sNodeId));
}
}
if (miner_list != block.info.nodeList()) {
LOG(WARNING) << "miner list error, " << _hash;
ostringstream oss;
for (size_t i = 0; i < miner_list.size(); ++i) {
oss << miner_list[i] << ",";
}
LOG(WARNING) << "get miner_list size=" << miner_list.size() << ",value=" << oss.str();
ostringstream oss2;
for (size_t i = 0; i < block.info.nodeList().size(); ++i) {
oss2 << block.info.nodeList()[i] << ",";
}
LOG(WARNING) << "block node_list size=" << block.info.nodeList().size() << ",value=" << oss2.str();
BOOST_THROW_EXCEPTION(MinerListError());
}
std::pair<Block, u256> ret = getBlockCache(block.info.hash(WithSeal));
if(ret.second == 0) {
Block s(*this, _db);
u256 td = s.enactOn(block, *this);
s.setEvmCoverLog(m_params.evmCoverLog);
s.setEvmEventLog(m_params.evmEventLog);
addBlockCache(s, td);
}
else {
//do nothing
}
}
ImportRoute BlockChain::import(VerifiedBlockRef const& _block, OverlayDB const& _db, bool _mustBeNew)
{
//@tidy This is a behemoth of a method - could do to be split into a few smaller ones.
#if ETH_TIMED_IMPORTS
Timer total;
double preliminaryChecks;
double enactment;
double collation;
double writing;
double checkBest;
Timer t;
#endif
// Check block doesn't already exist first!
if (isKnown(_block.info.hash()) && _mustBeNew)
{
LOG(TRACE) << _block.info.hash() << ": Not new.";
BOOST_THROW_EXCEPTION(AlreadyHaveBlock() << errinfo_block(_block.block.toBytes()));
}
// Work out its number as the parent's number + 1
if (!isKnown(_block.info.parentHash(), false)) // doesn't have to be current.
{
LOG(TRACE) << _block.info.hash() << ": Unknown parent " << _block.info.parentHash();
// We don't know the parent (yet) - discard for now. It'll get resent to us if we find out about its ancestry later on.
BOOST_THROW_EXCEPTION(UnknownParent() << errinfo_hash256(_block.info.parentHash()));
}
auto pd = details(_block.info.parentHash());
if (!pd)
{
auto pdata = pd.rlp();
LOG(DEBUG) << "Details is returning false despite block known:" << RLP(pdata);
auto parentBlock = block(_block.info.parentHash());
LOG(DEBUG) << "isKnown:" << isKnown(_block.info.parentHash());
LOG(DEBUG) << "last/number:" << m_lastBlockNumber << m_lastBlockHash << _block.info.number();
LOG(DEBUG) << "Block:" << BlockHeader(&parentBlock);
LOG(DEBUG) << "RLP:" << RLP(parentBlock);
LOG(DEBUG) << "DATABASE CORRUPTION: CRITICAL FAILURE";
exit(-1);
}
// Check it's not crazy
if (_block.info.timestamp() > utcTime() && !m_params.otherParams.count("allowFutureBlocks"))
{
LOG(TRACE) << _block.info.hash() << ": Future time " << _block.info.timestamp() << " (now at " << utcTime() << ")";
// Block has a timestamp in the future. This is no good.
BOOST_THROW_EXCEPTION(FutureTime());
}
// Verify parent-critical parts,
verifyBlock(_block.block, m_onBad, ImportRequirements::InOrderChecks | ImportRequirements::CheckMinerSignatures);
LOG(TRACE) << "Attempting import of " << _block.info.hash() << "...";
#if ETH_TIMED_IMPORTS
preliminaryChecks = t.elapsed();
t.restart();
#endif
ldb::WriteBatch blocksBatch;
ldb::WriteBatch extrasBatch;
h256 newLastBlockHash = currentHash();
unsigned newLastBlockNumber = number();
BlockLogBlooms blb;
BlockReceipts br;
u256 td;
Transactions goodTransactions;
std::shared_ptr<Block> tempBlock(new Block(*this, _db));
#if ETH_CATCH
try
#endif
{
// Check transactions are valid and that they result in a state equivalent to our state_root.
// Get total difficulty increase and update state, checking it.
u256 tdIncrease =0;
auto pair = getBlockCache(_block.info.hash());
if(pair.second != 0) {
tdIncrease = pair.second;
*tempBlock = pair.first;
}
else{
tdIncrease = tempBlock->enactOn(_block, *this);
tempBlock->setEvmCoverLog(m_params.evmCoverLog);
tempBlock->setEvmEventLog(m_params.evmEventLog);
addBlockCache(*tempBlock, tdIncrease);
}
for (unsigned i = 0; i < tempBlock->pending().size(); ++i) {
blb.blooms.push_back(tempBlock->receipt(i).bloom());
br.receipts.push_back(tempBlock->receipt(i));
goodTransactions.push_back(tempBlock->pending()[i]);
}
tempBlock->commitAll();
td = pd.totalDifficulty + tdIncrease;
#if ETH_TIMED_IMPORTS
enactment = t.elapsed();
t.restart();
#endif // ETH_TIMED_IMPORTS
#if ETH_PARANOIA
checkConsistency();
#endif // ETH_PARANOIA
// All ok - insert into DB
// ensure parent is cached for later addition.
// TODO: this is a bit horrible would be better refactored into an enveloping UpgradableGuard
// together with an "ensureCachedWithUpdatableLock(l)" method.
// This is safe in practice since the caches don't get flushed nearly often enough to be
// done here.
details(_block.info.parentHash());
DEV_WRITE_GUARDED(x_details)
m_details[_block.info.parentHash()].children.push_back(_block.info.hash());
#if ETH_TIMED_IMPORTS
collation = t.elapsed();
t.restart();
#endif // ETH_TIMED_IMPORTS
blocksBatch.Put(toSlice(_block.info.hash()), ldb::Slice(_block.block));//_block.block [0]=head [1]=transactionlist [2]=unclelist [3]=hash [4]=siglist
DEV_READ_GUARDED(x_details)
extrasBatch.Put(toSlice(_block.info.parentHash(), ExtraDetails), (ldb::Slice)dev::ref(m_details[_block.info.parentHash()].rlp()));
extrasBatch.Put(toSlice(_block.info.hash(), ExtraDetails), (ldb::Slice)dev::ref(BlockDetails((unsigned)pd.number + 1, td, _block.info.parentHash(), {}).rlp()));
extrasBatch.Put(toSlice(_block.info.hash(), ExtraLogBlooms), (ldb::Slice)dev::ref(blb.rlp()));
extrasBatch.Put(toSlice(_block.info.hash(), ExtraReceipts), (ldb::Slice)dev::ref(br.rlp()));
#if ETH_TIMED_IMPORTS
writing = t.elapsed();
t.restart();
#endif // ETH_TIMED_IMPORTS
}
#if ETH_CATCH
catch (BadRoot& ex)
{
m_pnoncecheck->delCache(goodTransactions);
LOG(WARNING) << "*** BadRoot error! Trying to import" << _block.info.hash() << "needed root" << ex.root;
LOG(WARNING) << _block.info;
// Attempt in import later.
BOOST_THROW_EXCEPTION(TransientError());