-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathBlockHeader.cpp
More file actions
335 lines (300 loc) · 13.1 KB
/
Copy pathBlockHeader.cpp
File metadata and controls
335 lines (300 loc) · 13.1 KB
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
/*
Modifications Copyright (C) 2018 SKALE Labs
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 BlockHeader.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "BlockHeader.h"
#include "Exceptions.h"
#include <libdevcore/Common.h>
#include <libdevcore/Log.h>
#include <libdevcore/OverlayDB.h>
#include <libdevcore/RLP.h>
#include <libdevcore/TrieDB.h>
#include <libdevcore/TrieHash.h>
#include <libethcore/Common.h>
#include <libethereum/SchainPatch.h>
using namespace std;
using namespace dev;
using namespace dev::eth;
bool BlockHeader::useTimestampHack = false;
BlockHeader::BlockHeader() {}
BlockHeader::BlockHeader( bytesConstRef _block, BlockDataType _bdt, h256 const& _hashWith ) {
RLP header = _bdt == BlockData ? extractHeader( _block ) : RLP( _block );
m_hash = _hashWith ? _hashWith : sha3( header.data() );
populate( header );
}
BlockHeader::BlockHeader( BlockHeader const& _other )
: m_parentHash( _other.parentHash() ),
m_sha3Uncles( _other.sha3Uncles() ),
m_stateRoot( _other.stateRoot() ),
m_transactionsRoot( _other.transactionsRoot() ),
m_receiptsRoot( _other.receiptsRoot() ),
m_logBloom( _other.logBloom() ),
m_number( _other.number() ),
m_gasLimit( _other.gasLimit() ),
m_gasUsed( _other.gasUsed() ),
m_extraData( _other.extraData() ),
m_timestamp( _other.timestamp() ),
m_author( _other.author() ),
m_difficulty( _other.difficulty() ),
m_baseFeePerGas( _other.baseFeePerGas() ),
m_seal( _other.seal() ),
m_hash( _other.hashRawRead() ),
m_hashWithout( _other.hashWithoutRawRead() ) {
assert( *this == _other );
}
BlockHeader& BlockHeader::operator=( BlockHeader const& _other ) {
if ( this == &_other )
return *this;
m_parentHash = _other.parentHash();
m_sha3Uncles = _other.sha3Uncles();
m_stateRoot = _other.stateRoot();
m_transactionsRoot = _other.transactionsRoot();
m_receiptsRoot = _other.receiptsRoot();
m_logBloom = _other.logBloom();
m_number = _other.number();
m_gasLimit = _other.gasLimit();
m_gasUsed = _other.gasUsed();
m_extraData = _other.extraData();
m_timestamp = _other.timestamp();
m_author = _other.author();
m_difficulty = _other.difficulty();
m_baseFeePerGas = _other.baseFeePerGas();
std::vector< bytes > seal = _other.seal();
{
Guard l( m_sealLock );
m_seal = std::move( seal );
}
h256 hash = _other.hashRawRead();
h256 hashWithout = _other.hashWithoutRawRead();
{
Guard l( m_hashLock );
m_hash = std::move( hash );
m_hashWithout = std::move( hashWithout );
}
assert( *this == _other );
return *this;
}
void BlockHeader::clear() {
m_parentHash = h256();
m_sha3Uncles = EmptyListSHA3;
m_author = Address();
m_stateRoot = EmptyTrie;
m_transactionsRoot = EmptyTrie;
m_receiptsRoot = EmptyTrie;
m_logBloom = LogBloom();
m_difficulty = 0;
m_baseFeePerGas = 1;
m_number = 0;
m_gasLimit = 0;
m_gasUsed = 0;
m_timestamp = -1;
m_extraData.clear();
m_seal.clear();
noteDirty();
}
h256 BlockHeader::hash( IncludeSeal _i ) const {
h256 dummy;
Guard l( m_hashLock );
h256& memo = _i == WithSeal ? m_hash : _i == WithoutSeal ? m_hashWithout : dummy;
if ( !memo ) {
RLPStream s;
streamRLP( s, _i );
memo = sha3( s.out() );
}
return memo;
}
void BlockHeader::streamRLPFields( RLPStream& _s ) const {
_s << m_parentHash << m_sha3Uncles << m_author << m_stateRoot << m_transactionsRoot
<< m_receiptsRoot << m_logBloom << m_difficulty << m_number << m_gasLimit << m_gasUsed
<< ( useTimestampHack ? ( m_number + 1 ) : m_timestamp ) << m_extraData;
}
void BlockHeader::streamRLP( RLPStream& _s, IncludeSeal _i ) const {
// Genesis (block 0) never carries baseFeePerGas in its RLP, even if its timestamp falls
// inside the London-active range. This keeps the genesis hash stable across London
// activation and matches the parser-side expectation in populate() below.
const bool london = LondonForkPatch::isEnabledWhen( static_cast< time_t >( timestamp() ) );
const bool writeBaseFee = london && number() > 0;
if ( _i != OnlySeal ) {
_s.appendList( BlockHeader::BasicFields + ( writeBaseFee ? 1 : 0 ) +
( _i == WithoutSeal ? 0 : m_seal.size() ) );
BlockHeader::streamRLPFields( _s );
}
if ( _i != WithoutSeal )
for ( unsigned i = 0; i < m_seal.size(); ++i )
_s.appendRaw( m_seal[i] );
if ( _i != OnlySeal ) {
if ( writeBaseFee )
_s << m_baseFeePerGas;
}
}
h256 BlockHeader::headerHashFromBlock( bytesConstRef _block ) {
return sha3( RLP( _block )[0].data() );
}
RLP BlockHeader::extractHeader( bytesConstRef _block ) {
RLP root( _block );
if ( !root.isList() )
BOOST_THROW_EXCEPTION( InvalidBlockFormat() << errinfo_comment( "Block must be a list" )
<< BadFieldError( 0, _block.toString() ) );
RLP header = root[0];
if ( !header.isList() )
BOOST_THROW_EXCEPTION( InvalidBlockFormat()
<< errinfo_comment( "Block header must be a list" )
<< BadFieldError( 0, header.data().toString() ) );
if ( !root[1].isList() )
BOOST_THROW_EXCEPTION( InvalidBlockFormat()
<< errinfo_comment( "Block transactions must be a list" )
<< BadFieldError( 1, root[1].data().toString() ) );
if ( !root[2].isList() )
BOOST_THROW_EXCEPTION( InvalidBlockFormat()
<< errinfo_comment( "Block uncles must be a list" )
<< BadFieldError( 2, root[2].data().toString() ) );
return header;
}
void BlockHeader::populate( RLP const& _header ) {
int field = 0;
try {
m_parentHash = _header[field = 0].toHash< h256 >( RLP::VeryStrict );
m_sha3Uncles = _header[field = 1].toHash< h256 >( RLP::VeryStrict );
m_author = _header[field = 2].toHash< Address >( RLP::VeryStrict );
m_stateRoot = _header[field = 3].toHash< h256 >( RLP::VeryStrict );
m_transactionsRoot = _header[field = 4].toHash< h256 >( RLP::VeryStrict );
m_receiptsRoot = _header[field = 5].toHash< h256 >( RLP::VeryStrict );
m_logBloom = _header[field = 6].toHash< LogBloom >( RLP::VeryStrict );
m_difficulty = _header[field = 7].toInt< u256 >();
m_number = _header[field = 8].toPositiveInt64();
m_gasLimit = _header[field = 9].toInt< u256 >();
m_gasUsed = _header[field = 10].toInt< u256 >();
m_timestamp = _header[field = 11].toPositiveInt64();
m_extraData = _header[field = 12].toBytes();
m_seal.clear();
m_baseFeePerGas = 0;
const bool london = LondonForkPatch::isEnabledWhen( static_cast< time_t >( m_timestamp ) );
// Genesis (block 0) never carries baseFeePerGas in its RLP regardless of London status.
// All subsequent London blocks written by streamRLP() always include it as the last field.
const bool expectBaseFee = london && m_number > 0;
const unsigned totalItems = _header.itemCount();
// Non-genesis London headers carry baseFee as the last field after 0 or 2 seal fields
// (14 or 16 total); reject other counts to avoid misreading a seal field.
if ( expectBaseFee ) {
const unsigned emptySealShape = 13 + 0 + 1; // 14
const unsigned twoFieldSealShape = 13 + 2 + 1; // 16
if ( totalItems != emptySealShape && totalItems != twoFieldSealShape ) {
BOOST_THROW_EXCEPTION(
InvalidBlockFormat()
<< errinfo_comment( "London block header has wrong field count "
"(expected 14 for empty seal or 16 for a 2-field seal, "
"including the trailing baseFeePerGas; it may be missing "
"or the seal length is wrong)" )
<< BadFieldError( 13, std::string( "<missing-or-misaligned>" ) ) );
}
}
const unsigned sealEnd = expectBaseFee ? totalItems - 1 : totalItems;
for ( unsigned i = 13; i < sealEnd; ++i )
m_seal.push_back( _header[i].data().toBytes() );
if ( expectBaseFee ) {
m_baseFeePerGas = _header[field = sealEnd].toInt< u256 >();
}
} catch ( Exception const& _e ) {
_e << errinfo_name( "invalid block header format" )
<< BadFieldError( field, toHex( _header[field].data().toBytes() ) );
throw;
}
}
void BlockHeader::populateFromParent( BlockHeader const& _parent ) {
m_stateRoot = _parent.stateRoot();
m_number = _parent.m_number + 1;
m_parentHash = _parent.m_hash;
m_gasLimit = _parent.m_gasLimit;
m_difficulty = _parent.m_difficulty;
// EIP-3675 (Paris): post-merge blocks must carry difficulty 0. Activation is
// keyed to the parent timestamp, same as the check in SealEngineFace::verify.
if ( ParisForkPatch::isEnabledWhen( static_cast< time_t >( _parent.timestamp() ) ) )
m_difficulty = 0;
m_gasUsed = 0;
m_baseFeePerGas = _parent.m_baseFeePerGas;
// At London activation, the parent may be a pre-London block with baseFeePerGas=0
// (no field 13 in its RLP). Ensure the first post-London block starts at 1.
if ( LondonForkPatch::isEnabledWhen( static_cast< time_t >( m_timestamp ) ) &&
m_baseFeePerGas == 0 )
m_baseFeePerGas = 1;
}
void BlockHeader::verify( Strictness _s, BlockHeader const& _parent, bytesConstRef _block ) const {
if ( m_number > ~( unsigned ) 0 )
BOOST_THROW_EXCEPTION( InvalidNumber() );
if ( _s != CheckNothingNew && m_gasUsed > m_gasLimit )
BOOST_THROW_EXCEPTION(
TooMuchGasUsed() << RequirementError( bigint( m_gasLimit ), bigint( m_gasUsed ) ) );
if ( _parent ) {
if ( m_parentHash && _parent.hash() != m_parentHash )
BOOST_THROW_EXCEPTION( InvalidParentHash() );
if ( m_timestamp < _parent.m_timestamp )
BOOST_THROW_EXCEPTION( InvalidTimestamp() );
if ( m_number != _parent.m_number + 1 )
BOOST_THROW_EXCEPTION( InvalidNumber() );
}
if ( _block ) {
RLP root( _block );
auto txList = root[1];
auto expectedRoot = trieRootOver(
txList.itemCount(), [&]( unsigned i ) { return rlp( i ); },
[&]( unsigned i ) { return txList[i].data().toBytes(); } );
BOOST_LOG( m_loggerDebug ) << "Expected trie root: " << toString( expectedRoot );
if ( m_transactionsRoot != expectedRoot ) {
OverlayDB tm;
GenericTrieDB< OverlayDB > transactionsTrie( &tm );
transactionsTrie.init();
vector< bytesConstRef > txs;
for ( unsigned i = 0; i < txList.itemCount(); ++i ) {
RLPStream k;
k << i;
transactionsTrie.insert( &k.out(), txList[i].data() );
txs.push_back( txList[i].data() );
BOOST_LOG( m_loggerDebug ) << toHex( k.out() ) << toHex( txList[i].data() );
}
BOOST_LOG( m_loggerDebug ) << "trieRootOver" << expectedRoot;
BOOST_LOG( m_loggerDebug ) << "orderedTrieRoot" << orderedTrieRoot( txs );
BOOST_LOG( m_loggerDebug ) << "TrieDB" << transactionsTrie.root();
BOOST_LOG( m_loggerDebug ) << "Contents:";
for ( auto const& t : txs )
BOOST_LOG( m_loggerDebug ) << toHex( t );
BOOST_THROW_EXCEPTION( InvalidTransactionsRoot()
<< Hash256RequirementError( expectedRoot, m_transactionsRoot ) );
}
BOOST_LOG( m_loggerDebug ) << "Expected uncle hash: " << toString( sha3( root[2].data() ) );
if ( m_sha3Uncles != sha3( root[2].data() ) )
BOOST_THROW_EXCEPTION( InvalidUnclesHash() << Hash256RequirementError(
sha3( root[2].data() ), m_sha3Uncles ) );
}
}
void BlockHeader::setTimestamp( int64_t _v ) {
m_timestamp = _v;
if ( useTimestampHack )
m_timestamp = this->number() + 1;
noteDirty();
}
void BlockHeader::setNumber( int64_t _v ) {
m_number = _v;
if ( useTimestampHack )
m_timestamp = _v + 1;
noteDirty();
}
int64_t BlockHeader::timestamp() const {
if ( useTimestampHack )
return m_number + 1;
else
return m_timestamp;
}