OSDN Git Service

Merge pull request #375 from Bytom/dev
[bytom/bytom-spv.git] / protocol / bc / types / transaction.go
1 package types
2
3 import (
4         "bytes"
5         "encoding/hex"
6         "fmt"
7         "io"
8
9         "github.com/bytom/crypto/sha3pool"
10         "github.com/bytom/encoding/blockchain"
11         "github.com/bytom/errors"
12         "github.com/bytom/protocol/bc"
13 )
14
15 // CurrentTransactionVersion is the current latest
16 // supported transaction version.
17 const CurrentTransactionVersion = 1
18
19 // Tx holds a transaction along with its hash.
20 type Tx struct {
21         TxData
22         *bc.Tx `json:"-"`
23 }
24
25 func (tx *Tx) UnmarshalText(p []byte) error {
26         if err := tx.TxData.UnmarshalText(p); err != nil {
27                 return err
28         }
29
30         tx.Tx = MapTx(&tx.TxData)
31         return nil
32 }
33
34 // SetInputArguments sets the Arguments field in input n.
35 func (tx *Tx) SetInputArguments(n uint32, args [][]byte) {
36         tx.Inputs[n].SetArguments(args)
37         id := tx.Tx.InputIDs[n]
38         e := tx.Entries[id]
39         switch e := e.(type) {
40         case *bc.Issuance:
41                 e.WitnessArguments = args
42         case *bc.Spend:
43                 e.WitnessArguments = args
44         }
45 }
46
47 func (tx *Tx) IssuanceHash(n int) bc.Hash {
48         return tx.Tx.InputIDs[n]
49 }
50
51 func (tx *Tx) OutputID(outputIndex int) *bc.Hash {
52         return tx.ResultIds[outputIndex]
53 }
54
55 // NewTx returns a new Tx containing data and its hash.
56 // If you have already computed the hash, use struct literal
57 // notation to make a Tx object directly.
58 func NewTx(data TxData) *Tx {
59         return &Tx{
60                 TxData: data,
61                 Tx:     MapTx(&data),
62         }
63 }
64
65 // These flags are part of the wire protocol;
66 // they must not change.
67 const (
68         SerWitness uint8 = 1 << iota
69         SerPrevout
70         SerMetadata
71
72         // Bit mask for accepted serialization flags.
73         // All other flag bits must be 0.
74         SerTxHash   = 0x0 // this is used only for computing transaction hash - prevout and refdata are replaced with their hashes
75         SerValid    = 0x7
76         serRequired = 0x7 // we support only this combination of flags
77 )
78
79 // TxData encodes a transaction in the blockchain.
80 // Most users will want to use Tx instead;
81 // it includes the hash.
82 type TxData struct {
83         Version        uint64
84         SerializedSize uint64
85         Inputs         []*TxInput
86         Outputs        []*TxOutput
87
88         TimeRange uint64
89
90         // The unconsumed suffix of the common fields extensible string
91         CommonFieldsSuffix []byte
92
93         // The unconsumed suffix of the common witness extensible string
94         CommonWitnessSuffix []byte
95 }
96
97 // HasIssuance returns true if this transaction has an issuance input.
98 func (tx *TxData) HasIssuance() bool {
99         for _, in := range tx.Inputs {
100                 if in.IsIssuance() {
101                         return true
102                 }
103         }
104         return false
105 }
106
107 func (tx *TxData) UnmarshalText(p []byte) error {
108         b := make([]byte, hex.DecodedLen(len(p)))
109         if _, err := hex.Decode(b, p); err != nil {
110                 return err
111         }
112
113         r := blockchain.NewReader(b)
114         if err := tx.readFrom(r); err != nil {
115                 return err
116         }
117         if trailing := r.Len(); trailing > 0 {
118                 return fmt.Errorf("trailing garbage (%d bytes)", trailing)
119         }
120         return nil
121 }
122
123 func (tx *TxData) readFrom(r *blockchain.Reader) (err error) {
124         tx.SerializedSize = uint64(r.Len())
125         var serflags [1]byte
126         if _, err = io.ReadFull(r, serflags[:]); err != nil {
127                 return errors.Wrap(err, "reading serialization flags")
128         }
129         if serflags[0] != serRequired {
130                 return fmt.Errorf("unsupported serflags %#x", serflags[0])
131         }
132
133         tx.Version, err = blockchain.ReadVarint63(r)
134         if err != nil {
135                 return errors.Wrap(err, "reading transaction version")
136         }
137
138         if tx.TimeRange, err = blockchain.ReadVarint63(r); err != nil {
139                 return err
140         }
141         // Common witness
142         tx.CommonWitnessSuffix, err = blockchain.ReadExtensibleString(r, tx.readCommonWitness)
143         if err != nil {
144                 return errors.Wrap(err, "reading transaction common witness")
145         }
146
147         n, err := blockchain.ReadVarint31(r)
148         if err != nil {
149                 return errors.Wrap(err, "reading number of transaction inputs")
150         }
151         for ; n > 0; n-- {
152                 ti := new(TxInput)
153                 if err = ti.readFrom(r); err != nil {
154                         return errors.Wrapf(err, "reading input %d", len(tx.Inputs))
155                 }
156                 tx.Inputs = append(tx.Inputs, ti)
157         }
158
159         n, err = blockchain.ReadVarint31(r)
160         if err != nil {
161                 return errors.Wrap(err, "reading number of transaction outputs")
162         }
163         for ; n > 0; n-- {
164                 to := new(TxOutput)
165                 if err = to.readFrom(r, tx.Version); err != nil {
166                         return errors.Wrapf(err, "reading output %d", len(tx.Outputs))
167                 }
168                 tx.Outputs = append(tx.Outputs, to)
169         }
170
171         return nil
172 }
173
174 // does not read the enclosing extensible string
175 func (tx *TxData) readCommonWitness(r *blockchain.Reader) error {
176         return nil
177 }
178
179 func (tx *TxData) MarshalText() ([]byte, error) {
180         var buf bytes.Buffer
181         tx.WriteTo(&buf) // error is impossible
182         b := make([]byte, hex.EncodedLen(buf.Len()))
183         hex.Encode(b, buf.Bytes())
184         return b, nil
185 }
186
187 // WriteTo writes tx to w.
188 func (tx *TxData) WriteTo(w io.Writer) (int64, error) {
189         ew := errors.NewWriter(w)
190         if err := tx.writeTo(ew, serRequired); err != nil {
191                 return ew.Written(), ew.Err()
192         }
193         return ew.Written(), ew.Err()
194 }
195
196 func (tx *TxData) writeTo(w io.Writer, serflags byte) error {
197         if _, err := w.Write([]byte{serflags}); err != nil {
198                 return errors.Wrap(err, "writing serialization flags")
199         }
200
201         if _, err := blockchain.WriteVarint63(w, tx.Version); err != nil {
202                 return errors.Wrap(err, "writing transaction version")
203         }
204
205         if _, err := blockchain.WriteVarint63(w, tx.TimeRange); err != nil {
206                 return errors.Wrap(err, "writing transaction maxtime")
207         }
208         // common witness
209         if _, err := blockchain.WriteExtensibleString(w, tx.CommonWitnessSuffix, tx.writeCommonWitness); err != nil {
210                 return errors.Wrap(err, "writing common witness")
211         }
212
213         if _, err := blockchain.WriteVarint31(w, uint64(len(tx.Inputs))); err != nil {
214                 return errors.Wrap(err, "writing tx input count")
215         }
216         for i, ti := range tx.Inputs {
217                 if err := ti.writeTo(w, serflags); err != nil {
218                         return errors.Wrapf(err, "writing tx input %d", i)
219                 }
220         }
221
222         if _, err := blockchain.WriteVarint31(w, uint64(len(tx.Outputs))); err != nil {
223                 return errors.Wrap(err, "writing tx output count")
224         }
225         for i, to := range tx.Outputs {
226                 if err := to.writeTo(w, serflags); err != nil {
227                         return errors.Wrapf(err, "writing tx output %d", i)
228                 }
229         }
230
231         return nil
232 }
233
234 // does not write the enclosing extensible string
235 func (tx *TxData) writeCommonWitness(w io.Writer) error {
236         // Future protocol versions may add fields here.
237         return nil
238 }
239
240 func writeRefData(w io.Writer, data []byte, serflags byte) error {
241         if serflags&SerMetadata != 0 {
242                 _, err := blockchain.WriteVarstr31(w, data)
243                 return err
244         }
245         return writeFastHash(w, data)
246 }
247
248 func writeFastHash(w io.Writer, d []byte) error {
249         if len(d) == 0 {
250                 _, err := blockchain.WriteVarstr31(w, nil)
251                 return err
252         }
253         var h [32]byte
254         sha3pool.Sum256(h[:], d)
255         _, err := blockchain.WriteVarstr31(w, h[:])
256         return err
257 }