github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/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 StateData [][]byte 20 } 21 22 func (sc *SpendCommitment) writeExtensibleString(w io.Writer, suffix []byte, assetVersion uint64) error { 23 _, err := blockchain.WriteExtensibleString(w, suffix, func(w io.Writer) error { 24 return sc.writeContents(w, suffix, assetVersion) 25 }) 26 return err 27 } 28 29 func (sc *SpendCommitment) writeContents(w io.Writer, suffix []byte, assetVersion uint64) (err error) { 30 if assetVersion == 1 { 31 if _, err = sc.SourceID.WriteTo(w); err != nil { 32 return errors.Wrap(err, "writing source id") 33 } 34 if _, err = sc.AssetAmount.WriteTo(w); err != nil { 35 return errors.Wrap(err, "writing asset amount") 36 } 37 if _, err = blockchain.WriteVarint63(w, sc.SourcePosition); err != nil { 38 return errors.Wrap(err, "writing source position") 39 } 40 if _, err = blockchain.WriteVarint63(w, sc.VMVersion); err != nil { 41 return errors.Wrap(err, "writing vm version") 42 } 43 if _, err = blockchain.WriteVarstr31(w, sc.ControlProgram); err != nil { 44 return errors.Wrap(err, "writing control program") 45 } 46 if _, err = blockchain.WriteVarstrList(w, sc.StateData); err != nil { 47 return errors.Wrap(err, "writing state data") 48 } 49 } 50 if len(suffix) > 0 { 51 _, err = w.Write(suffix) 52 } 53 return errors.Wrap(err, "writing suffix") 54 } 55 56 func (sc *SpendCommitment) readFrom(r *blockchain.Reader, assetVersion uint64) (suffix []byte, err error) { 57 return blockchain.ReadExtensibleString(r, func(r *blockchain.Reader) error { 58 if assetVersion == 1 { 59 if _, err := sc.SourceID.ReadFrom(r); err != nil { 60 return errors.Wrap(err, "reading source id") 61 } 62 if err = sc.AssetAmount.ReadFrom(r); err != nil { 63 return errors.Wrap(err, "reading asset+amount") 64 } 65 if sc.SourcePosition, err = blockchain.ReadVarint63(r); err != nil { 66 return errors.Wrap(err, "reading source position") 67 } 68 if sc.VMVersion, err = blockchain.ReadVarint63(r); err != nil { 69 return errors.Wrap(err, "reading VM version") 70 } 71 if sc.VMVersion != 1 { 72 return fmt.Errorf("unrecognized VM version %d for asset version 1", sc.VMVersion) 73 } 74 if sc.ControlProgram, err = blockchain.ReadVarstr31(r); err != nil { 75 return errors.Wrap(err, "reading control program") 76 } 77 if sc.StateData, err = blockchain.ReadVarstrList(r); err != nil { 78 return errors.Wrap(err, "reading state data") 79 } 80 return nil 81 } 82 return nil 83 }) 84 }