OSDN Git Service

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