OSDN Git Service

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