github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/protocol/bc/types/spend_commitment.go (about) 1 package types 2 3 import ( 4 "fmt" 5 "io" 6 7 "github.com/bytom/bytom/encoding/blockchain" 8 "github.com/bytom/bytom/errors" 9 "github.com/bytom/bytom/protocol/bc" 10 ) 11 12 // SpendCommitment contains the commitment data for a transaction output. 13 type SpendCommitment struct { 14 bc.AssetAmount 15 SourceID bc.Hash 16 SourcePosition uint64 17 VMVersion uint64 18 ControlProgram []byte 19 } 20 21 func (sc *SpendCommitment) writeExtensibleString(w io.Writer, suffix []byte, assetVersion uint64) error { 22 _, err := blockchain.WriteExtensibleString(w, suffix, func(w io.Writer) error { 23 return sc.writeContents(w, suffix, assetVersion) 24 }) 25 return err 26 } 27 28 func (sc *SpendCommitment) writeContents(w io.Writer, suffix []byte, assetVersion uint64) (err error) { 29 if assetVersion == 1 { 30 if _, err = sc.SourceID.WriteTo(w); err != nil { 31 return errors.Wrap(err, "writing source id") 32 } 33 if _, err = sc.AssetAmount.WriteTo(w); err != nil { 34 return errors.Wrap(err, "writing asset amount") 35 } 36 if _, err = blockchain.WriteVarint63(w, sc.SourcePosition); err != nil { 37 return errors.Wrap(err, "writing source position") 38 } 39 if _, err = blockchain.WriteVarint63(w, sc.VMVersion); err != nil { 40 return errors.Wrap(err, "writing vm version") 41 } 42 if _, err = blockchain.WriteVarstr31(w, sc.ControlProgram); err != nil { 43 return errors.Wrap(err, "writing control program") 44 } 45 } 46 if len(suffix) > 0 { 47 _, err = w.Write(suffix) 48 } 49 return errors.Wrap(err, "writing suffix") 50 } 51 52 func (sc *SpendCommitment) readFrom(r *blockchain.Reader, assetVersion uint64) (suffix []byte, err error) { 53 return blockchain.ReadExtensibleString(r, func(r *blockchain.Reader) error { 54 if assetVersion == 1 { 55 if _, err := sc.SourceID.ReadFrom(r); err != nil { 56 return errors.Wrap(err, "reading source id") 57 } 58 if err = sc.AssetAmount.ReadFrom(r); err != nil { 59 return errors.Wrap(err, "reading asset+amount") 60 } 61 if sc.SourcePosition, err = blockchain.ReadVarint63(r); err != nil { 62 return errors.Wrap(err, "reading source position") 63 } 64 if sc.VMVersion, err = blockchain.ReadVarint63(r); err != nil { 65 return errors.Wrap(err, "reading VM version") 66 } 67 if sc.VMVersion != 1 { 68 return fmt.Errorf("unrecognized VM version %d for asset version 1", sc.VMVersion) 69 } 70 if sc.ControlProgram, err = blockchain.ReadVarstr31(r); err != nil { 71 return errors.Wrap(err, "reading control program") 72 } 73 return nil 74 } 75 return nil 76 }) 77 }