OSDN Git Service

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