9 "github.com/vapor/common"
10 "github.com/vapor/config"
11 "github.com/vapor/consensus"
12 "github.com/vapor/errors"
13 "github.com/vapor/math/checked"
14 "github.com/vapor/protocol/bc"
15 "github.com/vapor/protocol/vm"
18 // validate transaction error
20 ErrTxVersion = errors.New("invalid transaction version")
21 ErrWrongTransactionSize = errors.New("invalid transaction size")
22 ErrBadTimeRange = errors.New("invalid transaction time range")
23 ErrEmptyInputIDs = errors.New("got the empty InputIDs")
24 ErrNotStandardTx = errors.New("not standard transaction")
25 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
26 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
27 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
28 ErrEmptyResults = errors.New("transaction has no results")
29 ErrMismatchedAssetID = errors.New("mismatched assetID")
30 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
31 ErrMismatchedReference = errors.New("mismatched reference")
32 ErrMismatchedValue = errors.New("mismatched value")
33 ErrMissingField = errors.New("missing required field")
34 ErrNoSource = errors.New("no source for value")
35 ErrOverflow = errors.New("arithmetic overflow/underflow")
36 ErrPosition = errors.New("invalid source or destination position")
37 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
38 ErrOverGasCredit = errors.New("all gas credit has been spend")
39 ErrGasCalculate = errors.New("gas usage calculate got a math error")
40 ErrVotePubKey = errors.New("invalid public key of vote")
41 ErrVoteOutputAmount = errors.New("invalid vote amount")
42 ErrVoteOutputAseet = errors.New("incorrect asset_id while checking vote asset")
45 // GasState record the gas usage status
46 type GasState struct {
54 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
56 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
59 g.BTMValue = uint64(BTMValue)
61 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.ActiveNetParams.VMGasRate); !ok {
62 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
65 if g.GasLeft, ok = checked.AddInt64(g.GasLeft, consensus.ActiveNetParams.DefaultGasCredit); !ok {
66 return errors.Wrap(ErrGasCalculate, "setGas calc free gas")
69 if g.GasLeft > consensus.ActiveNetParams.MaxGasAmount {
70 g.GasLeft = consensus.ActiveNetParams.MaxGasAmount
73 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.ActiveNetParams.StorageGasRate); !ok {
74 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
79 func (g *GasState) setGasValid() error {
81 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
82 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
85 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
86 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
93 func (g *GasState) updateUsage(gasLeft int64) error {
95 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
98 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
102 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
105 if !g.GasValid && (g.GasUsed > consensus.ActiveNetParams.DefaultGasCredit || g.StorageGas > g.GasLeft) {
106 return ErrOverGasCredit
111 // validationState contains the context that must propagate through
112 // the transaction graph when validating entries.
113 type validationState struct {
117 entryID bc.Hash // The ID of the nearest enclosing entry
118 sourcePos uint64 // The source position, for validate ValueSources
119 destPos uint64 // The destination position, for validate ValueDestinations
120 cache map[bc.Hash]error // Memoized per-entry validation results
123 func checkValid(vs *validationState, e bc.Entry) (err error) {
125 entryID := bc.EntryID(e)
126 if err, ok = vs.cache[entryID]; ok {
131 vs.cache[entryID] = err
134 switch e := e.(type) {
136 for i, resID := range e.ResultIds {
137 resultEntry := vs.tx.Entries[*resID]
140 if err = checkValid(&vs2, resultEntry); err != nil {
141 return errors.Wrapf(err, "checking result %d", i)
145 if e.Version == 1 && len(e.ResultIds) == 0 {
146 return ErrEmptyResults
150 parity := make(map[bc.AssetID]int64)
151 for i, src := range e.Sources {
152 if src.Value.Amount > math.MaxInt64 {
153 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
155 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
157 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])
159 parity[*src.Value.AssetId] = sum
162 for i, dest := range e.WitnessDestinations {
163 sum, ok := parity[*dest.Value.AssetId]
165 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
167 if dest.Value.Amount > math.MaxInt64 {
168 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
170 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
172 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)
174 parity[*dest.Value.AssetId] = diff
177 btmAmount := int64(0)
178 for assetID, amount := range parity {
179 if assetID == *consensus.BTMAssetID {
181 } else if amount != 0 {
182 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
186 if err = vs.gasStatus.setGas(btmAmount, int64(vs.tx.SerializedSize)); err != nil {
190 for _, BTMInputID := range vs.tx.GasInputIDs {
191 e, ok := vs.tx.Entries[BTMInputID]
193 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
197 vs2.entryID = BTMInputID
198 if err := checkValid(&vs2, e); err != nil {
199 return errors.Wrap(err, "checking gas input")
203 for i, dest := range e.WitnessDestinations {
205 vs2.destPos = uint64(i)
206 if err = checkValidDest(&vs2, dest); err != nil {
207 return errors.Wrapf(err, "checking mux destination %d", i)
211 if err := vs.gasStatus.setGasValid(); err != nil {
215 for i, src := range e.Sources {
217 vs2.sourcePos = uint64(i)
218 if err = checkValidSrc(&vs2, src); err != nil {
219 return errors.Wrapf(err, "checking mux source %d", i)
223 case *bc.IntraChainOutput:
226 if err = checkValidSrc(&vs2, e.Source); err != nil {
227 return errors.Wrap(err, "checking output source")
230 case *bc.CrossChainOutput:
233 if err = checkValidSrc(&vs2, e.Source); err != nil {
234 return errors.Wrap(err, "checking output source")
238 if len(e.Vote) != 64 {
244 if err = checkValidSrc(&vs2, e.Source); err != nil {
245 return errors.Wrap(err, "checking vote output source")
248 if e.Source.Value.Amount < consensus.ActiveNetParams.MinVoteOutputAmount {
249 return ErrVoteOutputAmount
252 if *e.Source.Value.AssetId != *consensus.BTMAssetID {
253 return ErrVoteOutputAseet
259 if err = checkValidSrc(&vs2, e.Source); err != nil {
260 return errors.Wrap(err, "checking retirement source")
263 case *bc.CrossChainInput:
264 if e.MainchainOutputId == nil {
265 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
268 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
270 return errors.Wrap(err, "getting mainchain output")
273 assetID := e.AssetDefinition.ComputeAssetID()
274 if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
275 return errors.New("incorrect asset_id while checking CrossChainInput")
278 prog := e.ControlProgram
280 if !common.IsOpenFederationIssueAsset(e.RawDefinitionByte) {
281 prog.Code = config.FederationWScript(config.CommonConfig)
284 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
285 return errors.Wrap(err, "checking cross-chain input control program")
288 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
294 return errors.WithDetailf(
296 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
297 mainchainOutput.Source.Value.Amount,
298 mainchainOutput.Source.Value.AssetId.Bytes(),
299 e.WitnessDestination.Value.Amount,
300 e.WitnessDestination.Value.AssetId.Bytes(),
306 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
307 return errors.Wrap(err, "checking cross-chain input destination")
309 vs.gasStatus.StorageGas = 0
312 if e.SpentOutputId == nil {
313 return errors.Wrap(ErrMissingField, "spend without spent output ID")
316 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
318 return errors.Wrap(err, "getting spend prevout")
321 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
323 return errors.Wrap(err, "checking control program")
325 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
329 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
334 return errors.WithDetailf(
336 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
337 spentOutput.Source.Value.Amount,
338 spentOutput.Source.Value.AssetId.Bytes(),
339 e.WitnessDestination.Value.Amount,
340 e.WitnessDestination.Value.AssetId.Bytes(),
345 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
346 return errors.Wrap(err, "checking spend destination")
350 if e.SpentOutputId == nil {
351 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
354 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
356 return errors.Wrap(err, "getting vetoInput prevout")
359 if len(voteOutput.Vote) != 64 {
363 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
365 return errors.Wrap(err, "checking control program")
367 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
371 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
376 return errors.WithDetailf(
378 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
379 voteOutput.Source.Value.Amount,
380 voteOutput.Source.Value.AssetId.Bytes(),
381 e.WitnessDestination.Value.Amount,
382 e.WitnessDestination.Value.AssetId.Bytes(),
387 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
388 return errors.Wrap(err, "checking vetoInput destination")
392 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
393 return ErrWrongCoinbaseTransaction
396 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
397 return ErrWrongCoinbaseAsset
400 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
401 return ErrCoinbaseArbitraryOversize
406 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
407 return errors.Wrap(err, "checking coinbase destination")
409 vs.gasStatus.StorageGas = 0
412 return fmt.Errorf("entry has unexpected type %T", e)
418 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
420 return errors.Wrap(ErrMissingField, "empty value source")
423 return errors.Wrap(ErrMissingField, "missing ref on value source")
425 if vs.Value == nil || vs.Value.AssetId == nil {
426 return errors.Wrap(ErrMissingField, "missing value on value source")
429 e, ok := vstate.tx.Entries[*vs.Ref]
431 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
435 vstate2.entryID = *vs.Ref
436 if err := checkValid(&vstate2, e); err != nil {
437 return errors.Wrap(err, "checking value source")
440 var dest *bc.ValueDestination
441 switch ref := e.(type) {
443 if vs.Position != 0 {
444 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
446 dest = ref.WitnessDestination
449 if vs.Position != 0 {
450 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
452 dest = ref.WitnessDestination
454 case *bc.CrossChainInput:
455 if vs.Position != 0 {
456 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
458 dest = ref.WitnessDestination
461 if vs.Position != 0 {
462 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
464 dest = ref.WitnessDestination
467 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
468 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
470 dest = ref.WitnessDestinations[vs.Position]
473 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
476 if dest.Ref == nil || *dest.Ref != vstate.entryID {
477 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
480 if dest.Position != vstate.sourcePos {
481 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
484 eq, err := dest.Value.Equal(vs.Value)
486 return errors.Sub(ErrMissingField, err)
489 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
495 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
497 return errors.Wrap(ErrMissingField, "empty value destination")
500 return errors.Wrap(ErrMissingField, "missing ref on value destination")
502 if vd.Value == nil || vd.Value.AssetId == nil {
503 return errors.Wrap(ErrMissingField, "missing value on value destination")
506 e, ok := vs.tx.Entries[*vd.Ref]
508 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
511 var src *bc.ValueSource
512 switch ref := e.(type) {
513 case *bc.IntraChainOutput:
514 if vd.Position != 0 {
515 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
519 case *bc.CrossChainOutput:
520 if vd.Position != 0 {
521 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
526 if vd.Position != 0 {
527 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
532 if vd.Position != 0 {
533 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
538 if vd.Position >= uint64(len(ref.Sources)) {
539 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
541 src = ref.Sources[vd.Position]
544 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
547 if src.Ref == nil || *src.Ref != vs.entryID {
548 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
551 if src.Position != vs.destPos {
552 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
555 eq, err := src.Value.Equal(vd.Value)
557 return errors.Sub(ErrMissingField, err)
560 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
566 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
567 for _, id := range tx.InputIDs {
569 return ErrEmptyInputIDs
575 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
576 if tx.TimeRange == 0 {
580 if tx.TimeRange < block.Height {
581 return ErrBadTimeRange
587 func applySoftFork001(vs *validationState, err error) {
588 if err == nil || vs.block.Height < consensus.ActiveNetParams.SoftForkPoint[consensus.SoftFork001] {
592 if rootErr := errors.Root(err); rootErr == ErrVotePubKey || rootErr == ErrVoteOutputAmount || rootErr == ErrVoteOutputAseet {
593 vs.gasStatus.GasValid = false
597 // ValidateTx validates a transaction.
598 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
599 gasStatus := &GasState{GasValid: false}
600 if block.Version == 1 && tx.Version != 1 {
601 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
603 if tx.SerializedSize == 0 {
604 return gasStatus, ErrWrongTransactionSize
606 if err := checkTimeRange(tx, block); err != nil {
607 return gasStatus, err
609 if err := checkInputID(tx, block.Height); err != nil {
610 return gasStatus, err
613 vs := &validationState{
617 gasStatus: gasStatus,
618 cache: make(map[bc.Hash]error),
621 err := checkValid(vs, tx.TxHeader)
622 applySoftFork001(vs, err)
623 return vs.gasStatus, err
626 type validateTxWork struct {
632 // ValidateTxResult is the result of async tx validate
633 type ValidateTxResult struct {
639 // GetGasState return the gasStatus
640 func (r *ValidateTxResult) GetGasState() *GasState {
644 // GetError return the err
645 func (r *ValidateTxResult) GetError() error {
649 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
652 case work := <-workCh:
653 gasStatus, err := ValidateTx(work.tx, work.block)
654 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
662 // ValidateTxs validates txs in async mode
663 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
665 validateWorkerNum := runtime.NumCPU()
666 //init the goroutine validate worker
667 var wg sync.WaitGroup
668 workCh := make(chan *validateTxWork, txSize)
669 resultCh := make(chan *ValidateTxResult, txSize)
670 closeCh := make(chan struct{})
671 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
673 go validateTxWorker(workCh, resultCh, closeCh, &wg)
677 for i, tx := range txs {
678 workCh <- &validateTxWork{i: i, tx: tx, block: block}
681 //collect validate results
682 results := make([]*ValidateTxResult, txSize)
683 for i := 0; i < txSize; i++ {
685 results[result.i] = result