OSDN Git Service

14d1b87ffb527a90257a702bd9251f42af1dcfd8
[bytom/vapor.git] / protocol / validation / tx.go
1 package validation
2
3 import (
4         "bytes"
5         "fmt"
6         "math"
7
8         "github.com/vapor/config"
9         "github.com/vapor/consensus"
10         "github.com/vapor/consensus/segwit"
11         "github.com/vapor/errors"
12         "github.com/vapor/math/checked"
13         "github.com/vapor/protocol/bc"
14         "github.com/vapor/protocol/vm"
15 )
16
17 const ruleAA = 142500
18
19 // validate transaction error
20 var (
21         ErrTxVersion                 = errors.New("invalid transaction version")
22         ErrWrongTransactionSize      = errors.New("invalid transaction size")
23         ErrBadTimeRange              = errors.New("invalid transaction time range")
24         ErrEmptyInputIDs             = errors.New("got the empty InputIDs")
25         ErrNotStandardTx             = errors.New("not standard transaction")
26         ErrWrongCoinbaseTransaction  = errors.New("wrong coinbase transaction")
27         ErrWrongCoinbaseAsset        = errors.New("wrong coinbase assetID")
28         ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
29         ErrEmptyResults              = errors.New("transaction has no results")
30         ErrMismatchedAssetID         = errors.New("mismatched assetID")
31         ErrMismatchedPosition        = errors.New("mismatched value source/dest position")
32         ErrMismatchedReference       = errors.New("mismatched reference")
33         ErrMismatchedValue           = errors.New("mismatched value")
34         ErrMissingField              = errors.New("missing required field")
35         ErrNoSource                  = errors.New("no source for value")
36         ErrOverflow                  = errors.New("arithmetic overflow/underflow")
37         ErrPosition                  = errors.New("invalid source or destination position")
38         ErrUnbalanced                = errors.New("unbalanced asset amount between input and output")
39         ErrOverGasCredit             = errors.New("all gas credit has been spend")
40         ErrGasCalculate              = errors.New("gas usage calculate got a math error")
41 )
42
43 // GasState record the gas usage status
44 type GasState struct {
45         BTMValue   uint64
46         GasLeft    int64
47         GasUsed    int64
48         GasValid   bool
49         StorageGas int64
50 }
51
52 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
53         if BTMValue < 0 {
54                 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
55         }
56
57         g.BTMValue = uint64(BTMValue)
58
59         var ok bool
60         if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
61                 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
62         }
63
64         if g.GasLeft > consensus.MaxGasAmount {
65                 g.GasLeft = consensus.MaxGasAmount
66         }
67
68         if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
69                 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
70         }
71         return nil
72 }
73
74 func (g *GasState) setGasValid() error {
75         var ok bool
76         if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
77                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
78         }
79
80         if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
81                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
82         }
83
84         g.GasValid = true
85         return nil
86 }
87
88 func (g *GasState) updateUsage(gasLeft int64) error {
89         if gasLeft < 0 {
90                 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
91         }
92
93         if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
94                 g.GasUsed += gasUsed
95                 g.GasLeft = gasLeft
96         } else {
97                 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
98         }
99
100         if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
101                 return ErrOverGasCredit
102         }
103         return nil
104 }
105
106 // validationState contains the context that must propagate through
107 // the transaction graph when validating entries.
108 type validationState struct {
109         block     *bc.Block
110         tx        *bc.Tx
111         gasStatus *GasState
112         entryID   bc.Hash           // The ID of the nearest enclosing entry
113         sourcePos uint64            // The source position, for validate ValueSources
114         destPos   uint64            // The destination position, for validate ValueDestinations
115         cache     map[bc.Hash]error // Memoized per-entry validation results
116 }
117
118 func checkValid(vs *validationState, e bc.Entry) (err error) {
119         var ok bool
120         entryID := bc.EntryID(e)
121         if err, ok = vs.cache[entryID]; ok {
122                 return err
123         }
124
125         defer func() {
126                 vs.cache[entryID] = err
127         }()
128
129         switch e := e.(type) {
130         case *bc.TxHeader:
131                 for i, resID := range e.ResultIds {
132                         resultEntry := vs.tx.Entries[*resID]
133                         vs2 := *vs
134                         vs2.entryID = *resID
135                         if err = checkValid(&vs2, resultEntry); err != nil {
136                                 return errors.Wrapf(err, "checking result %d", i)
137                         }
138                 }
139
140                 if e.Version == 1 && len(e.ResultIds) == 0 {
141                         return ErrEmptyResults
142                 }
143
144         case *bc.Mux:
145                 parity := make(map[bc.AssetID]int64)
146                 for i, src := range e.Sources {
147                         if src.Value.Amount > math.MaxInt64 {
148                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
149                         }
150                         sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
151                         if !ok {
152                                 return errors.WithDetailf(ErrOverflow, "adding %d units of asset %x from mux source %d to total %d overflows int64", src.Value.Amount, src.Value.AssetId.Bytes(), i, parity[*src.Value.AssetId])
153                         }
154                         parity[*src.Value.AssetId] = sum
155                 }
156
157                 for i, dest := range e.WitnessDestinations {
158                         sum, ok := parity[*dest.Value.AssetId]
159                         if !ok {
160                                 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
161                         }
162                         if dest.Value.Amount > math.MaxInt64 {
163                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
164                         }
165                         diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
166                         if !ok {
167                                 return errors.WithDetailf(ErrOverflow, "subtracting %d units of asset %x from mux destination %d from total %d underflows int64", dest.Value.Amount, dest.Value.AssetId.Bytes(), i, sum)
168                         }
169                         parity[*dest.Value.AssetId] = diff
170                 }
171
172                 for assetID, amount := range parity {
173                         if assetID == *consensus.BTMAssetID {
174                                 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
175                                         return err
176                                 }
177                         } else if amount != 0 {
178                                 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
179                         }
180                 }
181
182                 for _, BTMInputID := range vs.tx.GasInputIDs {
183                         e, ok := vs.tx.Entries[BTMInputID]
184                         if !ok {
185                                 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
186                         }
187
188                         vs2 := *vs
189                         vs2.entryID = BTMInputID
190                         if err := checkValid(&vs2, e); err != nil {
191                                 return errors.Wrap(err, "checking gas input")
192                         }
193                 }
194
195                 for i, dest := range e.WitnessDestinations {
196                         vs2 := *vs
197                         vs2.destPos = uint64(i)
198                         if err = checkValidDest(&vs2, dest); err != nil {
199                                 return errors.Wrapf(err, "checking mux destination %d", i)
200                         }
201                 }
202
203                 if err := vs.gasStatus.setGasValid(); err != nil {
204                         return err
205                 }
206
207                 for i, src := range e.Sources {
208                         vs2 := *vs
209                         vs2.sourcePos = uint64(i)
210                         if err = checkValidSrc(&vs2, src); err != nil {
211                                 return errors.Wrapf(err, "checking mux source %d", i)
212                         }
213                 }
214
215         case *bc.IntraChainOutput:
216                 vs2 := *vs
217                 vs2.sourcePos = 0
218                 if err = checkValidSrc(&vs2, e.Source); err != nil {
219                         return errors.Wrap(err, "checking output source")
220                 }
221
222         case *bc.CrossChainOutput:
223                 vs2 := *vs
224                 vs2.sourcePos = 0
225                 if err = checkValidSrc(&vs2, e.Source); err != nil {
226                         return errors.Wrap(err, "checking output source")
227                 }
228
229         case *bc.VoteOutput:
230                 vs2 := *vs
231                 vs2.sourcePos = 0
232                 if err = checkValidSrc(&vs2, e.Source); err != nil {
233                         return errors.Wrap(err, "checking vote output source")
234                 }
235
236         case *bc.Retirement:
237                 vs2 := *vs
238                 vs2.sourcePos = 0
239                 if err = checkValidSrc(&vs2, e.Source); err != nil {
240                         return errors.Wrap(err, "checking retirement source")
241                 }
242
243         case *bc.CrossChainInput:
244                 _, err := vm.Verify(NewTxVMContext(vs, e, e.ControlProgram, e.WitnessArguments), consensus.DefaultGasCredit)
245                 if err != nil {
246                         return errors.Wrap(err, "checking cross-chain input control program")
247                 }
248
249                 vs2 := *vs
250                 vs2.destPos = 0
251                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
252                         return errors.Wrap(err, "checking cross-chain input destination")
253                 }
254
255         case *bc.Spend:
256                 if e.SpentOutputId == nil {
257                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
258                 }
259                 var (
260                         controlProgram *bc.Program
261                         value          *bc.AssetAmount
262                 )
263                 entryOutput, err := vs.tx.Entry(*e.SpentOutputId)
264                 if err != nil {
265                         return errors.Wrap(err, "getting spend prevout")
266                 }
267
268                 switch output := entryOutput.(type) {
269                 case *bc.IntraChainOutput:
270                         controlProgram = output.ControlProgram
271                         value = output.Source.Value
272                 case *bc.VoteOutput:
273                         controlProgram = output.ControlProgram
274                         value = output.Source.Value
275                 default:
276                         return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", e.SpentOutputId.Bytes(), entryOutput)
277                 }
278
279                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, controlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
280                 if err != nil {
281                         return errors.Wrap(err, "checking control program")
282                 }
283                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
284                         return err
285                 }
286
287                 eq, err := value.Equal(e.WitnessDestination.Value)
288                 if err != nil {
289                         return err
290                 }
291                 if !eq {
292                         return errors.WithDetailf(
293                                 ErrMismatchedValue,
294                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
295                                 value.Amount,
296                                 value.AssetId.Bytes(),
297                                 e.WitnessDestination.Value.Amount,
298                                 e.WitnessDestination.Value.AssetId.Bytes(),
299                         )
300                 }
301                 vs2 := *vs
302                 vs2.destPos = 0
303                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
304                         return errors.Wrap(err, "checking spend destination")
305                 }
306
307         case *bc.Coinbase:
308                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
309                         return ErrWrongCoinbaseTransaction
310                 }
311
312                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
313                         return ErrWrongCoinbaseAsset
314                 }
315
316                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
317                         return ErrCoinbaseArbitraryOversize
318                 }
319
320                 vs2 := *vs
321                 vs2.destPos = 0
322                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
323                         return errors.Wrap(err, "checking coinbase destination")
324                 }
325                 vs.gasStatus.StorageGas = 0
326
327         default:
328                 return fmt.Errorf("entry has unexpected type %T", e)
329         }
330
331         return nil
332 }
333
334 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
335         if vs == nil {
336                 return errors.Wrap(ErrMissingField, "empty value source")
337         }
338         if vs.Ref == nil {
339                 return errors.Wrap(ErrMissingField, "missing ref on value source")
340         }
341         if vs.Value == nil || vs.Value.AssetId == nil {
342                 return errors.Wrap(ErrMissingField, "missing value on value source")
343         }
344
345         e, ok := vstate.tx.Entries[*vs.Ref]
346         if !ok {
347                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
348         }
349
350         vstate2 := *vstate
351         vstate2.entryID = *vs.Ref
352         if err := checkValid(&vstate2, e); err != nil {
353                 return errors.Wrap(err, "checking value source")
354         }
355
356         var dest *bc.ValueDestination
357         switch ref := e.(type) {
358         case *bc.Coinbase:
359                 if vs.Position != 0 {
360                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
361                 }
362                 dest = ref.WitnessDestination
363
364         case *bc.CrossChainInput:
365                 if vs.Position != 0 {
366                         return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
367                 }
368                 dest = ref.WitnessDestination
369
370         case *bc.Spend:
371                 if vs.Position != 0 {
372                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
373                 }
374                 dest = ref.WitnessDestination
375
376         case *bc.Mux:
377                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
378                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
379                 }
380                 dest = ref.WitnessDestinations[vs.Position]
381
382         default:
383                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
384         }
385
386         if dest.Ref == nil || *dest.Ref != vstate.entryID {
387                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
388         }
389
390         if dest.Position != vstate.sourcePos {
391                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
392         }
393
394         eq, err := dest.Value.Equal(vs.Value)
395         if err != nil {
396                 return errors.Sub(ErrMissingField, err)
397         }
398         if !eq {
399                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
400         }
401
402         return nil
403 }
404
405 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
406         if vd == nil {
407                 return errors.Wrap(ErrMissingField, "empty value destination")
408         }
409         if vd.Ref == nil {
410                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
411         }
412         if vd.Value == nil || vd.Value.AssetId == nil {
413                 return errors.Wrap(ErrMissingField, "missing value on value destination")
414         }
415
416         e, ok := vs.tx.Entries[*vd.Ref]
417         if !ok {
418                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
419         }
420
421         var src *bc.ValueSource
422         switch ref := e.(type) {
423         case *bc.IntraChainOutput:
424                 if vd.Position != 0 {
425                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
426                 }
427                 src = ref.Source
428
429         case *bc.CrossChainOutput:
430                 if vd.Position != 0 {
431                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
432                 }
433                 src = ref.Source
434
435         case *bc.VoteOutput:
436                 if vd.Position != 0 {
437                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
438                 }
439                 src = ref.Source
440
441         case *bc.Retirement:
442                 if vd.Position != 0 {
443                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
444                 }
445                 src = ref.Source
446
447         case *bc.Mux:
448                 if vd.Position >= uint64(len(ref.Sources)) {
449                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
450                 }
451                 src = ref.Sources[vd.Position]
452
453         default:
454                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
455         }
456
457         if src.Ref == nil || *src.Ref != vs.entryID {
458                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
459         }
460
461         if src.Position != vs.destPos {
462                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
463         }
464
465         eq, err := src.Value.Equal(vd.Value)
466         if err != nil {
467                 return errors.Sub(ErrMissingField, err)
468         }
469         if !eq {
470                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
471         }
472
473         return nil
474 }
475
476 func checkFedaration(tx *bc.Tx) error {
477         for _, id := range tx.InputIDs {
478                 switch inp := tx.Entries[id].(type) {
479                 case *bc.CrossChainInput:
480                         fedProg := config.FederationProgrom(config.CommonConfig)
481                         if !bytes.Equal(inp.ControlProgram.Code, fedProg) {
482                                 return errors.New("The federal controlProgram is incorrect")
483                         }
484                 default:
485                         continue
486                 }
487         }
488         return nil
489 }
490
491 func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
492         for _, id := range tx.InputIDs {
493                 if blockHeight >= ruleAA && id.IsZero() {
494                         return ErrEmptyInputIDs
495                 }
496         }
497
498         if err := checkFedaration(tx); err != nil {
499                 return err
500         }
501
502         for _, id := range tx.GasInputIDs {
503                 spend, err := tx.Spend(id)
504                 if err != nil {
505                         continue
506                 }
507
508                 code := []byte{}
509                 outputEntry, err := tx.Entry(*spend.SpentOutputId)
510                 if err != nil {
511                         return err
512                 }
513                 switch output := outputEntry.(type) {
514                 case *bc.IntraChainOutput:
515                         code = output.ControlProgram.Code
516                 case *bc.VoteOutput:
517                         code = output.ControlProgram.Code
518                 default:
519                         return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", id.Bytes(), outputEntry)
520                 }
521
522                 if !segwit.IsP2WScript(code) {
523                         return ErrNotStandardTx
524                 }
525         }
526         return nil
527 }
528
529 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
530         if tx.TimeRange == 0 {
531                 return nil
532         }
533
534         if tx.TimeRange < block.Height {
535                 return ErrBadTimeRange
536         }
537
538         return nil
539 }
540
541 // ValidateTx validates a transaction.
542 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
543         gasStatus := &GasState{GasValid: false}
544         if block.Version == 1 && tx.Version != 1 {
545                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
546         }
547         if tx.SerializedSize == 0 {
548                 return gasStatus, ErrWrongTransactionSize
549         }
550         if err := checkTimeRange(tx, block); err != nil {
551                 return gasStatus, err
552         }
553         if err := checkStandardTx(tx, block.Height); err != nil {
554                 return gasStatus, err
555         }
556
557         vs := &validationState{
558                 block:     block,
559                 tx:        tx,
560                 entryID:   tx.ID,
561                 gasStatus: gasStatus,
562                 cache:     make(map[bc.Hash]error),
563         }
564         return vs.gasStatus, checkValid(vs, tx.TxHeader)
565 }