blockGasSum := uint64(0)
coinbaseAmount := consensus.BlockSubsidy(b.BlockHeader.Height)
b.TransactionStatus = bc.NewTransactionStatus()
-
- for i, tx := range b.Transactions {
- gasStatus, err := ValidateTx(tx, b)
- if !gasStatus.GasValid {
- return errors.Wrapf(err, "validate of transaction %d of %d", i, len(b.Transactions))
+ validateResults := ValidateTxs(b.Transactions, b)
+ for i, validateResult := range validateResults {
+ if !validateResult.gasStatus.GasValid {
+ return errors.Wrapf(validateResult.err, "validate of transaction %d of %d", i, len(b.Transactions))
}
- if err := b.TransactionStatus.SetStatus(i, err != nil); err != nil {
+ if err := b.TransactionStatus.SetStatus(i, validateResult.err != nil); err != nil {
return err
}
- coinbaseAmount += gasStatus.BTMValue
- if blockGasSum += uint64(gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
+
+ coinbaseAmount += validateResult.gasStatus.BTMValue
+ if blockGasSum += uint64(validateResult.gasStatus.GasUsed); blockGasSum > consensus.MaxBlockGas {
return errOverBlockLimit
}
}
import (
"fmt"
"math"
+ "runtime"
+ "sync"
"github.com/bytom/bytom/consensus"
"github.com/bytom/bytom/consensus/segwit"
}
return vs.gasStatus, checkValid(vs, tx.TxHeader)
}
+
+type validateTxWork struct {
+ i int
+ tx *bc.Tx
+ block *bc.Block
+}
+
+// ValidateTxResult is the result of async tx validate
+type ValidateTxResult struct {
+ i int
+ gasStatus *GasState
+ err error
+}
+
+// GetGasState return the gasStatus
+func (r *ValidateTxResult) GetGasState() *GasState {
+ return r.gasStatus
+}
+
+// GetError return the err
+func (r *ValidateTxResult) GetError() error {
+ return r.err
+}
+
+func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, wg *sync.WaitGroup) {
+ for work := range workCh {
+ gasStatus, err := ValidateTx(work.tx, work.block)
+ resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
+ }
+ wg.Done()
+}
+
+// ValidateTxs validates txs in async mode
+func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
+ txSize := len(txs)
+ validateWorkerNum := runtime.NumCPU()
+ //init the goroutine validate worker
+ var wg sync.WaitGroup
+ workCh := make(chan *validateTxWork, txSize)
+ resultCh := make(chan *ValidateTxResult, txSize)
+ for i := 0; i <= validateWorkerNum && i < txSize; i++ {
+ wg.Add(1)
+ go validateTxWorker(workCh, resultCh, &wg)
+ }
+
+ //sent the works
+ for i, tx := range txs {
+ workCh <- &validateTxWork{i: i, tx: tx, block: block}
+ }
+ close(workCh)
+
+ //collect validate results
+ results := make([]*ValidateTxResult, txSize)
+ for i := 0; i < txSize; i++ {
+ result := <-resultCh
+ results[result.i] = result
+ }
+
+ wg.Wait()
+ return results
+}