OSDN Git Service

versoin1.1.9 (#594)
[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/bytom/vapor/common"
10         "github.com/bytom/vapor/config"
11         "github.com/bytom/vapor/consensus"
12         "github.com/bytom/vapor/errors"
13         "github.com/bytom/vapor/math/checked"
14         "github.com/bytom/vapor/protocol/bc"
15         "github.com/bytom/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 := &bc.Program{
279                         VmVersion: e.AssetDefinition.IssuanceProgram.VmVersion,
280                         Code:      e.AssetDefinition.IssuanceProgram.Code,
281                 }
282
283                 if !common.IsOpenFederationIssueAsset(e.RawDefinitionByte) {
284                         prog.Code = config.FederationWScript(config.CommonConfig, vs.block.Height)
285                 }
286
287                 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
288                         return errors.Wrap(err, "checking cross-chain input control program")
289                 }
290
291                 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
292                 if err != nil {
293                         return err
294                 }
295
296                 if !eq {
297                         return errors.WithDetailf(
298                                 ErrMismatchedValue,
299                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
300                                 mainchainOutput.Source.Value.Amount,
301                                 mainchainOutput.Source.Value.AssetId.Bytes(),
302                                 e.WitnessDestination.Value.Amount,
303                                 e.WitnessDestination.Value.AssetId.Bytes(),
304                         )
305                 }
306
307                 vs2 := *vs
308                 vs2.destPos = 0
309                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
310                         return errors.Wrap(err, "checking cross-chain input destination")
311                 }
312                 vs.gasStatus.StorageGas = 0
313
314         case *bc.Spend:
315                 if e.SpentOutputId == nil {
316                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
317                 }
318
319                 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
320                 if err != nil {
321                         return errors.Wrap(err, "getting spend prevout")
322                 }
323
324                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
325                 if err != nil {
326                         return errors.Wrap(err, "checking control program")
327                 }
328                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
329                         return err
330                 }
331
332                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
333                 if err != nil {
334                         return err
335                 }
336                 if !eq {
337                         return errors.WithDetailf(
338                                 ErrMismatchedValue,
339                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
340                                 spentOutput.Source.Value.Amount,
341                                 spentOutput.Source.Value.AssetId.Bytes(),
342                                 e.WitnessDestination.Value.Amount,
343                                 e.WitnessDestination.Value.AssetId.Bytes(),
344                         )
345                 }
346                 vs2 := *vs
347                 vs2.destPos = 0
348                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
349                         return errors.Wrap(err, "checking spend destination")
350                 }
351
352         case *bc.VetoInput:
353                 if e.SpentOutputId == nil {
354                         return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
355                 }
356
357                 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
358                 if err != nil {
359                         return errors.Wrap(err, "getting vetoInput prevout")
360                 }
361
362                 if len(voteOutput.Vote) != 64 {
363                         return ErrVotePubKey
364                 }
365
366                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
367                 if err != nil {
368                         return errors.Wrap(err, "checking control program")
369                 }
370                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
371                         return err
372                 }
373
374                 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
375                 if err != nil {
376                         return err
377                 }
378                 if !eq {
379                         return errors.WithDetailf(
380                                 ErrMismatchedValue,
381                                 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
382                                 voteOutput.Source.Value.Amount,
383                                 voteOutput.Source.Value.AssetId.Bytes(),
384                                 e.WitnessDestination.Value.Amount,
385                                 e.WitnessDestination.Value.AssetId.Bytes(),
386                         )
387                 }
388                 vs2 := *vs
389                 vs2.destPos = 0
390                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
391                         return errors.Wrap(err, "checking vetoInput destination")
392                 }
393
394         case *bc.Coinbase:
395                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
396                         return ErrWrongCoinbaseTransaction
397                 }
398
399                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
400                         return ErrWrongCoinbaseAsset
401                 }
402
403                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
404                         return ErrCoinbaseArbitraryOversize
405                 }
406
407                 vs2 := *vs
408                 vs2.destPos = 0
409                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
410                         return errors.Wrap(err, "checking coinbase destination")
411                 }
412                 vs.gasStatus.StorageGas = 0
413
414         default:
415                 return fmt.Errorf("entry has unexpected type %T", e)
416         }
417
418         return nil
419 }
420
421 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
422         if vs == nil {
423                 return errors.Wrap(ErrMissingField, "empty value source")
424         }
425         if vs.Ref == nil {
426                 return errors.Wrap(ErrMissingField, "missing ref on value source")
427         }
428         if vs.Value == nil || vs.Value.AssetId == nil {
429                 return errors.Wrap(ErrMissingField, "missing value on value source")
430         }
431
432         e, ok := vstate.tx.Entries[*vs.Ref]
433         if !ok {
434                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
435         }
436
437         vstate2 := *vstate
438         vstate2.entryID = *vs.Ref
439         if err := checkValid(&vstate2, e); err != nil {
440                 return errors.Wrap(err, "checking value source")
441         }
442
443         var dest *bc.ValueDestination
444         switch ref := e.(type) {
445         case *bc.VetoInput:
446                 if vs.Position != 0 {
447                         return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
448                 }
449                 dest = ref.WitnessDestination
450
451         case *bc.Coinbase:
452                 if vs.Position != 0 {
453                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
454                 }
455                 dest = ref.WitnessDestination
456
457         case *bc.CrossChainInput:
458                 if vs.Position != 0 {
459                         return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
460                 }
461                 dest = ref.WitnessDestination
462
463         case *bc.Spend:
464                 if vs.Position != 0 {
465                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
466                 }
467                 dest = ref.WitnessDestination
468
469         case *bc.Mux:
470                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
471                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
472                 }
473                 dest = ref.WitnessDestinations[vs.Position]
474
475         default:
476                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
477         }
478
479         if dest.Ref == nil || *dest.Ref != vstate.entryID {
480                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
481         }
482
483         if dest.Position != vstate.sourcePos {
484                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
485         }
486
487         eq, err := dest.Value.Equal(vs.Value)
488         if err != nil {
489                 return errors.Sub(ErrMissingField, err)
490         }
491         if !eq {
492                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
493         }
494
495         return nil
496 }
497
498 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
499         if vd == nil {
500                 return errors.Wrap(ErrMissingField, "empty value destination")
501         }
502         if vd.Ref == nil {
503                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
504         }
505         if vd.Value == nil || vd.Value.AssetId == nil {
506                 return errors.Wrap(ErrMissingField, "missing value on value destination")
507         }
508
509         e, ok := vs.tx.Entries[*vd.Ref]
510         if !ok {
511                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
512         }
513
514         var src *bc.ValueSource
515         switch ref := e.(type) {
516         case *bc.IntraChainOutput:
517                 if vd.Position != 0 {
518                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
519                 }
520                 src = ref.Source
521
522         case *bc.CrossChainOutput:
523                 if vd.Position != 0 {
524                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
525                 }
526                 src = ref.Source
527
528         case *bc.VoteOutput:
529                 if vd.Position != 0 {
530                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
531                 }
532                 src = ref.Source
533
534         case *bc.Retirement:
535                 if vd.Position != 0 {
536                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
537                 }
538                 src = ref.Source
539
540         case *bc.Mux:
541                 if vd.Position >= uint64(len(ref.Sources)) {
542                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
543                 }
544                 src = ref.Sources[vd.Position]
545
546         default:
547                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
548         }
549
550         if src.Ref == nil || *src.Ref != vs.entryID {
551                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
552         }
553
554         if src.Position != vs.destPos {
555                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
556         }
557
558         eq, err := src.Value.Equal(vd.Value)
559         if err != nil {
560                 return errors.Sub(ErrMissingField, err)
561         }
562         if !eq {
563                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
564         }
565
566         return nil
567 }
568
569 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
570         for _, id := range tx.InputIDs {
571                 if id.IsZero() {
572                         return ErrEmptyInputIDs
573                 }
574         }
575         return nil
576 }
577
578 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
579         if tx.TimeRange == 0 {
580                 return nil
581         }
582
583         if tx.TimeRange < block.Height {
584                 return ErrBadTimeRange
585         }
586
587         return nil
588 }
589
590 func applySoftFork001(vs *validationState, err error) {
591         if err == nil || vs.block.Height < consensus.ActiveNetParams.SoftForkPoint[consensus.SoftFork001] {
592                 return
593         }
594
595         if rootErr := errors.Root(err); rootErr == ErrVotePubKey || rootErr == ErrVoteOutputAmount || rootErr == ErrVoteOutputAseet {
596                 vs.gasStatus.GasValid = false
597         }
598 }
599
600 // ValidateTx validates a transaction.
601 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
602         gasStatus := &GasState{GasValid: false}
603         if block.Version == 1 && tx.Version != 1 {
604                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
605         }
606         if tx.SerializedSize == 0 {
607                 return gasStatus, ErrWrongTransactionSize
608         }
609         if err := checkTimeRange(tx, block); err != nil {
610                 return gasStatus, err
611         }
612         if err := checkInputID(tx, block.Height); err != nil {
613                 return gasStatus, err
614         }
615
616         vs := &validationState{
617                 block:     block,
618                 tx:        tx,
619                 entryID:   tx.ID,
620                 gasStatus: gasStatus,
621                 cache:     make(map[bc.Hash]error),
622         }
623
624         err := checkValid(vs, tx.TxHeader)
625         applySoftFork001(vs, err)
626         return vs.gasStatus, err
627 }
628
629 type validateTxWork struct {
630         i     int
631         tx    *bc.Tx
632         block *bc.Block
633 }
634
635 // ValidateTxResult is the result of async tx validate
636 type ValidateTxResult struct {
637         i         int
638         gasStatus *GasState
639         err       error
640 }
641
642 // GetGasState return the gasStatus
643 func (r *ValidateTxResult) GetGasState() *GasState {
644         return r.gasStatus
645 }
646
647 // GetError return the err
648 func (r *ValidateTxResult) GetError() error {
649         return r.err
650 }
651
652 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
653         for {
654                 select {
655                 case work := <-workCh:
656                         gasStatus, err := ValidateTx(work.tx, work.block)
657                         resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
658                 case <-closeCh:
659                         wg.Done()
660                         return
661                 }
662         }
663 }
664
665 // ValidateTxs validates txs in async mode
666 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
667         txSize := len(txs)
668         validateWorkerNum := runtime.NumCPU()
669         //init the goroutine validate worker
670         var wg sync.WaitGroup
671         workCh := make(chan *validateTxWork, txSize)
672         resultCh := make(chan *ValidateTxResult, txSize)
673         closeCh := make(chan struct{})
674         for i := 0; i <= validateWorkerNum && i < txSize; i++ {
675                 wg.Add(1)
676                 go validateTxWorker(workCh, resultCh, closeCh, &wg)
677         }
678
679         //sent the works
680         for i, tx := range txs {
681                 workCh <- &validateTxWork{i: i, tx: tx, block: block}
682         }
683
684         //collect validate results
685         results := make([]*ValidateTxResult, txSize)
686         for i := 0; i < txSize; i++ {
687                 result := <-resultCh
688                 results[result.i] = result
689         }
690
691         close(closeCh)
692         wg.Wait()
693         close(workCh)
694         close(resultCh)
695         return results
696 }