block.go 15.2 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU Lesser General Public License for more details.
//
// 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/>.
F
Felix Lange 已提交
16

17
// Package types contains data types related to Ethereum consensus.
18
package types
O
obscuren 已提交
19 20

import (
O
obscuren 已提交
21
	"encoding/binary"
22
	"encoding/json"
23
	"errors"
O
obscuren 已提交
24
	"fmt"
25
	"io"
O
obscuren 已提交
26
	"math/big"
O
obscuren 已提交
27
	"sort"
28
	"sync/atomic"
O
obscuren 已提交
29
	"time"
O
obscuren 已提交
30

O
obscuren 已提交
31
	"github.com/ethereum/go-ethereum/common"
32
	"github.com/ethereum/go-ethereum/common/hexutil"
33
	"github.com/ethereum/go-ethereum/crypto/sha3"
O
obscuren 已提交
34
	"github.com/ethereum/go-ethereum/rlp"
O
obscuren 已提交
35 36
)

37 38 39 40 41 42 43 44 45 46 47
var (
	EmptyRootHash  = DeriveSha(Transactions{})
	EmptyUncleHash = CalcUncleHash(nil)
)

var (
	errMissingHeaderMixDigest = errors.New("missing mixHash in JSON block header")
	errMissingHeaderFields    = errors.New("missing required JSON block header fields")
	errBadNonceSize           = errors.New("invalid block nonce size, want 8 bytes")
)

F
Felix Lange 已提交
48
// A BlockNonce is a 64-bit hash which proves (combined with the
L
Leif Jurvetson 已提交
49
// mix-hash) that a sufficient amount of computation has been carried
F
Felix Lange 已提交
50 51
// out on a block.
type BlockNonce [8]byte
O
obscuren 已提交
52

53
// EncodeNonce converts the given integer to a block nonce.
F
Felix Lange 已提交
54 55 56 57
func EncodeNonce(i uint64) BlockNonce {
	var n BlockNonce
	binary.BigEndian.PutUint64(n[:], i)
	return n
58 59
}

60
// Uint64 returns the integer value of a block nonce.
F
Felix Lange 已提交
61 62
func (n BlockNonce) Uint64() uint64 {
	return binary.BigEndian.Uint64(n[:])
63 64
}

65
// MarshalJSON implements json.Marshaler
66
func (n BlockNonce) MarshalJSON() ([]byte, error) {
67
	return hexutil.Bytes(n[:]).MarshalJSON()
68 69
}

70 71
// UnmarshalJSON implements json.Unmarshaler
func (n *BlockNonce) UnmarshalJSON(input []byte) error {
72
	return hexutil.UnmarshalJSON("BlockNonce", input, n[:])
73 74
}

75
// Header represents a block header in the Ethereum blockchain.
F
Felix Lange 已提交
76 77 78 79 80 81 82 83 84 85 86 87
type Header struct {
	ParentHash  common.Hash    // Hash to the previous block
	UncleHash   common.Hash    // Uncles of this block
	Coinbase    common.Address // The coin base address
	Root        common.Hash    // Block Trie state
	TxHash      common.Hash    // Tx sha
	ReceiptHash common.Hash    // Receipt sha
	Bloom       Bloom          // Bloom
	Difficulty  *big.Int       // Difficulty for the current block
	Number      *big.Int       // The block number
	GasLimit    *big.Int       // Gas limit
	GasUsed     *big.Int       // Gas used
88
	Time        *big.Int       // Creation time
F
Felix Lange 已提交
89 90 91 92 93
	Extra       []byte         // Extra data
	MixDigest   common.Hash    // for quick difficulty verification
	Nonce       BlockNonce
}

94 95 96 97 98 99
type jsonHeader struct {
	ParentHash  *common.Hash    `json:"parentHash"`
	UncleHash   *common.Hash    `json:"sha3Uncles"`
	Coinbase    *common.Address `json:"miner"`
	Root        *common.Hash    `json:"stateRoot"`
	TxHash      *common.Hash    `json:"transactionsRoot"`
100
	ReceiptHash *common.Hash    `json:"receiptsRoot"`
101
	Bloom       *Bloom          `json:"logsBloom"`
102 103 104 105 106 107
	Difficulty  *hexutil.Big    `json:"difficulty"`
	Number      *hexutil.Big    `json:"number"`
	GasLimit    *hexutil.Big    `json:"gasLimit"`
	GasUsed     *hexutil.Big    `json:"gasUsed"`
	Time        *hexutil.Big    `json:"timestamp"`
	Extra       *hexutil.Bytes  `json:"extraData"`
108 109 110 111 112 113
	MixDigest   *common.Hash    `json:"mixHash"`
	Nonce       *BlockNonce     `json:"nonce"`
}

// Hash returns the block hash of the header, which is simply the keccak256 hash of its
// RLP encoding.
F
Felix Lange 已提交
114 115 116 117
func (h *Header) Hash() common.Hash {
	return rlpHash(h)
}

118
// HashNoNonce returns the hash which is used as input for the proof-of-work search.
F
Felix Lange 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
func (h *Header) HashNoNonce() common.Hash {
	return rlpHash([]interface{}{
		h.ParentHash,
		h.UncleHash,
		h.Coinbase,
		h.Root,
		h.TxHash,
		h.ReceiptHash,
		h.Bloom,
		h.Difficulty,
		h.Number,
		h.GasLimit,
		h.GasUsed,
		h.Time,
		h.Extra,
	})
O
obscuren 已提交
135 136
}

137 138 139 140 141 142 143 144 145 146
// MarshalJSON encodes headers into the web3 RPC response block format.
func (h *Header) MarshalJSON() ([]byte, error) {
	return json.Marshal(&jsonHeader{
		ParentHash:  &h.ParentHash,
		UncleHash:   &h.UncleHash,
		Coinbase:    &h.Coinbase,
		Root:        &h.Root,
		TxHash:      &h.TxHash,
		ReceiptHash: &h.ReceiptHash,
		Bloom:       &h.Bloom,
147 148 149 150 151 152
		Difficulty:  (*hexutil.Big)(h.Difficulty),
		Number:      (*hexutil.Big)(h.Number),
		GasLimit:    (*hexutil.Big)(h.GasLimit),
		GasUsed:     (*hexutil.Big)(h.GasUsed),
		Time:        (*hexutil.Big)(h.Time),
		Extra:       (*hexutil.Bytes)(&h.Extra),
153 154 155
		MixDigest:   &h.MixDigest,
		Nonce:       &h.Nonce,
	})
156 157
}

158 159 160 161 162
// UnmarshalJSON decodes headers from the web3 RPC response block format.
func (h *Header) UnmarshalJSON(input []byte) error {
	var dec jsonHeader
	if err := json.Unmarshal(input, &dec); err != nil {
		return err
163
	}
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	// Ensure that all fields are set. MixDigest is checked separately because
	// it is a recent addition to the spec (as of August 2016) and older RPC server
	// implementations might not provide it.
	if dec.MixDigest == nil {
		return errMissingHeaderMixDigest
	}
	if dec.ParentHash == nil || dec.UncleHash == nil || dec.Coinbase == nil ||
		dec.Root == nil || dec.TxHash == nil || dec.ReceiptHash == nil ||
		dec.Bloom == nil || dec.Difficulty == nil || dec.Number == nil ||
		dec.GasLimit == nil || dec.GasUsed == nil || dec.Time == nil ||
		dec.Extra == nil || dec.Nonce == nil {
		return errMissingHeaderFields
	}
	// Assign all values.
	h.ParentHash = *dec.ParentHash
	h.UncleHash = *dec.UncleHash
	h.Coinbase = *dec.Coinbase
	h.Root = *dec.Root
	h.TxHash = *dec.TxHash
	h.ReceiptHash = *dec.ReceiptHash
	h.Bloom = *dec.Bloom
	h.Difficulty = (*big.Int)(dec.Difficulty)
	h.Number = (*big.Int)(dec.Number)
	h.GasLimit = (*big.Int)(dec.GasLimit)
	h.GasUsed = (*big.Int)(dec.GasUsed)
	h.Time = (*big.Int)(dec.Time)
	h.Extra = *dec.Extra
	h.MixDigest = *dec.MixDigest
	h.Nonce = *dec.Nonce
	return nil
194 195
}

196 197 198 199 200
func rlpHash(x interface{}) (h common.Hash) {
	hw := sha3.NewKeccak256()
	rlp.Encode(hw, x)
	hw.Sum(h[:0])
	return h
O
obscuren 已提交
201 202
}

203 204 205 206 207 208 209
// Body is a simple (mutable, non-safe) data container for storing and moving
// a block's data contents (transactions and uncles) together.
type Body struct {
	Transactions []*Transaction
	Uncles       []*Header
}

210
// Block represents an entire block in the Ethereum blockchain.
O
obscuren 已提交
211
type Block struct {
O
obscuren 已提交
212 213 214
	header       *Header
	uncles       []*Header
	transactions Transactions
O
obscuren 已提交
215

216 217 218 219 220 221
	// caches
	hash atomic.Value
	size atomic.Value

	// Td is used by package core to store the total difficulty
	// of the chain up to and including the block.
222
	td *big.Int
223

F
Felix Lange 已提交
224 225 226 227
	// These fields are used by package eth to track
	// inter-peer block relay.
	ReceivedAt   time.Time
	ReceivedFrom interface{}
O
obscuren 已提交
228 229
}

230 231 232 233 234 235 236
// DeprecatedTd is an old relic for extracting the TD of a block. It is in the
// code solely to facilitate upgrading the database from the old format to the
// new, after which it should be deleted. Do not use!
func (b *Block) DeprecatedTd() *big.Int {
	return b.td
}

237
// [deprecated by eth/63]
238 239 240 241 242 243 244 245 246 247 248 249
// StorageBlock defines the RLP encoding of a Block stored in the
// state database. The StorageBlock encoding contains fields that
// would otherwise need to be recomputed.
type StorageBlock Block

// "external" block encoding. used for eth protocol, etc.
type extblock struct {
	Header *Header
	Txs    []*Transaction
	Uncles []*Header
}

250
// [deprecated by eth/63]
251 252 253 254 255 256 257 258
// "storage" block encoding. used for database.
type storageblock struct {
	Header *Header
	Txs    []*Transaction
	Uncles []*Header
	TD     *big.Int
}

F
Felix Lange 已提交
259 260 261 262 263 264 265 266
// NewBlock creates a new block. The input data is copied,
// changes to header and to the field values will not affect the
// block.
//
// The values of TxHash, UncleHash, ReceiptHash and Bloom in header
// are ignored and set to values derived from the given txs, uncles
// and receipts.
func NewBlock(header *Header, txs []*Transaction, uncles []*Header, receipts []*Receipt) *Block {
267
	b := &Block{header: CopyHeader(header), td: new(big.Int)}
F
Felix Lange 已提交
268 269 270

	// TODO: panic if len(txs) != len(receipts)
	if len(txs) == 0 {
271
		b.header.TxHash = EmptyRootHash
F
Felix Lange 已提交
272 273 274 275
	} else {
		b.header.TxHash = DeriveSha(Transactions(txs))
		b.transactions = make(Transactions, len(txs))
		copy(b.transactions, txs)
O
obscuren 已提交
276
	}
O
obscuren 已提交
277

F
Felix Lange 已提交
278
	if len(receipts) == 0 {
279
		b.header.ReceiptHash = EmptyRootHash
F
Felix Lange 已提交
280 281 282 283
	} else {
		b.header.ReceiptHash = DeriveSha(Receipts(receipts))
		b.header.Bloom = CreateBloom(receipts)
	}
O
obscuren 已提交
284

F
Felix Lange 已提交
285
	if len(uncles) == 0 {
286
		b.header.UncleHash = EmptyUncleHash
F
Felix Lange 已提交
287 288 289 290
	} else {
		b.header.UncleHash = CalcUncleHash(uncles)
		b.uncles = make([]*Header, len(uncles))
		for i := range uncles {
291
			b.uncles[i] = CopyHeader(uncles[i])
F
Felix Lange 已提交
292 293 294 295
		}
	}

	return b
O
obscuren 已提交
296 297
}

F
Felix Lange 已提交
298 299 300
// NewBlockWithHeader creates a block with the given header data. The
// header data is copied, changes to header and to the field values
// will not affect the block.
O
obscuren 已提交
301
func NewBlockWithHeader(header *Header) *Block {
302
	return &Block{header: CopyHeader(header)}
F
Felix Lange 已提交
303 304
}

305 306 307
// CopyHeader creates a deep copy of a block header to prevent side effects from
// modifying a header variable.
func CopyHeader(h *Header) *Header {
F
Felix Lange 已提交
308
	cpy := *h
309 310 311
	if cpy.Time = new(big.Int); h.Time != nil {
		cpy.Time.Set(h.Time)
	}
F
Felix Lange 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	if cpy.Difficulty = new(big.Int); h.Difficulty != nil {
		cpy.Difficulty.Set(h.Difficulty)
	}
	if cpy.Number = new(big.Int); h.Number != nil {
		cpy.Number.Set(h.Number)
	}
	if cpy.GasLimit = new(big.Int); h.GasLimit != nil {
		cpy.GasLimit.Set(h.GasLimit)
	}
	if cpy.GasUsed = new(big.Int); h.GasUsed != nil {
		cpy.GasUsed.Set(h.GasUsed)
	}
	if len(h.Extra) > 0 {
		cpy.Extra = make([]byte, len(h.Extra))
		copy(cpy.Extra, h.Extra)
	}
	return &cpy
O
obscuren 已提交
329 330
}

331
// DecodeRLP decodes the Ethereum
F
Felix Lange 已提交
332
func (b *Block) DecodeRLP(s *rlp.Stream) error {
333
	var eb extblock
334
	_, size, _ := s.Kind()
335 336
	if err := s.Decode(&eb); err != nil {
		return err
O
obscuren 已提交
337
	}
F
Felix Lange 已提交
338
	b.header, b.uncles, b.transactions = eb.Header, eb.Uncles, eb.Txs
339
	b.size.Store(common.StorageSize(rlp.ListSize(size)))
340 341 342
	return nil
}

343
// EncodeRLP serializes b into the Ethereum RLP block format.
344
func (b *Block) EncodeRLP(w io.Writer) error {
345
	return rlp.Encode(w, extblock{
F
Felix Lange 已提交
346 347 348
		Header: b.header,
		Txs:    b.transactions,
		Uncles: b.uncles,
349 350 351
	})
}

352
// [deprecated by eth/63]
F
Felix Lange 已提交
353
func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
354 355
	var sb storageblock
	if err := s.Decode(&sb); err != nil {
O
obscuren 已提交
356 357
		return err
	}
358
	b.header, b.uncles, b.transactions, b.td = sb.Header, sb.Uncles, sb.Txs, sb.TD
O
obscuren 已提交
359
	return nil
O
obscuren 已提交
360 361
}

F
Felix Lange 已提交
362
// TODO: copies
363

F
Felix Lange 已提交
364 365
func (b *Block) Uncles() []*Header          { return b.uncles }
func (b *Block) Transactions() Transactions { return b.transactions }
366

F
Felix Lange 已提交
367 368
func (b *Block) Transaction(hash common.Hash) *Transaction {
	for _, transaction := range b.transactions {
369
		if transaction.Hash() == hash {
O
obscuren 已提交
370
			return transaction
O
obscuren 已提交
371 372
		}
	}
O
obscuren 已提交
373
	return nil
O
obscuren 已提交
374 375
}

F
Felix Lange 已提交
376 377 378 379
func (b *Block) Number() *big.Int     { return new(big.Int).Set(b.header.Number) }
func (b *Block) GasLimit() *big.Int   { return new(big.Int).Set(b.header.GasLimit) }
func (b *Block) GasUsed() *big.Int    { return new(big.Int).Set(b.header.GasUsed) }
func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) }
380
func (b *Block) Time() *big.Int       { return new(big.Int).Set(b.header.Time) }
O
obscuren 已提交
381

F
Felix Lange 已提交
382 383 384 385 386 387 388 389 390 391 392
func (b *Block) NumberU64() uint64        { return b.header.Number.Uint64() }
func (b *Block) MixDigest() common.Hash   { return b.header.MixDigest }
func (b *Block) Nonce() uint64            { return binary.BigEndian.Uint64(b.header.Nonce[:]) }
func (b *Block) Bloom() Bloom             { return b.header.Bloom }
func (b *Block) Coinbase() common.Address { return b.header.Coinbase }
func (b *Block) Root() common.Hash        { return b.header.Root }
func (b *Block) ParentHash() common.Hash  { return b.header.ParentHash }
func (b *Block) TxHash() common.Hash      { return b.header.TxHash }
func (b *Block) ReceiptHash() common.Hash { return b.header.ReceiptHash }
func (b *Block) UncleHash() common.Hash   { return b.header.UncleHash }
func (b *Block) Extra() []byte            { return common.CopyBytes(b.header.Extra) }
O
obscuren 已提交
393

394
func (b *Block) Header() *Header { return CopyHeader(b.header) }
O
obscuren 已提交
395

396 397 398
// Body returns the non-header content of the block.
func (b *Block) Body() *Body { return &Body{b.transactions, b.uncles} }

F
Felix Lange 已提交
399 400
func (b *Block) HashNoNonce() common.Hash {
	return b.header.HashNoNonce()
401
}
O
obscuren 已提交
402

F
Felix Lange 已提交
403
func (b *Block) Size() common.StorageSize {
404 405 406
	if size := b.size.Load(); size != nil {
		return size.(common.StorageSize)
	}
407
	c := writeCounter(0)
F
Felix Lange 已提交
408
	rlp.Encode(&c, b)
409
	b.size.Store(common.StorageSize(c))
410 411 412 413 414 415 416 417 418 419
	return common.StorageSize(c)
}

type writeCounter common.StorageSize

func (c *writeCounter) Write(b []byte) (int, error) {
	*c += writeCounter(len(b))
	return len(b), nil
}

F
Felix Lange 已提交
420 421
func CalcUncleHash(uncles []*Header) common.Hash {
	return rlpHash(uncles)
O
Merge  
obscuren 已提交
422 423
}

F
Felix Lange 已提交
424 425 426 427 428 429 430 431 432 433
// WithMiningResult returns a new block with the data from b
// where nonce and mix digest are set to the provided values.
func (b *Block) WithMiningResult(nonce uint64, mixDigest common.Hash) *Block {
	cpy := *b.header
	binary.BigEndian.PutUint64(cpy.Nonce[:], nonce)
	cpy.MixDigest = mixDigest
	return &Block{
		header:       &cpy,
		transactions: b.transactions,
		uncles:       b.uncles,
O
Merge  
obscuren 已提交
434
	}
O
obscuren 已提交
435 436
}

437 438 439
// WithBody returns a new block with the given transaction and uncle contents.
func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
	block := &Block{
440
		header:       CopyHeader(b.header),
441 442 443 444 445
		transactions: make([]*Transaction, len(transactions)),
		uncles:       make([]*Header, len(uncles)),
	}
	copy(block.transactions, transactions)
	for i := range uncles {
446
		block.uncles[i] = CopyHeader(uncles[i])
447 448 449 450
	}
	return block
}

451 452
// Hash returns the keccak256 hash of b's header.
// The hash is computed on the first call and cached thereafter.
F
Felix Lange 已提交
453
func (b *Block) Hash() common.Hash {
454 455 456 457 458 459
	if hash := b.hash.Load(); hash != nil {
		return hash.(common.Hash)
	}
	v := rlpHash(b.header)
	b.hash.Store(v)
	return v
O
obscuren 已提交
460 461
}

F
Felix Lange 已提交
462
func (b *Block) String() string {
463
	str := fmt.Sprintf(`Block(#%v): Size: %v {
464
MinerHash: %x
O
obscuren 已提交
465
%v
O
obscuren 已提交
466
Transactions:
O
obscuren 已提交
467
%v
O
obscuren 已提交
468
Uncles:
O
obscuren 已提交
469 470
%v
}
471
`, b.Number(), b.Size(), b.header.HashNoNonce(), b.header, b.transactions, b.uncles)
472
	return str
O
obscuren 已提交
473 474
}

F
Felix Lange 已提交
475
func (h *Header) String() string {
476 477
	return fmt.Sprintf(`Header(%x):
[
O
obscuren 已提交
478 479 480 481 482 483 484 485 486 487 488 489
	ParentHash:	    %x
	UncleHash:	    %x
	Coinbase:	    %x
	Root:		    %x
	TxSha		    %x
	ReceiptSha:	    %x
	Bloom:		    %x
	Difficulty:	    %v
	Number:		    %v
	GasLimit:	    %v
	GasUsed:	    %v
	Time:		    %v
490
	Extra:		    %s
F
Felix Lange 已提交
491
	MixDigest:      %x
492
	Nonce:		    %x
F
Felix Lange 已提交
493
]`, h.Hash(), h.ParentHash, h.UncleHash, h.Coinbase, h.Root, h.TxHash, h.ReceiptHash, h.Bloom, h.Difficulty, h.Number, h.GasLimit, h.GasUsed, h.Time, h.Extra, h.MixDigest, h.Nonce)
M
Maran 已提交
494
}
O
obscuren 已提交
495

O
obscuren 已提交
496
type Blocks []*Block
497

O
obscuren 已提交
498
type BlockBy func(b1, b2 *Block) bool
O
obscuren 已提交
499

O
obscuren 已提交
500 501 502 503
func (self BlockBy) Sort(blocks Blocks) {
	bs := blockSorter{
		blocks: blocks,
		by:     self,
O
obscuren 已提交
504
	}
O
obscuren 已提交
505
	sort.Sort(bs)
O
obscuren 已提交
506
}
O
obscuren 已提交
507

O
obscuren 已提交
508 509 510
type blockSorter struct {
	blocks Blocks
	by     func(b1, b2 *Block) bool
O
obscuren 已提交
511
}
O
obscuren 已提交
512

O
obscuren 已提交
513 514 515
func (self blockSorter) Len() int { return len(self.blocks) }
func (self blockSorter) Swap(i, j int) {
	self.blocks[i], self.blocks[j] = self.blocks[j], self.blocks[i]
O
obscuren 已提交
516
}
O
obscuren 已提交
517
func (self blockSorter) Less(i, j int) bool { return self.by(self.blocks[i], self.blocks[j]) }
O
obscuren 已提交
518

F
Felix Lange 已提交
519
func Number(b1, b2 *Block) bool { return b1.header.Number.Cmp(b2.header.Number) < 0 }