8 "github.com/bytom/bytom/encoding/blockchain"
9 "github.com/bytom/bytom/encoding/bufpool"
10 "github.com/bytom/bytom/errors"
13 // serflag variables, start with 1
21 // Block describes a complete block, including its header and the transactions
28 func (b *Block) marshalText(serflags uint8) ([]byte, error) {
30 defer bufpool.Put(buf)
32 ew := errors.NewWriter(buf)
33 if err := b.writeTo(ew, serflags); err != nil {
37 if err := ew.Err(); err != nil {
41 enc := make([]byte, hex.EncodedLen(buf.Len()))
42 hex.Encode(enc, buf.Bytes())
46 // MarshalText fulfills the json.Marshaler interface. This guarantees that
47 // blocks will get deserialized correctly when being parsed from HTTP requests.
48 func (b *Block) MarshalText() ([]byte, error) {
49 return b.marshalText(SerBlockFull)
52 // MarshalTextForBlockHeader fulfills the json.Marshaler interface.
53 func (b *Block) MarshalTextForBlockHeader() ([]byte, error) {
54 return b.marshalText(SerBlockHeader)
57 // MarshalTextForTransactions fulfills the json.Marshaler interface.
58 func (b *Block) MarshalTextForTransactions() ([]byte, error) {
59 return b.marshalText(SerBlockTransactions)
62 // UnmarshalText fulfills the encoding.TextUnmarshaler interface.
63 func (b *Block) UnmarshalText(text []byte) error {
64 decoded := make([]byte, hex.DecodedLen(len(text)))
65 if _, err := hex.Decode(decoded, text); err != nil {
69 r := blockchain.NewReader(decoded)
70 if err := b.readFrom(r); err != nil {
74 if trailing := r.Len(); trailing > 0 {
75 return fmt.Errorf("trailing garbage (%d bytes)", trailing)
80 func (b *Block) readFrom(r *blockchain.Reader) error {
81 serflag, err := b.BlockHeader.readFrom(r)
86 if serflag == SerBlockHeader {
90 n, err := blockchain.ReadVarint31(r)
92 return errors.Wrap(err, "reading number of transactions")
97 if err = data.readFrom(r); err != nil {
98 return errors.Wrapf(err, "reading transaction %d", len(b.Transactions))
101 b.Transactions = append(b.Transactions, NewTx(data))
106 // WriteTo write block to io.Writer
107 func (b *Block) WriteTo(w io.Writer) (int64, error) {
108 ew := errors.NewWriter(w)
109 if err := b.writeTo(ew, SerBlockFull); err != nil {
112 return ew.Written(), ew.Err()
115 func (b *Block) writeTo(w io.Writer, serflags uint8) error {
116 if err := b.BlockHeader.writeTo(w, serflags); err != nil {
120 if serflags == SerBlockHeader {
124 if _, err := blockchain.WriteVarint31(w, uint64(len(b.Transactions))); err != nil {
128 for _, tx := range b.Transactions {
129 if _, err := tx.WriteTo(w); err != nil {