github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/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 "fmt" 23 "io" 24 "math/big" 25 "reflect" 26 "sync/atomic" 27 "time" 28 29 "github.com/zhiqiangxu/go-ethereum/common" 30 "github.com/zhiqiangxu/go-ethereum/common/hexutil" 31 "github.com/zhiqiangxu/go-ethereum/rlp" 32 "golang.org/x/crypto/sha3" 33 ) 34 35 var ( 36 EmptyRootHash = DeriveSha(Transactions{}) 37 EmptyUncleHash = rlpHash([]*Header(nil)) 38 ) 39 40 // A BlockNonce is a 64-bit hash which proves (combined with the 41 // mix-hash) that a sufficient amount of computation has been carried 42 // out on a block. 43 type BlockNonce [8]byte 44 45 // EncodeNonce converts the given integer to a block nonce. 46 func EncodeNonce(i uint64) BlockNonce { 47 var n BlockNonce 48 binary.BigEndian.PutUint64(n[:], i) 49 return n 50 } 51 52 // Uint64 returns the integer value of a block nonce. 53 func (n BlockNonce) Uint64() uint64 { 54 return binary.BigEndian.Uint64(n[:]) 55 } 56 57 // MarshalText encodes n as a hex string with 0x prefix. 58 func (n BlockNonce) MarshalText() ([]byte, error) { 59 return hexutil.Bytes(n[:]).MarshalText() 60 } 61 62 // UnmarshalText implements encoding.TextUnmarshaler. 63 func (n *BlockNonce) UnmarshalText(input []byte) error { 64 return hexutil.UnmarshalFixedText("BlockNonce", input, n[:]) 65 } 66 67 //go:generate gencodec -type Header -field-override headerMarshaling -out gen_header_json.go 68 69 // Header represents a block header in the Ethereum blockchain. 70 type Header struct { 71 ParentHash common.Hash `json:"parentHash" gencodec:"required"` 72 UncleHash common.Hash `json:"sha3Uncles" gencodec:"required"` 73 Coinbase common.Address `json:"miner" gencodec:"required"` 74 Root common.Hash `json:"stateRoot" gencodec:"required"` 75 TxHash common.Hash `json:"transactionsRoot" gencodec:"required"` 76 ReceiptHash common.Hash `json:"receiptsRoot" gencodec:"required"` 77 Bloom Bloom `json:"logsBloom" gencodec:"required"` 78 Difficulty *big.Int `json:"difficulty" gencodec:"required"` 79 Number *big.Int `json:"number" gencodec:"required"` 80 GasLimit uint64 `json:"gasLimit" gencodec:"required"` 81 GasUsed uint64 `json:"gasUsed" gencodec:"required"` 82 Time uint64 `json:"timestamp" gencodec:"required"` 83 Extra []byte `json:"extraData" gencodec:"required"` 84 MixDigest common.Hash `json:"mixHash"` 85 Nonce BlockNonce `json:"nonce"` 86 } 87 88 // field type overrides for gencodec 89 type headerMarshaling struct { 90 Difficulty *hexutil.Big 91 Number *hexutil.Big 92 GasLimit hexutil.Uint64 93 GasUsed hexutil.Uint64 94 Time hexutil.Uint64 95 Extra hexutil.Bytes 96 Hash common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON 97 } 98 99 // Hash returns the block hash of the header, which is simply the keccak256 hash of its 100 // RLP encoding. 101 func (h *Header) Hash() common.Hash { 102 return rlpHash(h) 103 } 104 105 var headerSize = common.StorageSize(reflect.TypeOf(Header{}).Size()) 106 107 // Size returns the approximate memory used by all internal contents. It is used 108 // to approximate and limit the memory consumption of various caches. 109 func (h *Header) Size() common.StorageSize { 110 return headerSize + common.StorageSize(len(h.Extra)+(h.Difficulty.BitLen()+h.Number.BitLen())/8) 111 } 112 113 // SanityCheck checks a few basic things -- these checks are way beyond what 114 // any 'sane' production values should hold, and can mainly be used to prevent 115 // that the unbounded fields are stuffed with junk data to add processing 116 // overhead 117 func (h *Header) SanityCheck() error { 118 if h.Number != nil && !h.Number.IsUint64() { 119 return fmt.Errorf("too large block number: bitlen %d", h.Number.BitLen()) 120 } 121 if h.Difficulty != nil { 122 if diffLen := h.Difficulty.BitLen(); diffLen > 80 { 123 return fmt.Errorf("too large block difficulty: bitlen %d", diffLen) 124 } 125 } 126 if eLen := len(h.Extra); eLen > 100*1024 { 127 return fmt.Errorf("too large block extradata: size %d", eLen) 128 } 129 return nil 130 } 131 132 func rlpHash(x interface{}) (h common.Hash) { 133 hw := sha3.NewLegacyKeccak256() 134 rlp.Encode(hw, x) 135 hw.Sum(h[:0]) 136 return h 137 } 138 139 // Body is a simple (mutable, non-safe) data container for storing and moving 140 // a block's data contents (transactions and uncles) together. 141 type Body struct { 142 Transactions []*Transaction 143 Uncles []*Header 144 } 145 146 // Block represents an entire block in the Ethereum blockchain. 147 type Block struct { 148 header *Header 149 uncles []*Header 150 transactions Transactions 151 152 // caches 153 hash atomic.Value 154 size atomic.Value 155 156 // Td is used by package core to store the total difficulty 157 // of the chain up to and including the block. 158 td *big.Int 159 160 // These fields are used by package eth to track 161 // inter-peer block relay. 162 ReceivedAt time.Time 163 ReceivedFrom interface{} 164 } 165 166 // DeprecatedTd is an old relic for extracting the TD of a block. It is in the 167 // code solely to facilitate upgrading the database from the old format to the 168 // new, after which it should be deleted. Do not use! 169 func (b *Block) DeprecatedTd() *big.Int { 170 return b.td 171 } 172 173 // [deprecated by eth/63] 174 // StorageBlock defines the RLP encoding of a Block stored in the 175 // state database. The StorageBlock encoding contains fields that 176 // would otherwise need to be recomputed. 177 type StorageBlock Block 178 179 // "external" block encoding. used for eth protocol, etc. 180 type extblock struct { 181 Header *Header 182 Txs []*Transaction 183 Uncles []*Header 184 } 185 186 // [deprecated by eth/63] 187 // "storage" block encoding. used for database. 188 type storageblock struct { 189 Header *Header 190 Txs []*Transaction 191 Uncles []*Header 192 TD *big.Int 193 } 194 195 // NewBlock creates a new block. The input data is copied, 196 // changes to header and to the field values will not affect the 197 // block. 198 // 199 // The values of TxHash, UncleHash, ReceiptHash and Bloom in header 200 // are ignored and set to values derived from the given txs, uncles 201 // and receipts. 202 func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block { 203 b := &Block{header: CopyHeader(header), td: new(big.Int)} 204 205 // TODO: panic if len(txs) != len(receipts) 206 if len(txs) == 0 { 207 b.header.TxHash = EmptyRootHash 208 } else { 209 b.header.TxHash = DeriveSha(Transactions(txs)) 210 b.transactions = make(Transactions, len(txs)) 211 copy(b.transactions, txs) 212 } 213 214 if len(receipts) == 0 { 215 b.header.ReceiptHash = EmptyRootHash 216 } else { 217 b.header.ReceiptHash = DeriveSha(Receipts(receipts)) 218 b.header.Bloom = CreateBloom(receipts) 219 } 220 221 if len(uncles) == 0 { 222 b.header.UncleHash = EmptyUncleHash 223 } else { 224 b.header.UncleHash = CalcUncleHash(uncles) 225 b.uncles = make([]*Header, len(uncles)) 226 for i := range uncles { 227 b.uncles[i] = CopyHeader(uncles[i]) 228 } 229 } 230 231 return b 232 } 233 234 // NewBlockWithHeader creates a block with the given header data. The 235 // header data is copied, changes to header and to the field values 236 // will not affect the block. 237 func NewBlockWithHeader(header *Header) *Block { 238 return &Block{header: CopyHeader(header)} 239 } 240 241 // CopyHeader creates a deep copy of a block header to prevent side effects from 242 // modifying a header variable. 243 func CopyHeader(h *Header) *Header { 244 cpy := *h 245 if cpy.Difficulty = new(big.Int); h.Difficulty != nil { 246 cpy.Difficulty.Set(h.Difficulty) 247 } 248 if cpy.Number = new(big.Int); h.Number != nil { 249 cpy.Number.Set(h.Number) 250 } 251 if len(h.Extra) > 0 { 252 cpy.Extra = make([]byte, len(h.Extra)) 253 copy(cpy.Extra, h.Extra) 254 } 255 return &cpy 256 } 257 258 // DecodeRLP decodes the Ethereum 259 func (b *Block) DecodeRLP(s *rlp.Stream) error { 260 var eb extblock 261 _, size, _ := s.Kind() 262 if err := s.Decode(&eb); err != nil { 263 return err 264 } 265 b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs 266 b.size.Store(common.StorageSize(rlp.ListSize(size))) 267 return nil 268 } 269 270 // EncodeRLP serializes b into the Ethereum RLP block format. 271 func (b *Block) EncodeRLP(w io.Writer) error { 272 return rlp.Encode(w, extblock{ 273 Header: b.header, 274 Txs: b.transactions, 275 Uncles: b.uncles, 276 }) 277 } 278 279 // [deprecated by eth/63] 280 func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error { 281 var sb storageblock 282 if err := s.Decode(&sb); err != nil { 283 return err 284 } 285 b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD 286 return nil 287 } 288 289 // TODO: copies 290 291 func (b *Block) Uncles() []*Header { return b.uncles } 292 func (b *Block) Transactions() Transactions { return b.transactions } 293 294 func (b *Block) Transaction(hash common.Hash) *Transaction { 295 for _, transaction := range b.transactions { 296 if transaction.Hash() == hash { 297 return transaction 298 } 299 } 300 return nil 301 } 302 303 func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) } 304 func (b *Block) GasLimit() uint64 { return b.header.GasLimit } 305 func (b *Block) GasUsed() uint64 { return b.header.GasUsed } 306 func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) } 307 func (b *Block) Time() uint64 { return b.header.Time } 308 309 func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } 310 func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } 311 func (b *Block) Nonce() uint64 { return binary.BigEndian.Uint64(b.header.Nonce[:]) } 312 func (b *Block) Bloom() Bloom { return b.header.Bloom } 313 func (b *Block) Coinbase() common.Address { return b.header.Coinbase } 314 func (b *Block) Root() common.Hash { return b.header.Root } 315 func (b *Block) ParentHash() common.Hash { return b.header.ParentHash } 316 func (b *Block) TxHash() common.Hash { return b.header.TxHash } 317 func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash } 318 func (b *Block) UncleHash() common.Hash { return b.header.UncleHash } 319 func (b *Block) Extra() []byte { return common.CopyBytes(b.header.Extra) } 320 321 func (b *Block) Header() *Header { return CopyHeader(b.header) } 322 323 // Body returns the non-header content of the block. 324 func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} } 325 326 // Size returns the true RLP encoded storage size of the block, either by encoding 327 // and returning it, or returning a previsouly cached value. 328 func (b *Block) Size() common.StorageSize { 329 if size := b.size.Load(); size != nil { 330 return size.(common.StorageSize) 331 } 332 c := writeCounter(0) 333 rlp.Encode(&c, b) 334 b.size.Store(common.StorageSize(c)) 335 return common.StorageSize(c) 336 } 337 338 // SanityCheck can be used to prevent that unbounded fields are 339 // stuffed with junk data to add processing overhead 340 func (b *Block) SanityCheck() error { 341 return b.header.SanityCheck() 342 } 343 344 type writeCounter common.StorageSize 345 346 func (c *writeCounter) Write(b []byte) (int, error) { 347 *c += writeCounter(len(b)) 348 return len(b), nil 349 } 350 351 func CalcUncleHash(uncles []*Header) common.Hash { 352 if len(uncles) == 0 { 353 return EmptyUncleHash 354 } 355 return rlpHash(uncles) 356 } 357 358 // WithSeal returns a new block with the data from b but the header replaced with 359 // the sealed one. 360 func (b *Block) WithSeal(header *Header) *Block { 361 cpy := *header 362 363 return &Block{ 364 header: &cpy, 365 transactions: b.transactions, 366 uncles: b.uncles, 367 } 368 } 369 370 // WithBody returns a new block with the given transaction and uncle contents. 371 func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block { 372 block := &Block{ 373 header: CopyHeader(b.header), 374 transactions: make([]*Transaction, len(transactions)), 375 uncles: make([]*Header, len(uncles)), 376 } 377 copy(block.transactions, transactions) 378 for i := range uncles { 379 block.uncles[i] = CopyHeader(uncles[i]) 380 } 381 return block 382 } 383 384 // Hash returns the keccak256 hash of b's header. 385 // The hash is computed on the first call and cached thereafter. 386 func (b *Block) Hash() common.Hash { 387 if hash := b.hash.Load(); hash != nil { 388 return hash.(common.Hash) 389 } 390 v := b.header.Hash() 391 b.hash.Store(v) 392 return v 393 } 394 395 type Blocks []*Block