github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/core/types/block.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package types contains data types related to Ethereum consensus. 18 package types 19 20 import ( 21 "encoding/binary" 22 "errors" 23 "fmt" 24 "io" 25 "math/big" 26 "reflect" 27 "sync/atomic" 28 "time" 29 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/common/hexutil" 32 "github.com/ethereum/go-ethereum/crypto" 33 "github.com/ethereum/go-ethereum/rlp" 34 ) 35 36 var ( 37 EmptyRootHash = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") 38 EmptyCodeHash = crypto.Keccak256(nil) 39 40 EmptyUncleHash = rlpHash([]*Header(nil)) 41 ) 42 43 // A BlockNonce is a 64-bit hash which proves (combined with the 44 // mix-hash) that a sufficient amount of computation has been carried 45 // out on a block. 46 type BlockNonce [8]byte 47 48 // EncodeNonce converts the given integer to a block nonce. 49 func EncodeNonce(i uint64) BlockNonce { 50 var n BlockNonce 51 binary.BigEndian.PutUint64(n[:], i) 52 return n 53 } 54 55 // Uint64 returns the integer value of a block nonce. 56 func (n BlockNonce) Uint64() uint64 { 57 return binary.BigEndian.Uint64(n[:]) 58 } 59 60 // MarshalText encodes n as a hex string with 0x prefix. 61 func (n BlockNonce) MarshalText() ([]byte, error) { 62 return hexutil.Bytes(n[:]).MarshalText() 63 } 64 65 // UnmarshalText implements encoding.TextUnmarshaler. 66 func (n *BlockNonce) UnmarshalText(input []byte) error { 67 return hexutil.UnmarshalFixedText("BlockNonce", input, n[:]) 68 } 69 70 //go:generate gencodec -type Header -field-override headerMarshaling -out gen_header_json.go 71 72 // Header represents a block header in the Ethereum blockchain. 73 type Header struct { 74 ParentHash common.Hash `json:"parentHash" gencodec:"required"` 75 UncleHash common.Hash `json:"sha3Uncles" gencodec:"required"` 76 Coinbase common.Address `json:"miner" gencodec:"required"` 77 Root common.Hash `json:"stateRoot" gencodec:"required"` 78 TxHash common.Hash `json:"transactionsRoot" gencodec:"required"` 79 ReceiptHash common.Hash `json:"receiptsRoot" gencodec:"required"` 80 Bloom Bloom `json:"logsBloom" gencodec:"required"` 81 Difficulty *big.Int `json:"difficulty" gencodec:"required"` 82 Number *big.Int `json:"number" gencodec:"required"` 83 GasLimit uint64 `json:"gasLimit" gencodec:"required"` 84 GasUsed uint64 `json:"gasUsed" gencodec:"required"` 85 Time uint64 `json:"timestamp" gencodec:"required"` 86 Extra []byte `json:"extraData" gencodec:"required"` 87 MixDigest common.Hash `json:"mixHash"` 88 Nonce BlockNonce `json:"nonce"` 89 } 90 91 // field type overrides for gencodec 92 type headerMarshaling struct { 93 Difficulty *hexutil.Big 94 Number *hexutil.Big 95 GasLimit hexutil.Uint64 96 GasUsed hexutil.Uint64 97 Time hexutil.Uint64 98 Extra hexutil.Bytes 99 Hash common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON 100 } 101 102 // Hash returns the block hash of the header, which is simply the keccak256 hash of its 103 // RLP encoding. 104 func (h *Header) Hash() common.Hash { 105 return rlpHash(h) 106 } 107 108 var headerSize = common.StorageSize(reflect.TypeOf(Header{}).Size()) 109 110 // Size returns the approximate memory used by all internal contents. It is used 111 // to approximate and limit the memory consumption of various caches. 112 func (h *Header) Size() common.StorageSize { 113 return headerSize + common.StorageSize(len(h.Extra)+(h.Difficulty.BitLen()+h.Number.BitLen())/8) 114 } 115 116 // SanityCheck checks a few basic things -- these checks are way beyond what 117 // any 'sane' production values should hold, and can mainly be used to prevent 118 // that the unbounded fields are stuffed with junk data to add processing 119 // overhead 120 func (h *Header) SanityCheck() error { 121 if h.Number != nil && !h.Number.IsUint64() { 122 return fmt.Errorf("too large block number: bitlen %d", h.Number.BitLen()) 123 } 124 if h.Difficulty != nil { 125 if diffLen := h.Difficulty.BitLen(); diffLen > 80 { 126 return fmt.Errorf("too large block difficulty: bitlen %d", diffLen) 127 } 128 } 129 if eLen := len(h.Extra); eLen > 100*1024 { 130 return fmt.Errorf("too large block extradata: size %d", eLen) 131 } 132 return nil 133 } 134 135 // EmptyBody returns true if there is no additional 'body' to complete the header 136 // that is: no transactions and no uncles. 137 func (h *Header) EmptyBody() bool { 138 return h.TxHash == EmptyRootHash && h.UncleHash == EmptyUncleHash 139 } 140 141 // EmptyReceipts returns true if there are no receipts for this header/block. 142 func (h *Header) EmptyReceipts() bool { 143 return h.ReceiptHash == EmptyRootHash 144 } 145 146 // Body is a simple (mutable, non-safe) data container for storing and moving 147 // a block's data contents (transactions and uncles) together. 148 type Body struct { 149 Transactions []*Transaction 150 Uncles []*Header 151 } 152 153 // Block represents an entire block in the Ethereum blockchain. 154 type Block struct { 155 header *Header 156 uncles []*Header 157 transactions Transactions 158 159 // caches 160 hash atomic.Value 161 size atomic.Value 162 163 // Td is used by package core to store the total difficulty 164 // of the chain up to and including the block. 165 td *big.Int 166 167 // These fields are used by package eth to track 168 // inter-peer block relay. 169 ReceivedAt time.Time 170 ReceivedFrom interface{} 171 } 172 173 // "external" block encoding. used for eth protocol, etc. 174 type extblock struct { 175 Header *Header 176 Txs []*Transaction 177 Uncles []*Header 178 } 179 180 // NewBlock creates a new block. The input data is copied, 181 // changes to header and to the field values will not affect the 182 // block. 183 // 184 // The values of TxHash, UncleHash, ReceiptHash and Bloom in header 185 // are ignored and set to values derived from the given txs, uncles 186 // and receipts. 187 func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt, hasher TrieHasher) *Block { 188 b := &Block{header: CopyHeader(header), td: new(big.Int)} 189 190 // TODO: panic if len(txs) != len(receipts) 191 if len(txs) == 0 { 192 b.header.TxHash = EmptyRootHash 193 } else { 194 b.header.TxHash = DeriveSha(Transactions(txs), hasher) 195 b.transactions = make(Transactions, len(txs)) 196 copy(b.transactions, txs) 197 } 198 199 if len(receipts) == 0 { 200 b.header.ReceiptHash = EmptyRootHash 201 } else { 202 b.header.ReceiptHash = DeriveSha(Receipts(receipts), hasher) 203 b.header.Bloom = CreateBloom(receipts) 204 } 205 206 if len(uncles) == 0 { 207 b.header.UncleHash = EmptyUncleHash 208 } else { 209 b.header.UncleHash = CalcUncleHash(uncles) 210 b.uncles = make([]*Header, len(uncles)) 211 for i := range uncles { 212 b.uncles[i] = CopyHeader(uncles[i]) 213 } 214 } 215 216 return b 217 } 218 219 // NewBlockWithHeader creates a block with the given header data. The 220 // header data is copied, changes to header and to the field values 221 // will not affect the block. 222 func NewBlockWithHeader(header *Header) *Block { 223 return &Block{header: CopyHeader(header)} 224 } 225 226 // CopyHeader creates a deep copy of a block header to prevent side effects from 227 // modifying a header variable. 228 func CopyHeader(h *Header) *Header { 229 cpy := *h 230 if cpy.Difficulty = new(big.Int); h.Difficulty != nil { 231 cpy.Difficulty.Set(h.Difficulty) 232 } 233 if cpy.Number = new(big.Int); h.Number != nil { 234 cpy.Number.Set(h.Number) 235 } 236 if len(h.Extra) > 0 { 237 cpy.Extra = make([]byte, len(h.Extra)) 238 copy(cpy.Extra, h.Extra) 239 } 240 return &cpy 241 } 242 243 // DecodeRLP decodes the Ethereum 244 func (b *Block) DecodeRLP(s *rlp.Stream) error { 245 var eb extblock 246 _, size, _ := s.Kind() 247 if err := s.Decode(&eb); err != nil { 248 return err 249 } 250 b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs 251 b.size.Store(common.StorageSize(rlp.ListSize(size))) 252 return nil 253 } 254 255 // EncodeRLP serializes b into the Ethereum RLP block format. 256 func (b *Block) EncodeRLP(w io.Writer) error { 257 return rlp.Encode(w, extblock{ 258 Header: b.header, 259 Txs: b.transactions, 260 Uncles: b.uncles, 261 }) 262 } 263 264 // TODO: copies 265 266 func (b *Block) Uncles() []*Header { return b.uncles } 267 func (b *Block) Transactions() Transactions { return b.transactions } 268 269 func (b *Block) Transaction(hash common.Hash) *Transaction { 270 for _, transaction := range b.transactions { 271 if transaction.Hash() == hash { 272 return transaction 273 } 274 } 275 return nil 276 } 277 278 func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) } 279 func (b *Block) GasLimit() uint64 { return b.header.GasLimit } 280 func (b *Block) GasUsed() uint64 { return b.header.GasUsed } 281 func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) } 282 func (b *Block) Time() uint64 { return b.header.Time } 283 284 func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } 285 func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } 286 func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) } 287 func (b *Block) Bloom() Bloom { return b.header.Bloom } 288 func (b *Block) Coinbase() common.Address { return b.header.Coinbase } 289 func (b *Block) Root() common.Hash { return b.header.Root } 290 func (b *Block) ParentHash() common.Hash { return b.header.ParentHash } 291 func (b *Block) TxHash() common.Hash { return b.header.TxHash } 292 func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash } 293 func (b *Block) UncleHash() common.Hash { return b.header.UncleHash } 294 func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) } 295 296 func (b *Block) Header() *Header { return CopyHeader(b.header) } 297 298 // Body returns the non-header content of the block. 299 func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} } 300 301 // Size returns the true RLP encoded storage size of the block, either by encoding 302 // and returning it, or returning a previsouly cached value. 303 func (b *Block) Size() common.StorageSize { 304 if size := b.size.Load(); size != nil { 305 return size.(common.StorageSize) 306 } 307 c := writeCounter(0) 308 rlp.Encode(&c, b) 309 b.size.Store(common.StorageSize(c)) 310 return common.StorageSize(c) 311 } 312 313 func (b *Block) SetRoot(root common.Hash) { b.header.Root = root } 314 315 // SanityCheck can be used to prevent that unbounded fields are 316 // stuffed with junk data to add processing overhead 317 func (b *Block) SanityCheck() error { 318 return b.header.SanityCheck() 319 } 320 321 type writeCounter common.StorageSize 322 323 func (c *writeCounter) Write(b []byte) (int, error) { 324 *c += writeCounter(len(b)) 325 return len(b), nil 326 } 327 328 func CalcUncleHash(uncles []*Header) common.Hash { 329 if len(uncles) == 0 { 330 return EmptyUncleHash 331 } 332 return rlpHash(uncles) 333 } 334 335 // WithSeal returns a new block with the data from b but the header replaced with 336 // the sealed one. 337 func (b *Block) WithSeal(header *Header) *Block { 338 cpy := *header 339 340 return &Block{ 341 header: &cpy, 342 transactions: b.transactions, 343 uncles: b.uncles, 344 } 345 } 346 347 // WithBody returns a new block with the given transaction and uncle contents. 348 func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block { 349 block := &Block{ 350 header: CopyHeader(b.header), 351 transactions: make([]*Transaction, len(transactions)), 352 uncles: make([]*Header, len(uncles)), 353 } 354 copy(block.transactions, transactions) 355 for i := range uncles { 356 block.uncles[i] = CopyHeader(uncles[i]) 357 } 358 return block 359 } 360 361 // Hash returns the keccak256 hash of b's header. 362 // The hash is computed on the first call and cached thereafter. 363 func (b *Block) Hash() common.Hash { 364 if hash := b.hash.Load(); hash != nil { 365 return hash.(common.Hash) 366 } 367 v := b.header.Hash() 368 b.hash.Store(v) 369 return v 370 } 371 372 type Blocks []*Block 373 374 type DiffLayer struct { 375 BlockHash common.Hash 376 Number uint64 377 Receipts Receipts // Receipts are duplicated stored to simplify the logic 378 Codes []DiffCode 379 Destructs []common.Address 380 Accounts []DiffAccount 381 Storages []DiffStorage 382 383 DiffHash common.Hash 384 } 385 386 type extDiffLayer struct { 387 BlockHash common.Hash 388 Number uint64 389 Receipts []*ReceiptForStorage // Receipts are duplicated stored to simplify the logic 390 Codes []DiffCode 391 Destructs []common.Address 392 Accounts []DiffAccount 393 Storages []DiffStorage 394 } 395 396 // DecodeRLP decodes the Ethereum 397 func (d *DiffLayer) DecodeRLP(s *rlp.Stream) error { 398 var ed extDiffLayer 399 if err := s.Decode(&ed); err != nil { 400 return err 401 } 402 d.BlockHash, d.Number, d.Codes, d.Destructs, d.Accounts, d.Storages = 403 ed.BlockHash, ed.Number, ed.Codes, ed.Destructs, ed.Accounts, ed.Storages 404 405 d.Receipts = make([]*Receipt, len(ed.Receipts)) 406 for i, storageReceipt := range ed.Receipts { 407 d.Receipts[i] = (*Receipt)(storageReceipt) 408 } 409 return nil 410 } 411 412 // EncodeRLP serializes b into the Ethereum RLP block format. 413 func (d *DiffLayer) EncodeRLP(w io.Writer) error { 414 storageReceipts := make([]*ReceiptForStorage, len(d.Receipts)) 415 for i, receipt := range d.Receipts { 416 storageReceipts[i] = (*ReceiptForStorage)(receipt) 417 } 418 return rlp.Encode(w, extDiffLayer{ 419 BlockHash: d.BlockHash, 420 Number: d.Number, 421 Receipts: storageReceipts, 422 Codes: d.Codes, 423 Destructs: d.Destructs, 424 Accounts: d.Accounts, 425 Storages: d.Storages, 426 }) 427 } 428 429 func (d *DiffLayer) Validate() error { 430 if d.BlockHash == (common.Hash{}) { 431 return errors.New("blockHash can't be empty") 432 } 433 for _, storage := range d.Storages { 434 if len(storage.Keys) != len(storage.Vals) { 435 return errors.New("the length of keys and values mismatch in storage") 436 } 437 } 438 return nil 439 } 440 441 type DiffCode struct { 442 Hash common.Hash 443 Code []byte 444 } 445 446 type DiffAccount struct { 447 Account common.Address 448 Blob []byte 449 } 450 451 type DiffStorage struct { 452 Account common.Address 453 Keys []string 454 Vals [][]byte 455 } 456 457 type DiffAccountsInTx struct { 458 TxHash common.Hash 459 Accounts map[common.Address]*big.Int 460 } 461 462 type DiffAccountsInBlock struct { 463 Number uint64 464 BlockHash common.Hash 465 Transactions []DiffAccountsInTx 466 }