OSDN Git Service

feat: add cross-chain output (#56)
[bytom/vapor.git] / protocol / validation / tx.go
index abdd0a0..c12c04f 100644 (file)
@@ -1,29 +1,25 @@
 package validation
 
 import (
-       "bytes"
-       "encoding/json"
        "fmt"
        "math"
-       "strconv"
 
        "github.com/vapor/consensus"
        "github.com/vapor/consensus/segwit"
-       "github.com/vapor/crypto"
        "github.com/vapor/errors"
        "github.com/vapor/math/checked"
        "github.com/vapor/protocol/bc"
-       "github.com/vapor/protocol/bc/types"
        "github.com/vapor/protocol/vm"
-       "github.com/vapor/protocol/vm/vmutil"
-       "github.com/vapor/util"
 )
 
+const ruleAA = 142500
+
 // validate transaction error
 var (
        ErrTxVersion                 = errors.New("invalid transaction version")
        ErrWrongTransactionSize      = errors.New("invalid transaction size")
        ErrBadTimeRange              = errors.New("invalid transaction time range")
+       ErrEmptyInputIDs             = errors.New("got the empty InputIDs")
        ErrNotStandardTx             = errors.New("not standard transaction")
        ErrWrongCoinbaseTransaction  = errors.New("wrong coinbase transaction")
        ErrWrongCoinbaseAsset        = errors.New("wrong coinbase assetID")
@@ -202,10 +198,8 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        }
                }
 
-               if len(vs.tx.GasInputIDs) > 0 {
-                       if err := vs.gasStatus.setGasValid(); err != nil {
-                               return err
-                       }
+               if err := vs.gasStatus.setGasValid(); err != nil {
+                       return err
                }
 
                for i, src := range e.Sources {
@@ -216,7 +210,14 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                        }
                }
 
-       case *bc.Output:
+       case *bc.IntraChainOutput:
+               vs2 := *vs
+               vs2.sourcePos = 0
+               if err = checkValidSrc(&vs2, e.Source); err != nil {
+                       return errors.Wrap(err, "checking output source")
+               }
+
+       case *bc.CrossChainOutput:
                vs2 := *vs
                vs2.sourcePos = 0
                if err = checkValidSrc(&vs2, e.Source); err != nil {
@@ -254,7 +255,7 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                if e.SpentOutputId == nil {
                        return errors.Wrap(ErrMissingField, "spend without spent output ID")
                }
-               spentOutput, err := vs.tx.Output(*e.SpentOutputId)
+               spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
                if err != nil {
                        return errors.Wrap(err, "getting spend prevout")
                }
@@ -306,51 +307,8 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
                if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
                        return errors.Wrap(err, "checking coinbase destination")
                }
+               vs.gasStatus.StorageGas = 0
 
-               // special case for coinbase transaction, it's valid unit all the verify has been passed
-               vs.gasStatus.GasValid = true
-       case *bc.Claim:
-               // 对交易的合法性进行验证
-               if e.SpentOutputId == nil {
-                       return errors.Wrap(ErrMissingField, "spend without spent output ID")
-               }
-               spentOutput, err := vs.tx.Output(*e.SpentOutputId)
-               if err != nil {
-                       return errors.Wrap(err, "getting spend prevout")
-               }
-               stack := e.GetPeginwitness()
-               if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
-
-                       return errors.New("pegin-no-witness")
-               }
-
-               if IsValidPeginWitness(stack, *spentOutput) == nil {
-                       return errors.New("PeginWitness invalid")
-               }
-
-               // 判断cliamd的输入是否已经被用
-
-               eq, err := spentOutput.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",
-                               spentOutput.Source.Value.Amount,
-                               spentOutput.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 spend destination")
-               }
-               vs.gasStatus.GasValid = true
        default:
                return fmt.Errorf("entry has unexpected type %T", e)
        }
@@ -358,98 +316,6 @@ func checkValid(vs *validationState, e bc.Entry) (err error) {
        return nil
 }
 
-type MerkleBlock struct {
-       BlockHeader  types.BlockHeader `json:"block_header"`
-       TxHashes     []*bc.Hash        `json:"tx_hashes"`
-       StatusHashes []*bc.Hash        `json:"status_hashes"`
-       Flags        []uint32          `json:"flags"`
-       MatchedTxIDs []*bc.Hash        `json:"matched_tx_ids"`
-}
-
-func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
-       if len(peginWitness) != 5 {
-               return errors.New("peginWitness is error")
-       }
-       amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
-       if err != nil {
-               return err
-       }
-       if consensus.MoneyRange(amount) {
-               return errors.New("Amount out of range")
-       }
-
-       if len(peginWitness[1]) != 32 {
-               return errors.New("The length of gennesisBlockHash is not correct")
-       }
-
-       claimScript := peginWitness[2]
-
-       var rawTx types.Tx
-       err = json.Unmarshal(peginWitness[3], &rawTx)
-       if err != nil {
-               return err
-       }
-       var merkleBlock MerkleBlock
-       err = json.Unmarshal(peginWitness[4], &merkleBlock)
-       if err != nil {
-               return err
-       }
-       // proof验证
-       var flags []uint8
-       for flag := range merkleBlock.Flags {
-               flags = append(flags, uint8(flag))
-       }
-       if !types.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, merkleBlock.BlockHeader.BlockCommitment.TransactionsMerkleRoot) {
-               return errors.New("Merkleblock validation failed")
-       }
-       var txHash bc.Hash = rawTx.ID
-       // 交易进行验证
-       if !checkPeginTx(&rawTx, &prevout, amount, claimScript) {
-               return errors.New("check PeginTx fail")
-       }
-
-       // Check that the merkle proof corresponds to the txid
-       if txHash != *prevout.Source.Ref {
-               return errors.New("prevout hash don't match")
-       }
-       // Check the genesis block corresponds to a valid peg (only one for now)
-       if !bytes.Equal(peginWitness[1], []byte(consensus.ActiveNetParams.ParentGenesisBlockHash)) {
-               return errors.New("ParentGenesisBlockHash don't match")
-       }
-       // TODO Finally, validate peg-in via rpc call
-
-       if util.ValidatePegin {
-               if err := util.IsConfirmedBytomBlock(merkleBlock.BlockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
-                       return err
-               }
-       }
-
-       return nil
-}
-
-func checkPeginTx(rawTx *types.Tx, prevout *bc.Output, claimAmount uint64, claimScript []byte) bool {
-       // Check that transaction matches txid
-       if rawTx.ID != *prevout.Source.Ref {
-               return false
-       }
-       // Check the transaction nout/value matches
-       amount := rawTx.Outputs[prevout.Source.Position].Amount
-       if claimAmount != amount {
-               return false
-       }
-       // Check that the witness program matches the p2ch on the p2sh-p2wsh transaction output
-       federationRedeemScript := vmutil.CalculateContract(consensus.ActiveNetParams.FedpegXPubs, claimScript)
-       scriptHash := crypto.Sha256(federationRedeemScript)
-       controlProg, err := vmutil.P2WSHProgram(scriptHash)
-       if err != nil {
-               return false
-       }
-       if bytes.Equal(rawTx.Outputs[prevout.Source.Position].ControlProgram, controlProg) {
-               return false
-       }
-       return true
-}
-
 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
        if vs == nil {
                return errors.Wrap(ErrMissingField, "empty value source")
@@ -497,11 +363,7 @@ func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
                        return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
                }
                dest = ref.WitnessDestinations[vs.Position]
-       case *bc.Claim:
-               if vs.Position != 0 {
-                       return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
-               }
-               dest = ref.WitnessDestination
+
        default:
                return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
        }
@@ -533,7 +395,7 @@ func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
                return errors.Wrap(ErrMissingField, "missing ref on value destination")
        }
        if vd.Value == nil || vd.Value.AssetId == nil {
-               return errors.Wrap(ErrMissingField, "missing value on value source")
+               return errors.Wrap(ErrMissingField, "missing value on value destination")
        }
 
        e, ok := vs.tx.Entries[*vd.Ref]
@@ -543,7 +405,13 @@ func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
 
        var src *bc.ValueSource
        switch ref := e.(type) {
-       case *bc.Output:
+       case *bc.IntraChainOutput:
+               if vd.Position != 0 {
+                       return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
+               }
+               src = ref.Source
+
+       case *bc.CrossChainOutput:
                if vd.Position != 0 {
                        return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
                }
@@ -562,7 +430,7 @@ func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
                src = ref.Sources[vd.Position]
 
        default:
-               return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
+               return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
        }
 
        if src.Ref == nil || *src.Ref != vs.entryID {
@@ -584,18 +452,25 @@ func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
        return nil
 }
 
-func checkStandardTx(tx *bc.Tx) error {
+func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
+       for _, id := range tx.InputIDs {
+               if blockHeight >= ruleAA && id.IsZero() {
+                       return ErrEmptyInputIDs
+               }
+       }
+
        for _, id := range tx.GasInputIDs {
                spend, err := tx.Spend(id)
                if err != nil {
-                       return err
+                       continue
                }
-               spentOutput, err := tx.Output(*spend.SpentOutputId)
+
+               intraChainSpentOutput, err := tx.IntraChainOutput(*spend.SpentOutputId)
                if err != nil {
                        return err
                }
 
-               if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
+               if !segwit.IsP2WScript(intraChainSpentOutput.ControlProgram.Code) {
                        return ErrNotStandardTx
                }
        }
@@ -606,15 +481,29 @@ func checkStandardTx(tx *bc.Tx) error {
                        return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
                }
 
-               output, ok := e.(*bc.Output)
-               if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
+               var prog []byte
+               switch e := e.(type) {
+               case *bc.IntraChainOutput:
+                       if *e.Source.Value.AssetId != *consensus.BTMAssetID {
+                               continue
+                       }
+                       prog = e.ControlProgram.Code
+
+               case *bc.CrossChainOutput:
+                       if *e.Source.Value.AssetId != *consensus.BTMAssetID {
+                               continue
+                       }
+                       prog = e.ControlProgram.Code
+
+               default:
                        continue
                }
 
-               if !segwit.IsP2WScript(output.ControlProgram.Code) {
+               if !segwit.IsP2WScript(prog) {
                        return ErrNotStandardTx
                }
        }
+
        return nil
 }
 
@@ -626,6 +515,7 @@ func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
        if tx.TimeRange < block.Height {
                return ErrBadTimeRange
        }
+
        return nil
 }
 
@@ -641,9 +531,10 @@ func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
        if err := checkTimeRange(tx, block); err != nil {
                return gasStatus, err
        }
-       if err := checkStandardTx(tx); err != nil {
+       if err := checkStandardTx(tx, block.Height); err != nil {
                return gasStatus, err
        }
+
        vs := &validationState{
                block:     block,
                tx:        tx,