-package legacy
+package types
import (
+ "encoding/hex"
"fmt"
"io"
"time"
"github.com/bytom/encoding/blockchain"
+ "github.com/bytom/encoding/bufpool"
"github.com/bytom/errors"
"github.com/bytom/protocol/bc"
)
// Hash of the previous block in the block chain.
PreviousBlockHash bc.Hash `json:"previous_block_hash"`
- Seed bc.Hash `json:"seed"`
-
// Time of the block in seconds.
Timestamp uint64 `json:"timestamp"`
- TransactionStatus bc.TransactionStatus `json:"transaction_status"`
-
BlockCommitment
Nonce uint64 `json:"nonce"`
return h
}
+// MarshalText fulfills the json.Marshaler interface.
+// This guarantees that block headers will get deserialized correctly
+// when being parsed from HTTP requests.
+func (bh *BlockHeader) MarshalText() ([]byte, error) {
+ buf := bufpool.Get()
+ defer bufpool.Put(buf)
+ if _, err := bh.WriteTo(buf); err != nil {
+ return nil, err
+ }
+
+ enc := make([]byte, hex.EncodedLen(buf.Len()))
+ hex.Encode(enc, buf.Bytes())
+ return enc, nil
+}
+
+// UnmarshalText fulfills the encoding.TextUnmarshaler interface.
+func (bh *BlockHeader) UnmarshalText(text []byte) error {
+ decoded := make([]byte, hex.DecodedLen(len(text)))
+ if _, err := hex.Decode(decoded, text); err != nil {
+ return err
+ }
+ _, err := bh.readFrom(blockchain.NewReader(decoded))
+ return err
+}
+
func (bh *BlockHeader) readFrom(r *blockchain.Reader) (serflag uint8, err error) {
var serflags [1]byte
io.ReadFull(r, serflags[:])
if _, err = bh.PreviousBlockHash.ReadFrom(r); err != nil {
return 0, err
}
- if _, err = bh.Seed.ReadFrom(r); err != nil {
- return 0, err
- }
if bh.Timestamp, err = blockchain.ReadVarint63(r); err != nil {
return 0, err
}
if _, err = blockchain.ReadExtensibleString(r, bh.BlockCommitment.readFrom); err != nil {
return 0, err
}
- if _, err = blockchain.ReadExtensibleString(r, bh.TransactionStatus.ReadFrom); err != nil {
- return 0, err
- }
if bh.Nonce, err = blockchain.ReadVarint63(r); err != nil {
return 0, err
}
if _, err = bh.PreviousBlockHash.WriteTo(w); err != nil {
return err
}
- if _, err = bh.Seed.WriteTo(w); err != nil {
- return err
- }
if _, err = blockchain.WriteVarint63(w, bh.Timestamp); err != nil {
return err
}
if _, err = blockchain.WriteExtensibleString(w, nil, bh.BlockCommitment.writeTo); err != nil {
return err
}
- if _, err = blockchain.WriteExtensibleString(w, nil, bh.TransactionStatus.WriteTo); err != nil {
- return err
- }
if _, err = blockchain.WriteVarint63(w, bh.Nonce); err != nil {
return err
}