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"
17 validateWorkerNum = 32
20 // validate transaction error
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")
46 // GasState record the gas usage status
47 type GasState struct {
55 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
57 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
60 g.BTMValue = uint64(BTMValue)
63 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
64 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
67 if g.GasLeft > consensus.MaxGasAmount {
68 g.GasLeft = consensus.MaxGasAmount
71 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
72 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
77 func (g *GasState) setGasValid() error {
79 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
80 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
83 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
84 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
91 func (g *GasState) updateUsage(gasLeft int64) error {
93 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
96 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
100 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
103 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
104 return ErrOverGasCredit
109 // validationState contains the context that must propagate through
110 // the transaction graph when validating entries.
111 type validationState struct {
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
121 func checkValid(vs *validationState, e bc.Entry) (err error) {
123 entryID := bc.EntryID(e)
124 if err, ok = vs.cache[entryID]; ok {
129 vs.cache[entryID] = err
132 switch e := e.(type) {
134 for i, resID := range e.ResultIds {
135 resultEntry := vs.tx.Entries[*resID]
138 if err = checkValid(&vs2, resultEntry); err != nil {
139 return errors.Wrapf(err, "checking result %d", i)
143 if e.Version == 1 && len(e.ResultIds) == 0 {
144 return ErrEmptyResults
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)
153 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
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])
157 parity[*src.Value.AssetId] = sum
160 for i, dest := range e.WitnessDestinations {
161 sum, ok := parity[*dest.Value.AssetId]
163 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
165 if dest.Value.Amount > math.MaxInt64 {
166 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
168 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
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)
172 parity[*dest.Value.AssetId] = diff
175 for assetID, amount := range parity {
176 if assetID == *consensus.BTMAssetID {
177 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
180 } else if amount != 0 {
181 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
185 for _, BTMInputID := range vs.tx.GasInputIDs {
186 e, ok := vs.tx.Entries[BTMInputID]
188 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
192 vs2.entryID = BTMInputID
193 if err := checkValid(&vs2, e); err != nil {
194 return errors.Wrap(err, "checking gas input")
198 for i, dest := range e.WitnessDestinations {
200 vs2.destPos = uint64(i)
201 if err = checkValidDest(&vs2, dest); err != nil {
202 return errors.Wrapf(err, "checking mux destination %d", i)
206 if err := vs.gasStatus.setGasValid(); err != nil {
210 for i, src := range e.Sources {
212 vs2.sourcePos = uint64(i)
213 if err = checkValidSrc(&vs2, src); err != nil {
214 return errors.Wrapf(err, "checking mux source %d", i)
218 case *bc.IntraChainOutput:
221 if err = checkValidSrc(&vs2, e.Source); err != nil {
222 return errors.Wrap(err, "checking output source")
225 case *bc.CrossChainOutput:
228 if err = checkValidSrc(&vs2, e.Source); err != nil {
229 return errors.Wrap(err, "checking output source")
233 if len(e.Vote) != 64 {
238 if err = checkValidSrc(&vs2, e.Source); err != nil {
239 return errors.Wrap(err, "checking vote output source")
241 if e.Source.Value.Amount < consensus.MinVoteOutputAmount {
242 return ErrVoteOutputAmount
248 if err = checkValidSrc(&vs2, e.Source); err != nil {
249 return errors.Wrap(err, "checking retirement source")
252 case *bc.CrossChainInput:
253 if e.MainchainOutputId == nil {
254 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
257 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
259 return errors.Wrap(err, "getting mainchain output")
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")
268 VmVersion: e.ControlProgram.VmVersion,
269 Code: config.FederationWScript(config.CommonConfig),
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")
276 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
282 return errors.WithDetailf(
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(),
294 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
295 return errors.Wrap(err, "checking cross-chain input destination")
297 vs.gasStatus.StorageGas = 0
300 if e.SpentOutputId == nil {
301 return errors.Wrap(ErrMissingField, "spend without spent output ID")
304 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
306 return errors.Wrap(err, "getting spend prevout")
309 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
311 return errors.Wrap(err, "checking control program")
313 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
317 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
322 return errors.WithDetailf(
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(),
333 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
334 return errors.Wrap(err, "checking spend destination")
338 if e.SpentOutputId == nil {
339 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
342 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
344 return errors.Wrap(err, "getting vetoInput prevout")
347 if len(voteOutput.Vote) != 64 {
351 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
353 return errors.Wrap(err, "checking control program")
355 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
359 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
364 return errors.WithDetailf(
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(),
375 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
376 return errors.Wrap(err, "checking vetoInput destination")
380 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
381 return ErrWrongCoinbaseTransaction
384 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
385 return ErrWrongCoinbaseAsset
388 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
389 return ErrCoinbaseArbitraryOversize
394 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
395 return errors.Wrap(err, "checking coinbase destination")
397 vs.gasStatus.StorageGas = 0
400 return fmt.Errorf("entry has unexpected type %T", e)
406 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
408 return errors.Wrap(ErrMissingField, "empty value source")
411 return errors.Wrap(ErrMissingField, "missing ref on value source")
413 if vs.Value == nil || vs.Value.AssetId == nil {
414 return errors.Wrap(ErrMissingField, "missing value on value source")
417 e, ok := vstate.tx.Entries[*vs.Ref]
419 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
423 vstate2.entryID = *vs.Ref
424 if err := checkValid(&vstate2, e); err != nil {
425 return errors.Wrap(err, "checking value source")
428 var dest *bc.ValueDestination
429 switch ref := e.(type) {
431 if vs.Position != 0 {
432 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
434 dest = ref.WitnessDestination
437 if vs.Position != 0 {
438 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
440 dest = ref.WitnessDestination
442 case *bc.CrossChainInput:
443 if vs.Position != 0 {
444 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
446 dest = ref.WitnessDestination
449 if vs.Position != 0 {
450 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
452 dest = ref.WitnessDestination
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))
458 dest = ref.WitnessDestinations[vs.Position]
461 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
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())
468 if dest.Position != vstate.sourcePos {
469 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
472 eq, err := dest.Value.Equal(vs.Value)
474 return errors.Sub(ErrMissingField, err)
477 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
483 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
485 return errors.Wrap(ErrMissingField, "empty value destination")
488 return errors.Wrap(ErrMissingField, "missing ref on value destination")
490 if vd.Value == nil || vd.Value.AssetId == nil {
491 return errors.Wrap(ErrMissingField, "missing value on value destination")
494 e, ok := vs.tx.Entries[*vd.Ref]
496 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
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)
507 case *bc.CrossChainOutput:
508 if vd.Position != 0 {
509 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
514 if vd.Position != 0 {
515 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
520 if vd.Position != 0 {
521 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
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))
529 src = ref.Sources[vd.Position]
532 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
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())
539 if src.Position != vs.destPos {
540 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
543 eq, err := src.Value.Equal(vd.Value)
545 return errors.Sub(ErrMissingField, err)
548 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
554 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
555 for _, id := range tx.InputIDs {
557 return ErrEmptyInputIDs
563 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
564 if tx.TimeRange == 0 {
568 if tx.TimeRange < block.Height {
569 return ErrBadTimeRange
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)
581 if tx.SerializedSize == 0 {
582 return gasStatus, ErrWrongTransactionSize
584 if err := checkTimeRange(tx, block); err != nil {
585 return gasStatus, err
587 if err := checkInputID(tx, block.Height); err != nil {
588 return gasStatus, err
591 vs := &validationState{
595 gasStatus: gasStatus,
596 cache: make(map[bc.Hash]error),
598 return vs.gasStatus, checkValid(vs, tx.TxHeader)
601 type validateTxWork struct {
607 // ValidateTxResult is the result of async tx validate
608 type ValidateTxResult struct {
614 // GetGasState return the gasStatus
615 func (r *ValidateTxResult) GetGasState() *GasState {
619 // GetError return the err
620 func (r *ValidateTxResult) GetError() error {
624 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
627 case work := <-workCh:
628 gasStatus, err := ValidateTx(work.tx, work.block)
629 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
637 // ValidateTxs validates txs in async mode
638 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
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++ {
647 go validateTxWorker(workCh, resultCh, closeCh, &wg)
651 for i, tx := range txs {
652 workCh <- &validateTxWork{i: i, tx: tx, block: block}
655 //collect validate results
656 results := make([]*ValidateTxResult, txSize)
657 for i := 0; i < txSize; i++ {
659 results[result.i] = result