OSDN Git Service

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