github.com/beyonderyue/gochain@v2.2.26+incompatible/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  	"io"
    23  	"math/big"
    24  	"sort"
    25  	"sync/atomic"
    26  	"time"
    27  	"unsafe"
    28  
    29  	"github.com/gochain-io/gochain/common"
    30  	"github.com/gochain-io/gochain/common/hexutil"
    31  	"github.com/gochain-io/gochain/crypto/sha3"
    32  	"github.com/gochain-io/gochain/rlp"
    33  )
    34  
    35  var (
    36  	EmptyRootHash  = DeriveSha(Transactions{})
    37  	EmptyUncleHash = CalcUncleHash(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  	Signers     []common.Address `json:"signers"          gencodec:"required"`
    75  	Voters      []common.Address `json:"voters"           gencodec:"required"`
    76  	Signer      []byte           `json:"signer"           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        *big.Int         `json:"timestamp"        gencodec:"required"`
    86  	Extra       []byte           `json:"extraData"        gencodec:"required"`
    87  	MixDigest   common.Hash      `json:"mixHash"          gencodec:"required"`
    88  	Nonce       BlockNonce       `json:"nonce"            gencodec:"required"`
    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.Big
    98  	Extra      hexutil.Bytes
    99  	Signer     hexutil.Bytes
   100  	Hash       common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON
   101  }
   102  
   103  // Hash returns the block hash of the header, which is simply the keccak256 hash of its
   104  // RLP encoding.
   105  func (h *Header) Hash() common.Hash {
   106  	return rlpHash(h)
   107  }
   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 common.StorageSize(unsafe.Sizeof(*h)) + common.StorageSize(len(h.Extra)+(h.Difficulty.BitLen()+h.Number.BitLen()+h.Time.BitLen())/8)
   113  }
   114  
   115  func rlpHash(x interface{}) (h common.Hash) {
   116  	hw := sha3.NewKeccak256SingleSum()
   117  	rlp.Encode(hw, x)
   118  	hw.Sum(h[:0])
   119  	return h
   120  }
   121  
   122  // Body is a simple (mutable, non-safe) data container for storing and moving
   123  // a block's data contents (transactions and uncles) together.
   124  type Body struct {
   125  	Transactions []*Transaction
   126  	Uncles       []*Header
   127  }
   128  
   129  // Block represents an entire block in the Ethereum blockchain.
   130  type Block struct {
   131  	header *Header
   132  	// Deprecated.
   133  	uncles       []*Header
   134  	transactions Transactions
   135  
   136  	// caches
   137  	hash atomic.Value
   138  	size atomic.Value
   139  
   140  	// Td is used by package core to store the total difficulty
   141  	// of the chain up to and including the block.
   142  	td *big.Int
   143  
   144  	// These fields are used by package eth to track
   145  	// inter-peer block relay.
   146  	ReceivedAt   time.Time
   147  	ReceivedFrom interface{}
   148  }
   149  
   150  // DeprecatedTd is an old relic for extracting the TD of a block. It is in the
   151  // code solely to facilitate upgrading the database from the old format to the
   152  // new, after which it should be deleted. Do not use!
   153  func (b *Block) DeprecatedTd() *big.Int {
   154  	return b.td
   155  }
   156  
   157  // [deprecated by eth/63]
   158  // StorageBlock defines the RLP encoding of a Block stored in the
   159  // state database. The StorageBlock encoding contains fields that
   160  // would otherwise need to be recomputed.
   161  type StorageBlock Block
   162  
   163  // "external" block encoding. used for eth protocol, etc.
   164  type extblock struct {
   165  	Header *Header
   166  	Txs    []*Transaction
   167  	Uncles []*Header
   168  }
   169  
   170  // [deprecated by eth/63]
   171  // "storage" block encoding. used for database.
   172  type storageblock struct {
   173  	Header *Header
   174  	Txs    []*Transaction
   175  	Uncles []*Header
   176  	TD     *big.Int
   177  }
   178  
   179  // NewBlock creates a new block. The input data is copied,
   180  // changes to header and to the field values will not affect the
   181  // block.
   182  //
   183  // The values of TxHash, UncleHash, ReceiptHash and Bloom in header
   184  // are ignored and set to values derived from the given txs, uncles
   185  // and receipts.
   186  func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block {
   187  	b := &Block{header: CopyHeader(header), td: new(big.Int)}
   188  
   189  	// TODO: panic if len(txs) != len(receipts)
   190  	if len(txs) == 0 {
   191  		b.header.TxHash = EmptyRootHash
   192  	} else {
   193  		b.header.TxHash = DeriveSha(Transactions(txs))
   194  		b.transactions = make(Transactions, len(txs))
   195  		copy(b.transactions, txs)
   196  	}
   197  
   198  	if len(receipts) == 0 {
   199  		b.header.ReceiptHash = EmptyRootHash
   200  	} else {
   201  		b.header.ReceiptHash = DeriveSha(Receipts(receipts))
   202  		b.header.Bloom = CreateBloom(receipts)
   203  	}
   204  
   205  	if len(uncles) == 0 {
   206  		b.header.UncleHash = EmptyUncleHash
   207  	} else {
   208  		b.header.UncleHash = CalcUncleHash(uncles)
   209  		b.uncles = make([]*Header, len(uncles))
   210  		for i := range uncles {
   211  			b.uncles[i] = CopyHeader(uncles[i])
   212  		}
   213  	}
   214  
   215  	return b
   216  }
   217  
   218  // NewBlockWith assembles a block with the given header and body. Does not copy.
   219  func NewBlockWith(header *Header, body *Body) *Block {
   220  	return &Block{
   221  		header:       header,
   222  		transactions: body.Transactions,
   223  		uncles:       body.Uncles,
   224  	}
   225  }
   226  
   227  // NewBlockWithHeader creates a block with the given header data. The
   228  // header data is copied, changes to header and to the field values
   229  // will not affect the block.
   230  func NewBlockWithHeader(header *Header) *Block {
   231  	return &Block{header: CopyHeader(header)}
   232  }
   233  
   234  // CopyHeader creates a deep copy of a block header to prevent side effects from
   235  // modifying a header variable.
   236  func CopyHeader(h *Header) *Header {
   237  	cpy := *h
   238  	if cpy.Time = new(big.Int); h.Time != nil {
   239  		cpy.Time.Set(h.Time)
   240  	}
   241  	if cpy.Difficulty = new(big.Int); h.Difficulty != nil {
   242  		cpy.Difficulty.Set(h.Difficulty)
   243  	}
   244  	if cpy.Number = new(big.Int); h.Number != nil {
   245  		cpy.Number.Set(h.Number)
   246  	}
   247  	if len(h.Extra) > 0 {
   248  		cpy.Extra = make([]byte, len(h.Extra))
   249  		copy(cpy.Extra, h.Extra)
   250  	}
   251  	if len(h.Signer) > 0 {
   252  		cpy.Signer = make([]byte, len(h.Signer))
   253  		copy(cpy.Signer, h.Signer)
   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  // Deprecated.
   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() *big.Int       { return new(big.Int).Set(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) Signers() []common.Address { return b.header.Signers }
   316  func (b *Block) Voters() []common.Address  { return b.header.Voters }
   317  func (b *Block) Signer() []byte            { return common.CopyBytes(b.header.Signer) }
   318  func (b *Block) Root() common.Hash         { return b.header.Root }
   319  func (b *Block) ParentHash() common.Hash   { return b.header.ParentHash }
   320  func (b *Block) TxHash() common.Hash       { return b.header.TxHash }
   321  func (b *Block) ReceiptHash() common.Hash  { return b.header.ReceiptHash }
   322  func (b *Block) UncleHash() common.Hash    { return b.header.UncleHash }
   323  func (b *Block) Extra() []byte             { return common.CopyBytes(b.header.Extra) }
   324  
   325  func (b *Block) Header() *Header { return CopyHeader(b.header) }
   326  
   327  // Body returns the non-header content of the block.
   328  func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} }
   329  
   330  // Size returns the true RLP encoded storage size of the block, either by encoding
   331  // and returning it, or returning a previsouly cached value.
   332  func (b *Block) Size() common.StorageSize {
   333  	if size := b.size.Load(); size != nil {
   334  		return size.(common.StorageSize)
   335  	}
   336  	c := writeCounter(0)
   337  	rlp.Encode(&c, b)
   338  	b.size.Store(common.StorageSize(c))
   339  	return common.StorageSize(c)
   340  }
   341  
   342  type writeCounter common.StorageSize
   343  
   344  func (c *writeCounter) Write(b []byte) (int, error) {
   345  	*c += writeCounter(len(b))
   346  	return len(b), nil
   347  }
   348  
   349  func CalcUncleHash(uncles []*Header) common.Hash {
   350  	return rlpHash(uncles)
   351  }
   352  
   353  // WithSeal returns a new block with the data from b but the header replaced with
   354  // the sealed one.
   355  func (b *Block) WithSeal(header *Header) *Block {
   356  	cpy := *header
   357  
   358  	return &Block{
   359  		header:       &cpy,
   360  		transactions: b.transactions,
   361  		uncles:       b.uncles,
   362  	}
   363  }
   364  
   365  // WithBody returns a new block with the given transaction and uncle contents.
   366  func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
   367  	block := &Block{
   368  		header:       CopyHeader(b.header),
   369  		transactions: make([]*Transaction, len(transactions)),
   370  		uncles:       make([]*Header, len(uncles)),
   371  	}
   372  	copy(block.transactions, transactions)
   373  	for i := range uncles {
   374  		block.uncles[i] = CopyHeader(uncles[i])
   375  	}
   376  	return block
   377  }
   378  
   379  // Hash returns the keccak256 hash of b's header.
   380  // The hash is computed on the first call and cached thereafter.
   381  func (b *Block) Hash() common.Hash {
   382  	if hash := b.hash.Load(); hash != nil {
   383  		return hash.(common.Hash)
   384  	}
   385  	v := b.header.Hash()
   386  	b.hash.Store(v)
   387  	return v
   388  }
   389  
   390  type Blocks []*Block
   391  
   392  type BlockBy func(b1, b2 *Block) bool
   393  
   394  func (self BlockBy) Sort(blocks Blocks) {
   395  	bs := blockSorter{
   396  		blocks: blocks,
   397  		by:     self,
   398  	}
   399  	sort.Sort(bs)
   400  }
   401  
   402  type blockSorter struct {
   403  	blocks Blocks
   404  	by     func(b1, b2 *Block) bool
   405  }
   406  
   407  func (self blockSorter) Len() int { return len(self.blocks) }
   408  func (self blockSorter) Swap(i, j int) {
   409  	self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i]
   410  }
   411  func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) }
   412  
   413  func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }