8 "github.com/vapor/encoding/blockchain"
9 "github.com/vapor/encoding/bufpool"
10 "github.com/vapor/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 {
36 if err := ew.Err(); err != nil {
40 enc := make([]byte, hex.EncodedLen(buf.Len()))
41 hex.Encode(enc, buf.Bytes())
45 // MarshalText fulfills the json.Marshaler interface. This guarantees that
46 // blocks will get deserialized correctly when being parsed from HTTP requests.
47 func (b *Block) MarshalText() ([]byte, error) {
48 return b.marshalText(SerBlockFull)
51 // MarshalTextForBlockHeader fulfills the json.Marshaler interface.
52 func (b *Block) MarshalTextForBlockHeader() ([]byte, error) {
53 return b.marshalText(SerBlockHeader)
56 // MarshalTextForTransactions fulfills the json.Marshaler interface.
57 func (b *Block) MarshalTextForTransactions() ([]byte, error) {
58 return b.marshalText(SerBlockTransactions)
61 // UnmarshalText fulfills the encoding.TextUnmarshaler interface.
62 func (b *Block) UnmarshalText(text []byte) error {
63 decoded := make([]byte, hex.DecodedLen(len(text)))
64 if _, err := hex.Decode(decoded, text); err != nil {
68 r := blockchain.NewReader(decoded)
69 if err := b.readFrom(r); err != nil {
73 if trailing := r.Len(); trailing > 0 {
74 return fmt.Errorf("trailing garbage (%d bytes)", trailing)
79 func (b *Block) readFrom(r *blockchain.Reader) error {
80 serflag, err := b.BlockHeader.readFrom(r)
85 if serflag == SerBlockHeader {
89 n, err := blockchain.ReadVarint31(r)
91 return errors.Wrap(err, "reading number of transactions")
96 if err = data.readFrom(r); err != nil {
97 return errors.Wrapf(err, "reading transaction %d", len(b.Transactions))
100 b.Transactions = append(b.Transactions, NewTx(data))
105 func (b *Block) WriteTo(w io.Writer) (int64, error) {
106 ew := errors.NewWriter(w)
107 if err := b.writeTo(ew, SerBlockFull); err != nil {
110 return ew.Written(), ew.Err()
113 func (b *Block) writeTo(w io.Writer, serflags uint8) error {
114 if err := b.BlockHeader.writeTo(w, serflags); err != nil {
118 if serflags == SerBlockHeader {
122 if _, err := blockchain.WriteVarint31(w, uint64(len(b.Transactions))); err != nil {
126 for _, tx := range b.Transactions {
127 if _, err := tx.WriteTo(w); err != nil {