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