github.com/etsc3259/etsc@v0.0.0-20190109113336-a9c2c10f9c95/core/types/block.go (about)

     1  // Copyright 2014 The go-etsc Authors
     2  // This file is part of the go-etsc library.
     3  //
     4  // The go-etsc 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-etsc 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-etsc library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package types contains data types related to etsc 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/ETSC3259/etsc/common"
    30  	"github.com/ETSC3259/etsc/common/hexutil"
    31  	"github.com/ETSC3259/etsc/crypto/sha3"
    32  	"github.com/ETSC3259/etsc/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 etsc 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        *big.Int       `json:"timestamp"        gencodec:"required"`
    83  	Extra       []byte         `json:"extraData"        gencodec:"required"`
    84  	MixDigest   common.Hash    `json:"mixHash"          gencodec:"required"`
    85  	Nonce       BlockNonce     `json:"nonce"            gencodec:"required"`
    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.Big
    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  // Size returns the approximate memory used by all internal contents. It is used
   106  // to approximate and limit the memory consumption of various caches.
   107  func (h *Header) Size() common.StorageSize {
   108  	return common.StorageSize(unsafe.Sizeof(*h)) + common.StorageSize(len(h.Extra)+(h.Difficulty.BitLen()+h.Number.BitLen()+h.Time.BitLen())/8)
   109  }
   110  
   111  func rlpHash(x interface{}) (h common.Hash) {
   112  	hw := sha3.NewKeccak256()
   113  	rlp.Encode(hw, x)
   114  	hw.Sum(h[:0])
   115  	return h
   116  }
   117  
   118  // Body is a simple (mutable, non-safe) data container for storing and moving
   119  // a block's data contents (transactions and uncles) together.
   120  type Body struct {
   121  	Transactions []*Transaction
   122  	Uncles       []*Header
   123  }
   124  
   125  // Block represents an entire block in the etsc blockchain.
   126  type Block struct {
   127  	header       *Header
   128  	uncles       []*Header
   129  	transactions Transactions
   130  
   131  	// caches
   132  	hash atomic.Value
   133  	size atomic.Value
   134  
   135  	// Td is used by package core to store the total difficulty
   136  	// of the chain up to and including the block.
   137  	td *big.Int
   138  
   139  	// These fields are used by package etsc to track
   140  	// inter-peer block relay.
   141  	ReceivedAt   time.Time
   142  	ReceivedFrom interface{}
   143  }
   144  
   145  // DeprecatedTd is an old relic for extracting the TD of a block. It is in the
   146  // code solely to facilitate upgrading the database from the old format to the
   147  // new, after which it should be deleted. Do not use!
   148  func (b *Block) DeprecatedTd() *big.Int {
   149  	return b.td
   150  }
   151  
   152  // [deprecated by etsc/63]
   153  // StorageBlock defines the RLP encoding of a Block stored in the
   154  // state database. The StorageBlock encoding contains fields that
   155  // would otherwise need to be recomputed.
   156  type StorageBlock Block
   157  
   158  // "external" block encoding. used for etsc protocol, etc.
   159  type extblock struct {
   160  	Header *Header
   161  	Txs    []*Transaction
   162  	Uncles []*Header
   163  }
   164  
   165  // [deprecated by etsc/63]
   166  // "storage" block encoding. used for database.
   167  type storageblock struct {
   168  	Header *Header
   169  	Txs    []*Transaction
   170  	Uncles []*Header
   171  	TD     *big.Int
   172  }
   173  
   174  // NewBlock creates a new block. The input data is copied,
   175  // changes to header and to the field values will not affect the
   176  // block.
   177  //
   178  // The values of TxHash, UncleHash, ReceiptHash and Bloom in header
   179  // are ignored and set to values derived from the given txs, uncles
   180  // and receipts.
   181  func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block {
   182  	b := &Block{header: CopyHeader(header), td: new(big.Int)}
   183  
   184  	// TODO: panic if len(txs) != len(receipts)
   185  	if len(txs) == 0 {
   186  		b.header.TxHash = EmptyRootHash
   187  	} else {
   188  		b.header.TxHash = DeriveSha(Transactions(txs))
   189  		b.transactions = make(Transactions, len(txs))
   190  		copy(b.transactions, txs)
   191  	}
   192  
   193  	if len(receipts) == 0 {
   194  		b.header.ReceiptHash = EmptyRootHash
   195  	} else {
   196  		b.header.ReceiptHash = DeriveSha(Receipts(receipts))
   197  		b.header.Bloom = CreateBloom(receipts)
   198  	}
   199  
   200  	if len(uncles) == 0 {
   201  		b.header.UncleHash = EmptyUncleHash
   202  	} else {
   203  		b.header.UncleHash = CalcUncleHash(uncles)
   204  		b.uncles = make([]*Header, len(uncles))
   205  		for i := range uncles {
   206  			b.uncles[i] = CopyHeader(uncles[i])
   207  		}
   208  	}
   209  
   210  	return b
   211  }
   212  
   213  // NewBlockWithHeader creates a block with the given header data. The
   214  // header data is copied, changes to header and to the field values
   215  // will not affect the block.
   216  func NewBlockWithHeader(header *Header) *Block {
   217  	return &Block{header: CopyHeader(header)}
   218  }
   219  
   220  // CopyHeader creates a deep copy of a block header to prevent side effects from
   221  // modifying a header variable.
   222  func CopyHeader(h *Header) *Header {
   223  	cpy := *h
   224  	if cpy.Time = new(big.Int); h.Time != nil {
   225  		cpy.Time.Set(h.Time)
   226  	}
   227  	if cpy.Difficulty = new(big.Int); h.Difficulty != nil {
   228  		cpy.Difficulty.Set(h.Difficulty)
   229  	}
   230  	if cpy.Number = new(big.Int); h.Number != nil {
   231  		cpy.Number.Set(h.Number)
   232  	}
   233  	if len(h.Extra) > 0 {
   234  		cpy.Extra = make([]byte, len(h.Extra))
   235  		copy(cpy.Extra, h.Extra)
   236  	}
   237  	return &cpy
   238  }
   239  
   240  // DecodeRLP decodes the etsc
   241  func (b *Block) DecodeRLP(s *rlp.Stream) error {
   242  	var eb extblock
   243  	_, size, _ := s.Kind()
   244  	if err := s.Decode(&eb); err != nil {
   245  		return err
   246  	}
   247  	b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs
   248  	b.size.Store(common.StorageSize(rlp.ListSize(size)))
   249  	return nil
   250  }
   251  
   252  // EncodeRLP serializes b into the etsc RLP block format.
   253  func (b *Block) EncodeRLP(w io.Writer) error {
   254  	return rlp.Encode(w, extblock{
   255  		Header: b.header,
   256  		Txs:    b.transactions,
   257  		Uncles: b.uncles,
   258  	})
   259  }
   260  
   261  // [deprecated by etsc/63]
   262  func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
   263  	var sb storageblock
   264  	if err := s.Decode(&sb); err != nil {
   265  		return err
   266  	}
   267  	b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD
   268  	return nil
   269  }
   270  
   271  // TODO: copies
   272  
   273  func (b *Block) Uncles() []*Header          { return b.uncles }
   274  func (b *Block) Transactions() Transactions { return b.transactions }
   275  
   276  func (b *Block) Transaction(hash common.Hash) *Transaction {
   277  	for _, transaction := range b.transactions {
   278  		if transaction.Hash() == hash {
   279  			return transaction
   280  		}
   281  	}
   282  	return nil
   283  }
   284  
   285  func (b *Block) Number() *big.Int     { return new(big.Int).Set(b.header.Number) }
   286  func (b *Block) GasLimit() uint64     { return b.header.GasLimit }
   287  func (b *Block) GasUsed() uint64      { return b.header.GasUsed }
   288  func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) }
   289  func (b *Block) Time() *big.Int       { return new(big.Int).Set(b.header.Time) }
   290  
   291  func (b *Block) NumberU64() uint64        { return b.header.Number.Uint64() }
   292  func (b *Block) MixDigest() common.Hash   { return b.header.MixDigest }
   293  func (b *Block) Nonce() uint64            { return binary.BigEndian.Uint64(b.header.Nonce[:]) }
   294  func (b *Block) Bloom() Bloom             { return b.header.Bloom }
   295  func (b *Block) Coinbase() common.Address { return b.header.Coinbase }
   296  func (b *Block) Root() common.Hash        { return b.header.Root }
   297  func (b *Block) ParentHash() common.Hash  { return b.header.ParentHash }
   298  func (b *Block) TxHash() common.Hash      { return b.header.TxHash }
   299  func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash }
   300  func (b *Block) UncleHash() common.Hash   { return b.header.UncleHash }
   301  func (b *Block) Extra() []byte            { return common.CopyBytes(b.header.Extra) }
   302  
   303  func (b *Block) Header() *Header { return CopyHeader(b.header) }
   304  
   305  // Body returns the non-header content of the block.
   306  func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} }
   307  
   308  // Size returns the true RLP encoded storage size of the block, either by encoding
   309  // and returning it, or returning a previsouly cached value.
   310  func (b *Block) Size() common.StorageSize {
   311  	if size := b.size.Load(); size != nil {
   312  		return size.(common.StorageSize)
   313  	}
   314  	c := writeCounter(0)
   315  	rlp.Encode(&c, b)
   316  	b.size.Store(common.StorageSize(c))
   317  	return common.StorageSize(c)
   318  }
   319  
   320  type writeCounter common.StorageSize
   321  
   322  func (c *writeCounter) Write(b []byte) (int, error) {
   323  	*c += writeCounter(len(b))
   324  	return len(b), nil
   325  }
   326  
   327  func CalcUncleHash(uncles []*Header) common.Hash {
   328  	return rlpHash(uncles)
   329  }
   330  
   331  // WithSeal returns a new block with the data from b but the header replaced with
   332  // the sealed one.
   333  func (b *Block) WithSeal(header *Header) *Block {
   334  	cpy := *header
   335  
   336  	return &Block{
   337  		header:       &cpy,
   338  		transactions: b.transactions,
   339  		uncles:       b.uncles,
   340  	}
   341  }
   342  
   343  // WithBody returns a new block with the given transaction and uncle contents.
   344  func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
   345  	block := &Block{
   346  		header:       CopyHeader(b.header),
   347  		transactions: make([]*Transaction, len(transactions)),
   348  		uncles:       make([]*Header, len(uncles)),
   349  	}
   350  	copy(block.transactions, transactions)
   351  	for i := range uncles {
   352  		block.uncles[i] = CopyHeader(uncles[i])
   353  	}
   354  	return block
   355  }
   356  
   357  // Hash returns the keccak256 hash of b's header.
   358  // The hash is computed on the first call and cached thereafter.
   359  func (b *Block) Hash() common.Hash {
   360  	if hash := b.hash.Load(); hash != nil {
   361  		return hash.(common.Hash)
   362  	}
   363  	v := b.header.Hash()
   364  	b.hash.Store(v)
   365  	return v
   366  }
   367  
   368  type Blocks []*Block
   369  
   370  type BlockBy func(b1, b2 *Block) bool
   371  
   372  func (self BlockBy) Sort(blocks Blocks) {
   373  	bs := blockSorter{
   374  		blocks: blocks,
   375  		by:     self,
   376  	}
   377  	sort.Sort(bs)
   378  }
   379  
   380  type blockSorter struct {
   381  	blocks Blocks
   382  	by     func(b1, b2 *Block) bool
   383  }
   384  
   385  func (self blockSorter) Len() int { return len(self.blocks) }
   386  func (self blockSorter) Swap(i, j int) {
   387  	self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i]
   388  }
   389  func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) }
   390  
   391  func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }