OSDN Git Service

aede38f27913854cf4e39b331566592d1110a171
[bytom/vapor.git] / protocol / bc / types / output_commitment.go
1 package types
2
3 import (
4         "fmt"
5         "io"
6
7         "github.com/vapor/encoding/blockchain"
8         "github.com/vapor/errors"
9         "github.com/vapor/protocol/bc"
10 )
11
12 // OutputCommitment contains the commitment data for a transaction output.
13 type OutputCommitment struct {
14         bc.AssetAmount
15         VMVersion      uint64
16         ControlProgram []byte
17 }
18
19 func (oc *OutputCommitment) writeExtensibleString(w io.Writer, suffix []byte, assetVersion uint64) error {
20         _, err := blockchain.WriteExtensibleString(w, suffix, func(w io.Writer) error {
21                 return oc.writeContents(w, suffix, assetVersion)
22         })
23         return err
24 }
25
26 func (oc *OutputCommitment) writeContents(w io.Writer, suffix []byte, assetVersion uint64) (err error) {
27         if assetVersion == 1 {
28                 if _, err = oc.AssetAmount.WriteTo(w); err != nil {
29                         return errors.Wrap(err, "writing asset amount")
30                 }
31                 if _, err = blockchain.WriteVarint63(w, oc.VMVersion); err != nil {
32                         return errors.Wrap(err, "writing vm version")
33                 }
34                 if _, err = blockchain.WriteVarstr31(w, oc.ControlProgram); err != nil {
35                         return errors.Wrap(err, "writing control program")
36                 }
37         }
38         if len(suffix) > 0 {
39                 _, err = w.Write(suffix)
40         }
41         return errors.Wrap(err, "writing suffix")
42 }
43
44 func (oc *OutputCommitment) readFrom(r *blockchain.Reader, assetVersion uint64) (suffix []byte, err error) {
45         return blockchain.ReadExtensibleString(r, func(r *blockchain.Reader) error {
46                 if assetVersion == 1 {
47                         if err := oc.AssetAmount.ReadFrom(r); err != nil {
48                                 return errors.Wrap(err, "reading asset+amount")
49                         }
50                         oc.VMVersion, err = blockchain.ReadVarint63(r)
51                         if err != nil {
52                                 return errors.Wrap(err, "reading VM version")
53                         }
54                         if oc.VMVersion != 1 {
55                                 return fmt.Errorf("unrecognized VM version %d for asset version 1", oc.VMVersion)
56                         }
57                         oc.ControlProgram, err = blockchain.ReadVarstr31(r)
58                         return errors.Wrap(err, "reading control program")
59                 }
60                 return nil
61         })
62 }