OSDN Git Service

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