OSDN Git Service

add free gas (#295)
[bytom/vapor.git] / protocol / validation / tx.go
index 14d1b87..d360854 100644 (file)
@@ -1,20 +1,21 @@
 package validation
 
 import (
-       "bytes"
        "fmt"
        "math"
+       "sync"
 
        "github.com/vapor/config"
        "github.com/vapor/consensus"
-       "github.com/vapor/consensus/segwit"
        "github.com/vapor/errors"
        "github.com/vapor/math/checked"
        "github.com/vapor/protocol/bc"
        "github.com/vapor/protocol/vm"
 )
 
-const ruleAA = 142500
+const (
+       validateWorkerNum = 32
+)
 
 // validate transaction error
 var (
@@ -38,6 +39,8 @@ var (
        ErrUnbalanced                = errors.New("unbalanced asset amount between input and output")
        ErrOverGasCredit             = errors.New("all gas credit has been spend")
        ErrGasCalculate              = errors.New("gas usage calculate got a math error")
+       ErrVotePubKey                = errors.New("invalid public key of vote")
+       ErrVoteOutputAmount          = errors.New("invalid vote amount")
 )
 
 // GasState record the gas usage status
@@ -55,17 +58,20 @@ func (g *GasState) setGas(BTMValue int64, txSize int64) error {
        }
 
        g.BTMValue = uint64(BTMValue)
-
        var ok bool
-       if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
+       if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.ActiveNetParams.VMGasRate); !ok {
                return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
        }
 
-       if g.GasLeft > consensus.MaxGasAmount {
-               g.GasLeft = consensus.MaxGasAmount
+       if g.GasLeft, ok = checked.AddInt64(g.GasLeft, consensus.ActiveNetParams.DefaultGasCredit); !ok {
+               return errors.Wrap(ErrGasCalculate, "setGas calc free gas")
+       }
+
+       if g.GasLeft > consensus.ActiveNetParams.MaxGasAmount {
+               g.GasLeft = consensus.ActiveNetParams.MaxGasAmount
        }
 
-       if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
+       if g.StorageGas, ok = checked.MulInt64(txSize, consensus.ActiveNetParams.StorageGasRate); !ok {
                return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
        }
        return nil
@@ -97,7 +103,7 @@ func (g *GasState) updateUsage(gasLeft int64) error {
                return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
        }
 
-       if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
+       if !g.GasValid && (g.GasUsed > consensus.ActiveNetParams.DefaultGasCredit || g.StorageGas > g.GasLeft) {
                return ErrOverGasCredit
        }
        return nil
@@ -169,16 +175,19 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        parity[*dest.Value.AssetId] = diff
                }
 
+               btmAmount := int64(0)
                for assetID, amount := range parity {
                        if assetID == *consensus.BTMAssetID {
-                               if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
-                                       return err
-                               }
+                               btmAmount = amount
                        } else if amount != 0 {
                                return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
                        }
                }
 
+               if err = vs.gasStatus.setGas(btmAmount, int64(vs.tx.SerializedSize)); err != nil {
+                       return err
+               }
+
                for _, BTMInputID := range vs.tx.GasInputIDs {
                        e, ok := vs.tx.Entries[BTMInputID]
                        if !ok {
@@ -227,6 +236,9 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                }
 
        case *bc.VoteOutput:
+               if len(e.Vote) != 64 {
+                       return ErrVotePubKey
+               }
                vs2 := *vs
                vs2.sourcePos = 0
                if err = checkValidSrc(&vs2, e.Source); err != nil {
@@ -241,42 +253,63 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                }
 
        case *bc.CrossChainInput:
-               _, err := vm.Verify(NewTxVMContext(vs, e, e.ControlProgram, e.WitnessArguments), consensus.DefaultGasCredit)
+               if e.MainchainOutputId == nil {
+                       return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
+               }
+
+               mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
                if err != nil {
+                       return errors.Wrap(err, "getting mainchain output")
+               }
+
+               assetID := e.AssetDefinition.ComputeAssetID()
+               if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
+                       return errors.New("incorrect asset_id while checking CrossChainInput")
+               }
+
+               prog := &bc.Program{
+                       VmVersion: e.ControlProgram.VmVersion,
+                       Code:      config.FederationWScript(config.CommonConfig),
+               }
+
+               if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
                        return errors.Wrap(err, "checking cross-chain input control program")
                }
 
+               eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
+               if err != nil {
+                       return err
+               }
+
+               if !eq {
+                       return errors.WithDetailf(
+                               ErrMismatchedValue,
+                               "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
+                               mainchainOutput.Source.Value.Amount,
+                               mainchainOutput.Source.Value.AssetId.Bytes(),
+                               e.WitnessDestination.Value.Amount,
+                               e.WitnessDestination.Value.AssetId.Bytes(),
+                       )
+               }
+
                vs2 := *vs
                vs2.destPos = 0
                if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
                        return errors.Wrap(err, "checking cross-chain input destination")
                }
+               vs.gasStatus.StorageGas = 0
 
        case *bc.Spend:
                if e.SpentOutputId == nil {
                        return errors.Wrap(ErrMissingField, "spend without spent output ID")
                }
-               var (
-                       controlProgram *bc.Program
-                       value          *bc.AssetAmount
-               )
-               entryOutput, err := vs.tx.Entry(*e.SpentOutputId)
+
+               spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
                if err != nil {
                        return errors.Wrap(err, "getting spend prevout")
                }
 
-               switch output := entryOutput.(type) {
-               case *bc.IntraChainOutput:
-                       controlProgram = output.ControlProgram
-                       value = output.Source.Value
-               case *bc.VoteOutput:
-                       controlProgram = output.ControlProgram
-                       value = output.Source.Value
-               default:
-                       return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", e.SpentOutputId.Bytes(), entryOutput)
-               }
-
-               gasLeft, err := vm.Verify(NewTxVMContext(vs, e, controlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
+               gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
                if err != nil {
                        return errors.Wrap(err, "checking control program")
                }
@@ -284,7 +317,7 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        return err
                }
 
-               eq, err := value.Equal(e.WitnessDestination.Value)
+               eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
                if err != nil {
                        return err
                }
@@ -292,8 +325,8 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        return errors.WithDetailf(
                                ErrMismatchedValue,
                                "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
-                               value.Amount,
-                               value.AssetId.Bytes(),
+                               spentOutput.Source.Value.Amount,
+                               spentOutput.Source.Value.AssetId.Bytes(),
                                e.WitnessDestination.Value.Amount,
                                e.WitnessDestination.Value.AssetId.Bytes(),
                        )
@@ -304,6 +337,48 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        return errors.Wrap(err, "checking spend destination")
                }
 
+       case *bc.VetoInput:
+               if e.SpentOutputId == nil {
+                       return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
+               }
+
+               voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
+               if err != nil {
+                       return errors.Wrap(err, "getting vetoInput prevout")
+               }
+
+               if len(voteOutput.Vote) != 64 {
+                       return ErrVotePubKey
+               }
+
+               gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
+               if err != nil {
+                       return errors.Wrap(err, "checking control program")
+               }
+               if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
+                       return err
+               }
+
+               eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
+               if err != nil {
+                       return err
+               }
+               if !eq {
+                       return errors.WithDetailf(
+                               ErrMismatchedValue,
+                               "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
+                               voteOutput.Source.Value.Amount,
+                               voteOutput.Source.Value.AssetId.Bytes(),
+                               e.WitnessDestination.Value.Amount,
+                               e.WitnessDestination.Value.AssetId.Bytes(),
+                       )
+               }
+               vs2 := *vs
+               vs2.destPos = 0
+               if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
+                       return errors.Wrap(err, "checking vetoInput destination")
+               }
+
        case *bc.Coinbase:
                if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
                        return ErrWrongCoinbaseTransaction
@@ -313,7 +388,7 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        return ErrWrongCoinbaseAsset
                }
 
-               if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
+               if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
                        return ErrCoinbaseArbitraryOversize
                }
 
@@ -355,6 +430,12 @@ func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
 
        var dest *bc.ValueDestination
        switch ref := e.(type) {
+       case *bc.VetoInput:
+               if vs.Position != 0 {
+                       return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
+               }
+               dest = ref.WitnessDestination
+
        case *bc.Coinbase:
                if vs.Position != 0 {
                        return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
@@ -473,56 +554,12 @@ func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
        return nil
 }
 
-func checkFedaration(tx *bc.Tx) error {
+func checkInputID(tx *bc.Tx, blockHeight uint64) error {
        for _, id := range tx.InputIDs {
-               switch inp := tx.Entries[id].(type) {
-               case *bc.CrossChainInput:
-                       fedProg := config.FederationProgrom(config.CommonConfig)
-                       if !bytes.Equal(inp.ControlProgram.Code, fedProg) {
-                               return errors.New("The federal controlProgram is incorrect")
-                       }
-               default:
-                       continue
-               }
-       }
-       return nil
-}
-
-func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
-       for _, id := range tx.InputIDs {
-               if blockHeight >= ruleAA && id.IsZero() {
+               if id.IsZero() {
                        return ErrEmptyInputIDs
                }
        }
-
-       if err := checkFedaration(tx); err != nil {
-               return err
-       }
-
-       for _, id := range tx.GasInputIDs {
-               spend, err := tx.Spend(id)
-               if err != nil {
-                       continue
-               }
-
-               code := []byte{}
-               outputEntry, err := tx.Entry(*spend.SpentOutputId)
-               if err != nil {
-                       return err
-               }
-               switch output := outputEntry.(type) {
-               case *bc.IntraChainOutput:
-                       code = output.ControlProgram.Code
-               case *bc.VoteOutput:
-                       code = output.ControlProgram.Code
-               default:
-                       return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", id.Bytes(), outputEntry)
-               }
-
-               if !segwit.IsP2WScript(code) {
-                       return ErrNotStandardTx
-               }
-       }
        return nil
 }
 
@@ -550,7 +587,7 @@ func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
        if err := checkTimeRange(tx, block); err != nil {
                return gasStatus, err
        }
-       if err := checkStandardTx(tx, block.Height); err != nil {
+       if err := checkInputID(tx, block.Height); err != nil {
                return gasStatus, err
        }
 
@@ -563,3 +600,71 @@ func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
        }
        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, closeCh chan struct{}, wg *sync.WaitGroup) {
+       for {
+               select {
+               case work := <-workCh:
+                       gasStatus, err := ValidateTx(work.tx, work.block)
+                       resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
+               case <-closeCh:
+                       wg.Done()
+                       return
+               }
+       }
+}
+
+// ValidateTxs validates txs in async mode
+func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
+       txSize := len(txs)
+       //init the goroutine validate worker
+       var wg sync.WaitGroup
+       workCh := make(chan *validateTxWork, txSize)
+       resultCh := make(chan *ValidateTxResult, txSize)
+       closeCh := make(chan struct{})
+       for i := 0; i <= validateWorkerNum && i < txSize; i++ {
+               wg.Add(1)
+               go validateTxWorker(workCh, resultCh, closeCh, &wg)
+       }
+
+       //sent the works
+       for i, tx := range txs {
+               workCh <- &validateTxWork{i: i, tx: tx, block: block}
+       }
+
+       //collect validate results
+       results := make([]*ValidateTxResult, txSize)
+       for i := 0; i < txSize; i++ {
+               result := <-resultCh
+               results[result.i] = result
+       }
+
+       close(closeCh)
+       wg.Wait()
+       close(workCh)
+       close(resultCh)
+       return results
+}