8 "github.com/bytom/encoding/blockchain"
9 "github.com/bytom/encoding/bufpool"
10 "github.com/bytom/errors"
13 // serflag variables, start with 1
21 // Block describes a complete block, including its header and the transactions
28 // MarshalText fulfills the json.Marshaler interface. This guarantees that
29 // blocks will get deserialized correctly when being parsed from HTTP requests.
30 func (b *Block) MarshalText() ([]byte, error) {
32 defer bufpool.Put(buf)
34 if _, err := b.WriteTo(buf); err != nil {
38 enc := make([]byte, hex.EncodedLen(buf.Len()))
39 hex.Encode(enc, buf.Bytes())
43 // UnmarshalText fulfills the encoding.TextUnmarshaler interface.
44 func (b *Block) UnmarshalText(text []byte) error {
45 decoded := make([]byte, hex.DecodedLen(len(text)))
46 if _, err := hex.Decode(decoded, text); err != nil {
50 r := blockchain.NewReader(decoded)
51 if err := b.readFrom(r); err != nil {
55 if trailing := r.Len(); trailing > 0 {
56 return fmt.Errorf("trailing garbage (%d bytes)", trailing)
61 func (b *Block) readFrom(r *blockchain.Reader) error {
62 serflags, err := b.BlockHeader.readFrom(r)
67 if serflags == SerBlockHeader {
71 n, err := blockchain.ReadVarint31(r)
73 return errors.Wrap(err, "reading number of transactions")
78 if err = data.readFrom(r); err != nil {
79 return errors.Wrapf(err, "reading transaction %d", len(b.Transactions))
82 b.Transactions = append(b.Transactions, NewTx(data))
87 // WriteTo will write block to input io.Writer
88 func (b *Block) WriteTo(w io.Writer) (int64, error) {
89 ew := errors.NewWriter(w)
90 if err := b.writeTo(ew, SerBlockFull); err != nil {
93 return ew.Written(), ew.Err()
96 func (b *Block) writeTo(w io.Writer, serflags uint8) error {
97 if err := b.BlockHeader.writeTo(w, serflags); err != nil {
101 if serflags == SerBlockHeader {
105 if _, err := blockchain.WriteVarint31(w, uint64(len(b.Transactions))); err != nil {
109 for _, tx := range b.Transactions {
110 if _, err := tx.WriteTo(w); err != nil {