Skip to content

Commit 704fde0

Browse files
committed
core/types, core/vm: improve docs, add JSON marshaling methods
In this commit, core/types's types learn how to encode and decode themselves as JSON. The encoding is very similar to what the RPC API uses. The RPC API is missing some output fields (e.g. transaction signature values) which will be added to the API in a later commit. Some fields that the API generates are ignored by the decoder methods here.
1 parent 0c9a858 commit 704fde0

8 files changed

Lines changed: 589 additions & 99 deletions

File tree

‎core/types/block.go‎

Lines changed: 110 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@
1818
package types
1919

2020
import (
21-
"bytes"
2221
"encoding/binary"
2322
"encoding/json"
23+
"errors"
2424
"fmt"
2525
"io"
2626
"math/big"
@@ -33,25 +33,53 @@ import (
3333
"github.com/ethereum/go-ethereum/rlp"
3434
)
3535

36+
var (
37+
EmptyRootHash = DeriveSha(Transactions{})
38+
EmptyUncleHash = CalcUncleHash(nil)
39+
)
40+
41+
var (
42+
errMissingHeaderMixDigest = errors.New("missing mixHash in JSON block header")
43+
errMissingHeaderFields = errors.New("missing required JSON block header fields")
44+
errBadNonceSize = errors.New("invalid block nonce size, want 8 bytes")
45+
)
46+
3647
// A BlockNonce is a 64-bit hash which proves (combined with the
3748
// mix-hash) that a sufficient amount of computation has been carried
3849
// out on a block.
3950
type BlockNonce [8]byte
4051

52+
// EncodeNonce converts the given integer to a block nonce.
4153
func EncodeNonce(i uint64) BlockNonce {
4254
var n BlockNonce
4355
binary.BigEndian.PutUint64(n[:], i)
4456
return n
4557
}
4658

59+
// Uint64 returns the integer value of a block nonce.
4760
func (n BlockNonce) Uint64() uint64 {
4861
return binary.BigEndian.Uint64(n[:])
4962
}
5063

64+
// MarshalJSON implements json.Marshaler
5165
func (n BlockNonce) MarshalJSON() ([]byte, error) {
5266
return []byte(fmt.Sprintf(`"0x%x"`, n)), nil
5367
}
5468

69+
// UnmarshalJSON implements json.Unmarshaler
70+
func (n *BlockNonce) UnmarshalJSON(input []byte) error {
71+
var b hexBytes
72+
if err := b.UnmarshalJSON(input); err != nil {
73+
return err
74+
}
75+
if len(b) != 8 {
76+
return errBadNonceSize
77+
}
78+
copy((*n)[:], b)
79+
return nil
80+
}
81+
82+
// Header represents Ethereum block headers.
5583
type Header struct {
5684
ParentHash common.Hash // Hash to the previous block
5785
UncleHash common.Hash // Uncles of this block
@@ -70,10 +98,31 @@ type Header struct {
7098
Nonce BlockNonce
7199
}
72100

101+
type jsonHeader struct {
102+
ParentHash *common.Hash `json:"parentHash"`
103+
UncleHash *common.Hash `json:"sha3Uncles"`
104+
Coinbase *common.Address `json:"miner"`
105+
Root *common.Hash `json:"stateRoot"`
106+
TxHash *common.Hash `json:"transactionsRoot"`
107+
ReceiptHash *common.Hash `json:"receiptRoot"`
108+
Bloom *Bloom `json:"logsBloom"`
109+
Difficulty *hexBig `json:"difficulty"`
110+
Number *hexBig `json:"number"`
111+
GasLimit *hexBig `json:"gasLimit"`
112+
GasUsed *hexBig `json:"gasUsed"`
113+
Time *hexBig `json:"timestamp"`
114+
Extra *hexBytes `json:"extraData"`
115+
MixDigest *common.Hash `json:"mixHash"`
116+
Nonce *BlockNonce `json:"nonce"`
117+
}
118+
119+
// Hash returns the block hash of the header, which is simply the keccak256 hash of its
120+
// RLP encoding.
73121
func (h *Header) Hash() common.Hash {
74122
return rlpHash(h)
75123
}
76124

125+
// HashNoNonce returns the hash which is used as input for the proof-of-work search.
77126
func (h *Header) HashNoNonce() common.Hash {
78127
return rlpHash([]interface{}{
79128
h.ParentHash,
@@ -92,48 +141,63 @@ func (h *Header) HashNoNonce() common.Hash {
92141
})
93142
}
94143

95-
func (h *Header) UnmarshalJSON(data []byte) error {
96-
var ext struct {
97-
ParentHash string
98-
Coinbase string
99-
Difficulty string
100-
GasLimit string
101-
Time *big.Int
102-
Extra string
103-
}
104-
dec := json.NewDecoder(bytes.NewReader(data))
105-
if err := dec.Decode(&ext); err != nil {
106-
return err
107-
}
108-
109-
h.ParentHash = common.HexToHash(ext.ParentHash)
110-
h.Coinbase = common.HexToAddress(ext.Coinbase)
111-
h.Difficulty = common.String2Big(ext.Difficulty)
112-
h.Time = ext.Time
113-
h.Extra = []byte(ext.Extra)
114-
return nil
144+
// MarshalJSON encodes headers into the web3 RPC response block format.
145+
func (h *Header) MarshalJSON() ([]byte, error) {
146+
return json.Marshal(&jsonHeader{
147+
ParentHash: &h.ParentHash,
148+
UncleHash: &h.UncleHash,
149+
Coinbase: &h.Coinbase,
150+
Root: &h.Root,
151+
TxHash: &h.TxHash,
152+
ReceiptHash: &h.ReceiptHash,
153+
Bloom: &h.Bloom,
154+
Difficulty: (*hexBig)(h.Difficulty),
155+
Number: (*hexBig)(h.Number),
156+
GasLimit: (*hexBig)(h.GasLimit),
157+
GasUsed: (*hexBig)(h.GasUsed),
158+
Time: (*hexBig)(h.Time),
159+
Extra: (*hexBytes)(&h.Extra),
160+
MixDigest: &h.MixDigest,
161+
Nonce: &h.Nonce,
162+
})
115163
}
116164

117-
func (h *Header) MarshalJSON() ([]byte, error) {
118-
fields := map[string]interface{}{
119-
"hash": h.Hash(),
120-
"parentHash": h.ParentHash,
121-
"number": fmt.Sprintf("%#x", h.Number),
122-
"nonce": h.Nonce,
123-
"receiptRoot": h.ReceiptHash,
124-
"logsBloom": h.Bloom,
125-
"sha3Uncles": h.UncleHash,
126-
"stateRoot": h.Root,
127-
"miner": h.Coinbase,
128-
"difficulty": fmt.Sprintf("%#x", h.Difficulty),
129-
"extraData": fmt.Sprintf("0x%x", h.Extra),
130-
"gasLimit": fmt.Sprintf("%#x", h.GasLimit),
131-
"gasUsed": fmt.Sprintf("%#x", h.GasUsed),
132-
"timestamp": fmt.Sprintf("%#x", h.Time),
133-
"transactionsRoot": h.TxHash,
165+
// UnmarshalJSON decodes headers from the web3 RPC response block format.
166+
func (h *Header) UnmarshalJSON(input []byte) error {
167+
var dec jsonHeader
168+
if err := json.Unmarshal(input, &dec); err != nil {
169+
return err
134170
}
135-
136-
return json.Marshal(fields)
171+
// Ensure that all fields are set. MixDigest is checked separately because
172+
// it is a recent addition to the spec (as of August 2016) and older RPC server
173+
// implementations might not provide it.
174+
if dec.MixDigest == nil {
175+
return errMissingHeaderMixDigest
176+
}
177+
if dec.ParentHash == nil || dec.UncleHash == nil || dec.Coinbase == nil ||
178+
dec.Root == nil || dec.TxHash == nil || dec.ReceiptHash == nil ||
179+
dec.Bloom == nil || dec.Difficulty == nil || dec.Number == nil ||
180+
dec.GasLimit == nil || dec.GasUsed == nil || dec.Time == nil ||
181+
dec.Extra == nil || dec.Nonce == nil {
182+
return errMissingHeaderFields
183+
}
184+
// Assign all values.
185+
h.ParentHash = *dec.ParentHash
186+
h.UncleHash = *dec.UncleHash
187+
h.Coinbase = *dec.Coinbase
188+
h.Root = *dec.Root
189+
h.TxHash = *dec.TxHash
190+
h.ReceiptHash = *dec.ReceiptHash
191+
h.Bloom = *dec.Bloom
192+
h.Difficulty = (*big.Int)(dec.Difficulty)
193+
h.Number = (*big.Int)(dec.Number)
194+
h.GasLimit = (*big.Int)(dec.GasLimit)
195+
h.GasUsed = (*big.Int)(dec.GasUsed)
196+
h.Time = (*big.Int)(dec.Time)
197+
h.Extra = *dec.Extra
198+
h.MixDigest = *dec.MixDigest
199+
h.Nonce = *dec.Nonce
200+
return nil
137201
}
138202

139203
func rlpHash(x interface{}) (h common.Hash) {
@@ -150,6 +214,7 @@ type Body struct {
150214
Uncles []*Header
151215
}
152216

217+
// Block represents a block in the Ethereum blockchain.
153218
type Block struct {
154219
header *Header
155220
uncles []*Header
@@ -198,11 +263,6 @@ type storageblock struct {
198263
TD *big.Int
199264
}
200265

201-
var (
202-
EmptyRootHash = DeriveSha(Transactions{})
203-
EmptyUncleHash = CalcUncleHash(nil)
204-
)
205-
206266
// NewBlock creates a new block. The input data is copied,
207267
// changes to header and to the field values will not affect the
208268
// block.
@@ -275,23 +335,7 @@ func CopyHeader(h *Header) *Header {
275335
return &cpy
276336
}
277337

278-
func (b *Block) ValidateFields() error {
279-
if b.header == nil {
280-
return fmt.Errorf("header is nil")
281-
}
282-
for i, transaction := range b.transactions {
283-
if transaction == nil {
284-
return fmt.Errorf("transaction %d is nil", i)
285-
}
286-
}
287-
for i, uncle := range b.uncles {
288-
if uncle == nil {
289-
return fmt.Errorf("uncle %d is nil", i)
290-
}
291-
}
292-
return nil
293-
}
294-
338+
// DecodeRLP decodes the Ethereum
295339
func (b *Block) DecodeRLP(s *rlp.Stream) error {
296340
var eb extblock
297341
_, size, _ := s.Kind()
@@ -303,6 +347,7 @@ func (b *Block) DecodeRLP(s *rlp.Stream) error {
303347
return nil
304348
}
305349

350+
// EncodeRLP serializes b into the Ethereum RLP block format.
306351
func (b *Block) EncodeRLP(w io.Writer) error {
307352
return rlp.Encode(w, extblock{
308353
Header: b.header,
@@ -322,6 +367,7 @@ func (b *StorageBlock) DecodeRLP(s *rlp.Stream) error {
322367
}
323368

324369
// TODO: copies
370+
325371
func (b *Block) Uncles() []*Header { return b.uncles }
326372
func (b *Block) Transactions() Transactions { return b.transactions }
327373

@@ -409,8 +455,8 @@ func (b *Block) WithBody(transactions []*Transaction, uncles []*Header) *Block {
409455
return block
410456
}
411457

412-
// Implement pow.Block
413-
458+
// Hash returns the keccak256 hash of b's header.
459+
// The hash is computed on the first call and cached thereafter.
414460
func (b *Block) Hash() common.Hash {
415461
if hash := b.hash.Load(); hash != nil {
416462
return hash.(common.Hash)

‎core/types/bloom9.go‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,28 +31,34 @@ type bytesBacked interface {
3131

3232
const bloomLength = 256
3333

34+
// Bloom represents a 256 bit bloom filter.
3435
type Bloom [bloomLength]byte
3536

37+
// BytesToBloom converts a byte slice to a bloom filter.
38+
// It panics if b is not of suitable size.
3639
func BytesToBloom(b []byte) Bloom {
3740
var bloom Bloom
3841
bloom.SetBytes(b)
3942
return bloom
4043
}
4144

45+
// SetBytes sets the content of b to the given bytes.
46+
// It panics if d is not of suitable size.
4247
func (b *Bloom) SetBytes(d []byte) {
4348
if len(b) < len(d) {
4449
panic(fmt.Sprintf("bloom bytes too big %d %d", len(b), len(d)))
4550
}
46-
4751
copy(b[bloomLength-len(d):], d)
4852
}
4953

54+
// Add adds d to the filter. Future calls of Test(d) will return true.
5055
func (b *Bloom) Add(d *big.Int) {
5156
bin := new(big.Int).SetBytes(b[:])
5257
bin.Or(bin, bloom9(d.Bytes()))
5358
b.SetBytes(bin.Bytes())
5459
}
5560

61+
// Big converts b to a big integer.
5662
func (b Bloom) Big() *big.Int {
5763
return common.Bytes2Big(b[:])
5864
}
@@ -69,8 +75,22 @@ func (b Bloom) TestBytes(test []byte) bool {
6975
return b.Test(common.BytesToBig(test))
7076
}
7177

78+
// MarshalJSON encodes b as a hex string with 0x prefix.
7279
func (b Bloom) MarshalJSON() ([]byte, error) {
73-
return []byte(fmt.Sprintf(`"%#x"`, b.Bytes())), nil
80+
return []byte(fmt.Sprintf(`"%#x"`, b[:])), nil
81+
}
82+
83+
// UnmarshalJSON b as a hex string with 0x prefix.
84+
func (b *Bloom) UnmarshalJSON(input []byte) error {
85+
var dec hexBytes
86+
if err := dec.UnmarshalJSON(input); err != nil {
87+
return err
88+
}
89+
if len(dec) != bloomLength {
90+
return fmt.Errorf("invalid bloom size, want %d bytes", bloomLength)
91+
}
92+
copy((*b)[:], dec)
93+
return nil
7494
}
7595

7696
func CreateBloom(receipts Receipts) Bloom {

0 commit comments

Comments
 (0)