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