OSDN Git Service

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