9 "github.com/vapor/encoding/blockchain"
10 "github.com/vapor/encoding/bufpool"
11 "github.com/vapor/errors"
12 "github.com/vapor/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.
24 // Time returns the time represented by the Timestamp in block header.
25 func (bh *BlockHeader) Time() time.Time {
26 return time.Unix(int64(bh.Timestamp), 0).UTC()
29 // Hash returns complete hash of the block header.
30 func (bh *BlockHeader) Hash() bc.Hash {
31 h, _ := mapBlockHeader(bh)
35 // MarshalText fulfills the json.Marshaler interface. This guarantees that
36 // block headers will get deserialized correctly when being parsed from HTTP
38 func (bh *BlockHeader) MarshalText() ([]byte, error) {
40 defer bufpool.Put(buf)
42 if _, err := bh.WriteTo(buf); err != nil {
46 enc := make([]byte, hex.EncodedLen(buf.Len()))
47 hex.Encode(enc, buf.Bytes())
51 // UnmarshalText fulfills the encoding.TextUnmarshaler interface.
52 func (bh *BlockHeader) UnmarshalText(text []byte) error {
53 decoded := make([]byte, hex.DecodedLen(len(text)))
54 if _, err := hex.Decode(decoded, text); err != nil {
58 _, err := bh.readFrom(blockchain.NewReader(decoded))
62 func (bh *BlockHeader) readFrom(r *blockchain.Reader) (serflag uint8, err error) {
64 io.ReadFull(r, serflags[:])
67 case SerBlockHeader, SerBlockFull:
69 return 0, fmt.Errorf("unsupported serialization flags 0x%x", serflags)
72 if bh.Version, err = blockchain.ReadVarint63(r); err != nil {
75 if bh.Height, err = blockchain.ReadVarint63(r); err != nil {
78 if _, err = bh.PreviousBlockHash.ReadFrom(r); err != nil {
81 if bh.Timestamp, err = blockchain.ReadVarint63(r); err != nil {
84 if _, err = blockchain.ReadExtensibleString(r, bh.BlockCommitment.readFrom); err != nil {
90 // WriteTo writes the block header to the input io.Writer
91 func (bh *BlockHeader) WriteTo(w io.Writer) (int64, error) {
92 ew := errors.NewWriter(w)
93 if err := bh.writeTo(ew, SerBlockHeader); err != nil {
96 return ew.Written(), ew.Err()
99 func (bh *BlockHeader) writeTo(w io.Writer, serflags uint8) (err error) {
100 w.Write([]byte{serflags})
101 if _, err = blockchain.WriteVarint63(w, bh.Version); err != nil {
104 if _, err = blockchain.WriteVarint63(w, bh.Height); err != nil {
107 if _, err = bh.PreviousBlockHash.WriteTo(w); err != nil {
110 if _, err = blockchain.WriteVarint63(w, bh.Timestamp); err != nil {
113 if _, err = blockchain.WriteExtensibleString(w, nil, bh.BlockCommitment.writeTo); err != nil {