9 "github.com/bytom/bytom/encoding/blockchain"
10 "github.com/bytom/bytom/encoding/bufpool"
11 "github.com/bytom/bytom/errors"
12 "github.com/bytom/bytom/protocol/bc"
15 // BlockHeader defines information about a block and is used in the Bytom
16 type BlockHeader struct {
17 Version uint64 // The version of the block.
18 Height uint64 // The height of the block.
19 PreviousBlockHash bc.Hash // The hash of the previous block.
20 Timestamp uint64 // The time of the block in seconds.
21 Nonce uint64 // Nonce used to generate the block.
25 // Time returns the time represented by the Timestamp in block header.
26 func (bh *BlockHeader) Time() time.Time {
27 return time.Unix(int64(bh.Timestamp), 0).UTC()
30 // Hash returns complete hash of the block header.
31 func (bh *BlockHeader) Hash() bc.Hash {
32 h, _ := mapBlockHeader(bh)
36 // MarshalText fulfills the json.Marshaler interface. This guarantees that
37 // block headers will get deserialized correctly when being parsed from HTTP
39 func (bh *BlockHeader) MarshalText() ([]byte, error) {
41 defer bufpool.Put(buf)
43 if _, err := bh.WriteTo(buf); err != nil {
47 enc := make([]byte, hex.EncodedLen(buf.Len()))
48 hex.Encode(enc, buf.Bytes())
52 // UnmarshalText fulfills the encoding.TextUnmarshaler interface.
53 func (bh *BlockHeader) UnmarshalText(text []byte) error {
54 decoded := make([]byte, hex.DecodedLen(len(text)))
55 if _, err := hex.Decode(decoded, text); err != nil {
59 _, err := bh.readFrom(blockchain.NewReader(decoded))
63 func (bh *BlockHeader) readFrom(r *blockchain.Reader) (serflag uint8, err error) {
65 io.ReadFull(r, serflags[:])
68 case SerBlockHeader, SerBlockFull:
70 return 0, fmt.Errorf("unsupported serialization flags 0x%x", serflags)
73 if bh.Version, err = blockchain.ReadVarint63(r); err != nil {
76 if bh.Height, err = blockchain.ReadVarint63(r); err != nil {
79 if _, err = bh.PreviousBlockHash.ReadFrom(r); err != nil {
82 if bh.Timestamp, err = blockchain.ReadVarint63(r); err != nil {
85 if _, err = blockchain.ReadExtensibleString(r, bh.BlockCommitment.readFrom); err != nil {
88 if bh.Nonce, err = blockchain.ReadVarint63(r); err != nil {
95 // WriteTo writes the block header to the input io.Writer
96 func (bh *BlockHeader) WriteTo(w io.Writer) (int64, error) {
97 ew := errors.NewWriter(w)
98 if err := bh.writeTo(ew, SerBlockHeader); err != nil {
101 return ew.Written(), ew.Err()
104 func (bh *BlockHeader) writeTo(w io.Writer, serflags uint8) (err error) {
105 w.Write([]byte{serflags})
106 if _, err = blockchain.WriteVarint63(w, bh.Version); err != nil {
109 if _, err = blockchain.WriteVarint63(w, bh.Height); err != nil {
112 if _, err = bh.PreviousBlockHash.WriteTo(w); err != nil {
115 if _, err = blockchain.WriteVarint63(w, bh.Timestamp); err != nil {
118 if _, err = blockchain.WriteExtensibleString(w, nil, bh.BlockCommitment.writeTo); err != nil {
121 if _, err = blockchain.WriteVarint63(w, bh.Nonce); err != nil {