forked from bcosorg/bcos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlock.cpp
1120 lines (914 loc) · 37.1 KB
/
Block.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 Block.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Block.h"
#include <ctime>
#include <boost/filesystem.hpp>
#include <boost/timer.hpp>
#include <libdevcore/CommonIO.h>
#include <libdevcore/Assertions.h>
#include <libdevcore/TrieHash.h>
#include <libevmcore/Instruction.h>
#include <libethcore/Exceptions.h>
#include <libethcore/SealEngine.h>
#include <libevm/VMFactory.h>
#include "BlockChain.h"
#include "Defaults.h"
#include "ExtVM.h"
#include "Executive.h"
#include "BlockChain.h"
#include "TransactionQueue.h"
#include "SystemContractApi.h"
#include <libdevcore/easylog.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
namespace fs = boost::filesystem;
#define ETH_TIMED_ENACTMENTS 0
unsigned Block::c_maxSyncTransactions = 100;
const char* BlockSafeExceptions::name() { return EthViolet "?" EthBlue " ?"; }
const char* BlockDetail::name() { return EthViolet "?" EthWhite " ?"; }
const char* BlockTrace::name() { return EthViolet "?" EthGray " ◎"; }
const char* BlockChat::name() { return EthViolet "?" EthWhite " ?"; }
Block::Block(BlockChain const& _bc, OverlayDB const& _db, BaseState _bs, Address const& _author):
m_state(Invalid256, _db, _bs),
m_precommit(Invalid256),
m_author(_author)
{
noteChain(_bc);
m_previousBlock.clear();
m_currentBlock.clear();
}
Block::Block(BlockChain const& _bc, OverlayDB const& _db, h256 const& _root, Address const& _author):
m_state(Invalid256, _db, BaseState::PreExisting),
m_precommit(Invalid256),
m_author(_author)
{
noteChain(_bc);
m_state.setRoot(_root);
m_previousBlock.clear();
m_currentBlock.clear();
}
Block::Block(Block const& _s):
m_state(_s.m_state),
m_transactions(_s.m_transactions),
m_receipts(_s.m_receipts),
m_transactionSet(_s.m_transactionSet),
m_precommit(_s.m_state),
m_previousBlock(_s.m_previousBlock),
m_currentBlock(_s.m_currentBlock),
m_currentBytes(_s.m_currentBytes),
m_author(_s.m_author),
m_sealEngine(_s.m_sealEngine)
{
m_committedToSeal = false;
}
Block& Block::operator=(Block const& _s)
{
if (&_s == this)
return *this;
m_state = _s.m_state;
m_transactions = _s.m_transactions;
m_receipts = _s.m_receipts;
m_transactionSet = _s.m_transactionSet;
m_previousBlock = _s.m_previousBlock;
m_currentBlock = _s.m_currentBlock;
m_currentBytes = _s.m_currentBytes;
m_author = _s.m_author;
m_sealEngine = _s.m_sealEngine;
m_precommit = m_state;
m_committedToSeal = false;
return *this;
}
void Block::resetCurrent(u256 const& _timestamp)
{
m_transactions.clear();
m_receipts.clear();
m_transactionSet.clear();
m_currentBlock = BlockHeader();
m_currentBlock.setAuthor(m_author);
m_currentBlock.setTimestamp(max(m_previousBlock.timestamp() + 1, _timestamp));
m_currentBytes.clear();
sealEngine()->populateFromParent(m_currentBlock, m_previousBlock);
m_state.setRoot(m_previousBlock.stateRoot());
m_precommit = m_state;
m_committedToSeal = false;
performIrregularModifications();
}
void Block::resetCurrentTime(u256 const& _timestamp) {
m_currentBlock.setTimestamp(max(m_previousBlock.timestamp() + 1, _timestamp));
}
void Block::setIndex(u256 _idx) {
m_currentBlock.setIndex(_idx);
}
void Block::setNodeList(h512s const& _nodes) {
m_currentBlock.setNodeList(_nodes);
}
SealEngineFace* Block::sealEngine() const
{
if (!m_sealEngine)
BOOST_THROW_EXCEPTION(ChainOperationWithUnknownBlockChain());
return m_sealEngine;
}
void Block::noteChain(BlockChain const& _bc)
{
if (!m_sealEngine)
{
m_state.noteAccountStartNonce(_bc.chainParams().accountStartNonce);
m_precommit.noteAccountStartNonce(_bc.chainParams().accountStartNonce);
m_sealEngine = _bc.sealEngine();
}
}
bool Block::empty() const
{
if(!m_transactions.empty())
return false;
return m_receipts.empty();
}
PopulationStatistics Block::populateFromChain(BlockChain const& _bc, h256 const& _h, ImportRequirements::value _ir)
{
noteChain(_bc);
PopulationStatistics ret { 0.0, 0.0 };
if (!_bc.isKnown(_h))
{
// Might be worth throwing here.
LOG(WARNING) << "Invalid block given for state population: " << _h;
BOOST_THROW_EXCEPTION(BlockNotFound() << errinfo_target(_h));
}
auto b = _bc.block(_h);
BlockHeader bi(b); // No need to check - it's already in the DB.
if (bi.number())
{
// Non-genesis:
// 1. Start at parent's end state (state root).
BlockHeader bip(_bc.block(bi.parentHash()));
sync(_bc, bi.parentHash(), bip);
// 2. Enact the block's transactions onto this state.
m_author = bi.author();
Timer t;
auto vb = _bc.verifyBlock(&b, function<void(Exception&)>(), _ir | ImportRequirements::TransactionBasic);
ret.verify = t.elapsed();
t.restart();
enact(vb, _bc);
ret.enact = t.elapsed();
}
else
{
// Genesis required:
// We know there are no transactions, so just populate directly.
m_state = State(m_state.accountStartNonce(), m_state.db(), BaseState::Empty); // TODO: try with PreExisting.
sync(_bc, _h, bi);
}
return ret;
}
bool Block::sync(BlockChain const& _bc)
{
return sync(_bc, _bc.currentHash());
}
bool Block::sync(BlockChain const& _bc, h256 const& _block, BlockHeader const& _bi)
{
noteChain(_bc);
bool ret = false;
// BLOCK
BlockHeader bi = _bi ? _bi : _bc.info(_block);
#if ETH_PARANOIA
if (!bi)
while (1)
{
try
{
auto b = _bc.block(_block);
bi.populate(b);
break;
}
catch (Exception const& _e)
{
// TODO: Slightly nicer handling? :-)
LOG(ERROR) << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
LOG(ERROR) << diagnostic_information(_e) << endl;
}
catch (std::exception const& _e)
{
// TODO: Slightly nicer handling? :-)
LOG(ERROR) << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
LOG(ERROR) << _e.what() << endl;
}
}
#endif
if (bi == m_currentBlock)
{
// We mined the last block.
// Our state is good - we just need to move on to next.
m_previousBlock = m_currentBlock;
resetCurrent();
ret = true;
}
else if (bi == m_previousBlock)
{
// No change since last sync.
// Carry on as we were.
}
else
{
// New blocks available, or we've switched to a different branch. All change.
// Find most recent state dump and replay what's left.
// (Most recent state dump might end up being genesis.)
if (m_state.db().lookup(bi.stateRoot()).empty()) // TODO: API in State for this?
{
LOG(WARNING) << "Unable to sync to" << bi.hash() << "; state root" << bi.stateRoot() << "not found in database.";
LOG(WARNING) << "Database corrupt: contains block without stateRoot:" << bi;
LOG(WARNING) << "Try rescuing the database by running: eth --rescue";
BOOST_THROW_EXCEPTION(InvalidStateRoot() << errinfo_target(bi.stateRoot()));
}
m_previousBlock = bi;
resetCurrent();
ret = true;
}
#if ALLOW_REBUILD
else
{
// New blocks available, or we've switched to a different branch. All change.
// Find most recent state dump and replay what's left.
// (Most recent state dump might end up being genesis.)
std::vector<h256> chain;
while (bi.number() != 0 && m_db.lookup(bi.stateRoot()).empty()) // while we don't have the state root of the latest block...
{
chain.push_back(bi.hash()); // push back for later replay.
bi.populate(_bc.block(bi.parentHash())); // move to parent.
}
m_previousBlock = bi;
resetCurrent();
// Iterate through in reverse, playing back each of the blocks.
try
{
for (auto it = chain.rbegin(); it != chain.rend(); ++it)
{
auto b = _bc.block(*it);
enact(&b, _bc, _ir);
cleanup(true);
}
}
catch (...)
{
// TODO: Slightly nicer handling? :-)
LOG(ERROR) << "ERROR: Corrupt block-chain! Delete your block-chain DB and restart." << endl;
LOG(ERROR) << boost::current_exception_diagnostic_information() << endl;
exit(1);
}
resetCurrent();
ret = true;
}
#endif
return ret;
}
pair<TransactionReceipts, bool> Block::sync(BlockChain const& _bc, TransactionQueue& _tq, GasPricer const& _gp, unsigned msTimeout)
{
LOG(TRACE) << "Block::sync ";
if (isSealed())
BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
noteChain(_bc);
// TRANSACTIONS
pair<TransactionReceipts, bool> ret;
auto ts = _tq.topTransactions(c_maxSyncTransactions, m_transactionSet);
ret.second = (ts.size() == c_maxSyncTransactions); // say there's more to the caller if we hit the limit
LastHashes lh;
auto deadline = chrono::steady_clock::now() + chrono::milliseconds(msTimeout);
for (int goodTxs = max(0, (int)ts.size() - 1); goodTxs < (int)ts.size(); )
{
goodTxs = 0;
for (auto const& t : ts)
if (!m_transactionSet.count(t.sha3()))
{
try
{
++goodTxs;
u256 check = _bc.filterCheck(t, FilterCheckScene::PackTranscation);
if ( (u256)SystemContractCode::Ok != check )
{
LOG(WARNING) << "Block::sync " << t.sha3() << " transition filterCheck PackTranscation Fail" << check;
BOOST_THROW_EXCEPTION(FilterCheckFail());
}
if ( ! _bc.isBlockLimitOk(t) )
{
LOG(WARNING) << "Block::sync " << t.sha3() << " transition blockLimit=" << t.blockLimit() << " chain number=" << _bc.number();
BOOST_THROW_EXCEPTION(BlockLimitCheckFail());
}
if ( !_bc.isNonceOk(t) )
{
LOG(WARNING) << "Block::sync " << t.sha3() << " " << t.randomid();
BOOST_THROW_EXCEPTION(NonceCheckFail());
}
for ( size_t pIndex = 0; pIndex < m_transactions.size(); pIndex++)
{
if ( (m_transactions[pIndex].from() == t.from() ) && (m_transactions[pIndex].randomid() == t.randomid()) )
BOOST_THROW_EXCEPTION(NonceCheckFail());
}//for
u256 _t = _gp.ask(*this);
if ( _t )
_t = 0;
if (lh.empty())
lh = _bc.lastHashes();
execute(lh, t, Permanence::Committed, OnOpFunc(), &_bc);
ret.first.push_back(m_receipts.back());
}
catch ( FilterCheckFail const& in)
{
LOG(WARNING) << t.sha3() << "Block::sync Dropping transaction (filter check fail!)";
_tq.drop(t.sha3());
}
catch ( NoDeployPermission const &in)
{
LOG(WARNING) << t.sha3() << "Block::sync Dropping transaction (NoDeployPermission fail!)";
_tq.drop(t.sha3());
}
catch (BlockLimitCheckFail const& in)
{
LOG(WARNING) << t.sha3() << "Block::sync Dropping transaction (blocklimit check fail!)";
_tq.drop(t.sha3());
}
catch (NonceCheckFail const& in)
{
LOG(WARNING) << t.sha3() << "Block::sync Dropping transaction (nonce check fail!)";
_tq.drop(t.sha3());
}
catch (InvalidNonce const& in)
{
bigint const& req = *boost::get_error_info<errinfo_required>(in);
bigint const& got = *boost::get_error_info<errinfo_got>(in);
if (req > got)
{
// too old
LOG(TRACE) << t.sha3() << "Dropping old transaction (nonce too low)";
_tq.drop(t.sha3());
}
else if (got > req + _tq.waiting(t.sender()))
{
// too new
LOG(TRACE) << t.sha3() << "Dropping new transaction (too many nonces ahead)";
_tq.drop(t.sha3());
}
else
_tq.setFuture(t.sha3());
}
catch (BlockGasLimitReached const& e)
{
bigint const& got = *boost::get_error_info<errinfo_got>(e);
if (got > m_currentBlock.gasLimit())
{
LOG(TRACE) << t.sha3() << "Dropping over-gassy transaction (gas > block's gas limit)";
_tq.drop(t.sha3());
}
else
{
LOG(TRACE) << t.sha3() << "Temporarily no gas left in current block (txs gas > block's gas limit)";
//_tq.drop(t.sha3());
// Temporarily no gas left in current block.
// OPTIMISE: could note this and then we don't evaluate until a block that does have the gas left.
// for now, just leave alone.
}
}
catch (Exception const& _e)
{
// Something else went wrong - drop it.
LOG(TRACE) << t.sha3() << "Dropping invalid transaction:" << diagnostic_information(_e);
_tq.drop(t.sha3());
}
catch (std::exception const&)
{
// Something else went wrong - drop it.
_tq.drop(t.sha3());
LOG(WARNING) << t.sha3() << "Transaction caused low-level exception :(";
}
}
if (chrono::steady_clock::now() > deadline)
{
ret.second = true; // say there's more to the caller if we ended up crossing the deadline.
break;
}
}
return ret;
}
u256 Block::enactOn(VerifiedBlockRef const& _block, BlockChain const& _bc)
{
noteChain(_bc);
#if ETH_TIMED_ENACTMENTS
Timer t;
double populateVerify;
double populateGrand;
double syncReset;
double enactment;
#endif
// Check family:
BlockHeader biParent = _bc.info(_block.info.parentHash());
_block.info.verify(CheckNothingNew/*CheckParent*/, biParent);
#if ETH_TIMED_ENACTMENTS
populateVerify = t.elapsed();
t.restart();
#endif
BlockHeader biGrandParent;
if (biParent.number())
biGrandParent = _bc.info(biParent.parentHash());
#if ETH_TIMED_ENACTMENTS
populateGrand = t.elapsed();
t.restart();
#endif
sync(_bc, _block.info.parentHash(), BlockHeader());
resetCurrent();
#if ETH_TIMED_ENACTMENTS
syncReset = t.elapsed();
t.restart();
#endif
m_previousBlock = biParent;
auto ret = enact(_block, _bc, true);
#if ETH_TIMED_ENACTMENTS
enactment = t.elapsed();
if (populateVerify + populateGrand + syncReset + enactment > 0.5)
LOG(TRACE) << "popVer/popGrand/syncReset/enactment = " << populateVerify << "/" << populateGrand << "/" << syncReset << "/" << enactment;
#endif
return ret;
}
u256 Block::enact(VerifiedBlockRef const& _block, BlockChain const& _bc, bool _filtercheck)
{
noteChain(_bc);
DEV_TIMED_FUNCTION_ABOVE(500);
// m_currentBlock is assumed to be prepopulated and reset.
#if !ETH_RELEASE
assert(m_previousBlock.hash() == _block.info.parentHash());
assert(m_currentBlock.parentHash() == _block.info.parentHash());
#endif
if (m_currentBlock.parentHash() != m_previousBlock.hash())
// Internal client error.
BOOST_THROW_EXCEPTION(InvalidParentHash());
// Populate m_currentBlock with the correct values.
m_currentBlock.noteDirty();
m_currentBlock = _block.info;
LastHashes lh;
DEV_TIMED_ABOVE("lastHashes", 500)
lh = _bc.lastHashes(m_currentBlock.parentHash());
RLP rlp(_block.block);
vector<bytes> receipts;
LOG(TRACE) << "Block:enact tx_num=" << _block.transactions.size();
// All ok with the block generally. Play back the transactions now...
unsigned i = 0;
DEV_TIMED_ABOVE("txExec", 500)
for (Transaction const& tr : _block.transactions)
{
try
{
LOG(TRACE) << "Enacting transaction: " << tr.randomid() << tr.from() << tr.value() << toString(tr.sha3());
execute(lh, tr, Permanence::Committed, OnOpFunc(), (_filtercheck ? (&_bc) : nullptr));
}
catch (Exception& ex)
{
ex << errinfo_transactionIndex(i);
throw;
}
LOG(TRACE) << "Block::enact: t=" << toString(tr.sha3());
LOG(TRACE) << "Block::enact: stateRoot=" << toString(m_receipts.back().stateRoot()) << ",gasUsed=" << toString(m_receipts.back().gasUsed()) << ",sha3=" << toString(sha3(m_receipts.back().rlp()));
RLPStream receiptRLP;
m_receipts.back().streamRLP(receiptRLP);
receipts.push_back(receiptRLP.out());
++i;
}
h256 receiptsRoot;
DEV_TIMED_ABOVE(".receiptsRoot()", 500)
receiptsRoot = orderedTrieRoot(receipts);
if (receiptsRoot != m_currentBlock.receiptsRoot())
{
LOG(TRACE) << "Block::enact receiptsRoot" << toString(receiptsRoot) << ",m_currentBlock.receiptsRoot()=" << toString(m_currentBlock.receiptsRoot()) << ",header" << m_currentBlock;
assert(false);
InvalidReceiptsStateRoot ex;
ex << Hash256RequirementError(receiptsRoot, m_currentBlock.receiptsRoot());
ex << errinfo_receipts(receipts);
BOOST_THROW_EXCEPTION(ex);
}
if (m_currentBlock.logBloom() != logBloom())
{
InvalidLogBloom ex;
ex << LogBloomRequirementError(logBloom(), m_currentBlock.logBloom());
ex << errinfo_receipts(receipts);
BOOST_THROW_EXCEPTION(ex);
}
// Initialise total difficulty calculation.
u256 tdIncrease = m_currentBlock.difficulty();
// Check uncles & apply their rewards to state.
if (rlp[2].itemCount() > 2)
{
TooManyUncles ex;
ex << errinfo_max(2);
ex << errinfo_got(rlp[2].itemCount());
BOOST_THROW_EXCEPTION(ex);
}
vector<BlockHeader> rewarded;
h256Hash excluded;
DEV_TIMED_ABOVE("allKin", 500)
excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6);
excluded.insert(m_currentBlock.hash());
unsigned ii = 0;
DEV_TIMED_ABOVE("uncleCheck", 500)
for (auto const& i : rlp[2])
{
try
{
auto h = sha3(i.data());
if (excluded.count(h))
{
UncleInChain ex;
ex << errinfo_comment("Uncle in block already mentioned");
ex << errinfo_unclesExcluded(excluded);
ex << errinfo_hash256(sha3(i.data()));
BOOST_THROW_EXCEPTION(ex);
}
excluded.insert(h);
// CheckNothing since it's a VerifiedBlock.
BlockHeader uncle(i.data(), HeaderData, h);
BlockHeader uncleParent;
if (!_bc.isKnown(uncle.parentHash()))
BOOST_THROW_EXCEPTION(UnknownParent() << errinfo_hash256(uncle.parentHash()));
uncleParent = BlockHeader(_bc.block(uncle.parentHash()));
// m_currentBlock.number() - uncle.number() m_cB.n - uP.n()
// 1 2
// 2
// 3
// 4
// 5
// 6 7
// (8 Invalid)
bigint depth = (bigint)m_currentBlock.number() - (bigint)uncle.number();
if (depth > 6)
{
UncleTooOld ex;
ex << errinfo_uncleNumber(uncle.number());
ex << errinfo_currentNumber(m_currentBlock.number());
BOOST_THROW_EXCEPTION(ex);
}
else if (depth < 1)
{
UncleIsBrother ex;
ex << errinfo_uncleNumber(uncle.number());
ex << errinfo_currentNumber(m_currentBlock.number());
BOOST_THROW_EXCEPTION(ex);
}
// cB
// cB.p^1 1 depth, valid uncle
// cB.p^2 ---/ 2
// cB.p^3 -----/ 3
// cB.p^4 -------/ 4
// cB.p^5 ---------/ 5
// cB.p^6 -----------/ 6
// cB.p^7 -------------/
// cB.p^8
auto expectedUncleParent = _bc.details(m_currentBlock.parentHash()).parent;
for (unsigned i = 1; i < depth; expectedUncleParent = _bc.details(expectedUncleParent).parent, ++i) {}
if (expectedUncleParent != uncleParent.hash())
{
UncleParentNotInChain ex;
ex << errinfo_uncleNumber(uncle.number());
ex << errinfo_currentNumber(m_currentBlock.number());
BOOST_THROW_EXCEPTION(ex);
}
uncle.verify(CheckNothingNew/*CheckParent*/, uncleParent);
rewarded.push_back(uncle);
++ii;
}
catch (Exception& ex)
{
ex << errinfo_uncleIndex(ii);
throw;
}
}
// Commit all cached state changes to the state trie.
//bool removeEmptyAccounts = m_currentBlock.number() >= _bc.chainParams().u256Param("EIP158ForkBlock");
m_state.commit( State::CommitBehaviour::KeepEmptyAccounts);
DEV_TIMED_ABOVE("commit", 500)
// Hash the state trie and check against the state_root hash in m_currentBlock.
if (m_currentBlock.stateRoot() != m_previousBlock.stateRoot() && m_currentBlock.stateRoot() != rootHash())
{
auto r = rootHash();
m_state.db().rollback();
LOG(TRACE) << "m_currentBlock.stateRoot()=" << m_currentBlock.stateRoot() << ",m_previousBlock.stateRoot()=" << m_previousBlock.stateRoot() << ",rootHash()=" << rootHash();
BOOST_THROW_EXCEPTION(InvalidStateRoot() << Hash256RequirementError(r, m_currentBlock.stateRoot()));
}
if (m_currentBlock.gasUsed() != gasUsed())
{
// Rollback the trie.
m_state.db().rollback();
BOOST_THROW_EXCEPTION(InvalidGasUsed() << RequirementError(bigint(gasUsed()), bigint(m_currentBlock.gasUsed())));
}
return tdIncrease;
}
// will throw exception
ExecutionResult Block::execute(LastHashes const& _lh, Transaction const& _t, Permanence _p, OnOpFunc const& _onOp, BlockChain const *_bcp)
{
LOG(TRACE) << "Block::execute " << _t.sha3();
if (isSealed())
BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
// Uncommitting is a non-trivial operation - only do it once we've verified as much of the
// transaction as possible.
uncommitToSeal();
if ( _bcp != nullptr )
{
u256 check = _bcp->filterCheck(_t, FilterCheckScene::BlockExecuteTransation);
if ( (u256)SystemContractCode::Ok != check )
{
LOG(WARNING) << "Block::execute " << _t.sha3() << " transition filterCheck Fail" << check;
BOOST_THROW_EXCEPTION(FilterCheckFail());
}
}
if (VMFactory::getKind() == VMKind::Dual) {
VMFactory::setKind(VMKind::JIT);
Timer timer;
std::pair<ExecutionResult, TransactionReceipt> JITResultReceipt = m_state.execute(EnvInfo(info(), _lh, gasUsed()), *m_sealEngine, _t, Permanence::Dry, _onOp);
std::unordered_map<Address, Account> JITCache = m_state.getCache();
m_state.clearCache();
VMFactory::setKind(VMKind::Interpreter);
timer.restart();
std::pair<ExecutionResult, TransactionReceipt> interpreterResultReceipt = m_state.execute(EnvInfo(info(), _lh, gasUsed()), *m_sealEngine, _t, _p, _onOp);
std::unordered_map<Address, Account> interpreterCache = m_state.getCache();
m_state.commit(State::CommitBehaviour::KeepEmptyAccounts);
VMFactory::setKind(VMKind::Dual);
auto lhsResult = interpreterResultReceipt.first;
auto rhsResult = JITResultReceipt.first;
for (auto lhsAccountIt = interpreterCache.begin(); lhsAccountIt != interpreterCache.end(); ++lhsAccountIt) {
auto rhsAccountIt = JITCache.find(lhsAccountIt->first);
if (rhsAccountIt == JITCache.end()) {
LOG(WARNING) << "[Dual error]JIT执行缺少Account:" << lhsAccountIt->first;
}
else {
Account &lhs = lhsAccountIt->second;
Account &rhs = rhsAccountIt->second;
if (lhs.nonce() != rhs.nonce() || lhs.balance() != rhs.balance() || lhs.code() != rhs.code()) {
LOG(WARNING) << "[Dual error]JIT Account与Interpreter Account差异:" << lhsAccountIt->first
<< "nonce:" << lhs.nonce() << "," << rhs.nonce()
<< "; balance:" << lhs.balance() << "," << rhs.balance()
<< "; code:" << lhs.code() << "," << rhs.code();
}
auto lhsStorage = lhs.storageOverlay();
auto rhsStorage = rhs.storageOverlay();
for (auto lhsStorageIt = lhsStorage.begin(); lhsStorageIt != lhsStorage.end(); ++lhsStorageIt) {
auto rhsStorageIt = rhsStorage.find(lhsStorageIt->first);
if (rhsStorageIt == rhsStorage.end()) {
LOG(WARNING) << "[Dual error]JIT缺少Storage key, Account:" << lhsStorageIt->first << "storage key:" << lhsStorageIt->first;
}
else if (lhsStorageIt->second != rhsStorageIt->second) {
LOG(WARNING) << "[Dual error]JIT storage与Interpreter差异 Account:" << lhsStorageIt->first << "JIT:" << lhsStorageIt->second << "Interpreter:" << rhsStorageIt->second;
}
}
}
}
if (_p == Permanence::Committed)
{
// Add to the user-originated transactions that we've executed.
m_transactions.push_back(_t);
m_receipts.push_back(interpreterResultReceipt.second);
m_transactionSet.insert(_t.sha3());
}
return interpreterResultReceipt.first;
}
std::pair<ExecutionResult, TransactionReceipt> resultReceipt = m_state.execute(EnvInfo(info(), _lh, gasUsed(), m_evmCoverLog, m_evmEventLog), *m_sealEngine, _t, _p, _onOp);
if (_p == Permanence::Committed)
{
// Add to the user-originated transactions that we've executed.
m_transactions.push_back(_t);
LOG(TRACE) << "Block::execute: t=" << toString(_t.sha3());
m_receipts.push_back(resultReceipt.second);
LOG(TRACE) << "Block::execute: stateRoot=" << toString(resultReceipt.second.stateRoot()) << ",gasUsed=" << toString(resultReceipt.second.gasUsed()) << ",sha3=" << toString(sha3(resultReceipt.second.rlp()));
m_transactionSet.insert(_t.sha3());
if (_bcp) {
(_bcp)->updateCache(_t.to());
}
}
return resultReceipt.first;
}
void Block::applyRewards(vector<BlockHeader> const& , u256 const& )
{
return ;
}
void Block::performIrregularModifications()
{
}
void Block::commitToSeal(BlockChain const& _bc, bytes const& _extraData)
{
if (isSealed())
BOOST_THROW_EXCEPTION(InvalidOperationOnSealedBlock());
noteChain(_bc);
if (m_committedToSeal)
uncommitToSeal();
else
m_precommit = m_state;
vector<BlockHeader> uncleBlockHeaders;
RLPStream unclesData;
unsigned unclesCount = 0;
if (m_previousBlock.number() != 0)
{
// Find great-uncles (or second-cousins or whatever they are) - children of great-grandparents, great-great-grandparents... that were not already uncles in previous generations.
LOG(TRACE) << "Checking " << m_previousBlock.hash() << ", parent=" << m_previousBlock.parentHash();
h256Hash excluded = _bc.allKinFrom(m_currentBlock.parentHash(), 6);
auto p = m_previousBlock.parentHash();
for (unsigned gen = 0; gen < 6 && p != _bc.genesisHash() && unclesCount < 2; ++gen, p = _bc.details(p).parent)
{
auto us = _bc.details(p).children;
assert(us.size() >= 1); // must be at least 1 child of our grandparent - it's our own parent!
for (auto const& u : us)
if (!excluded.count(u)) // ignore any uncles/mainline blocks that we know about.
{
uncleBlockHeaders.push_back(_bc.info(u));
unclesData.appendRaw(_bc.headerData(u));
++unclesCount;
if (unclesCount == 2)
break;
excluded.insert(u);
}
}
}
BytesMap transactionsMap;
BytesMap receiptsMap;
RLPStream txs;
txs.appendList(m_transactions.size());
for (unsigned i = 0; i < m_transactions.size(); ++i)
{
RLPStream k;
k << i;
RLPStream receiptrlp;
m_receipts[i].streamRLP(receiptrlp);
receiptsMap.insert(std::make_pair(k.out(), receiptrlp.out()));
RLPStream txrlp;
m_transactions[i].streamRLP(txrlp);
transactionsMap.insert(std::make_pair(k.out(), txrlp.out()));
txs.appendRaw(txrlp.out());
}
txs.swapOut(m_currentTxs);
RLPStream(unclesCount).appendRaw(unclesData.out(), unclesCount).swapOut(m_currentUncles);
DEV_TIMED_ABOVE("commit", 500)
m_state.commit(State::CommitBehaviour::KeepEmptyAccounts);
/*
LOG(TRACE) << "Post-reward stateRoot:" << m_state.rootHash();
LOG(TRACE) << m_state;
LOG(TRACE) << *this;
*/
m_currentBlock.setLogBloom(logBloom());
m_currentBlock.setGasUsed(gasUsed());
m_currentBlock.setRoots(hash256(transactionsMap), hash256(receiptsMap), sha3(m_currentUncles), m_state.rootHash());
m_currentBlock.setParentHash(m_previousBlock.hash());
m_currentBlock.setExtraData(_extraData);
if (m_currentBlock.extraData().size() > 32)
{
auto ed = m_currentBlock.extraData();
ed.resize(32);
m_currentBlock.setExtraData(ed);
}
m_committedToSeal = true;
}
void Block::uncommitToSeal()
{
if (m_committedToSeal)
{
m_state = m_precommit;
m_committedToSeal = false;
}
}
bool Block::sealBlock(bytesConstRef _header)
{
return sealBlock(BlockHeader(_header, HeaderData), _header);
}
bool Block::sealBlock(BlockHeader const& _header, bytesConstRef _headerBytes) {
if (!m_committedToSeal)
return false;
if (_header.hash(WithoutSeal) != m_currentBlock.hash(WithoutSeal))
return false;
LOG(TRACE) << "Sealing block!";
// Compile block:
RLPStream ret;
ret.appendList(5);
ret.appendRaw(_headerBytes);
ret.appendRaw(m_currentTxs);
ret.appendRaw(m_currentUncles);
ret.append(m_currentBlock.hash(WithoutSeal));
std::vector<std::pair<u256, Signature>> sig_list;
ret.appendVector(sig_list);
ret.swapOut(m_currentBytes);
m_currentBlock = _header;
m_state = m_precommit;
return true;
}
bytes Block::blockBytes() const
{
cdebug << "Block::blockBytes()";
BlockHeader header = info();
RLPStream h;
header.streamRLP(h);
RLPStream ret;
ret.appendList(3);
ret.appendRaw(h.out());
ret.appendRaw(m_currentTxs);
ret.appendRaw(m_currentUncles);
return ret.out();