8 "github.com/bytom/vapor/config"
9 "github.com/bytom/vapor/consensus"
10 "github.com/bytom/vapor/errors"
11 "github.com/bytom/vapor/math/checked"
12 "github.com/bytom/vapor/protocol/bc"
13 "github.com/bytom/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")
44 ErrVoteOutputAseet = errors.New("incorrect asset_id while checking vote asset")
47 // GasState record the gas usage status
48 type GasState struct {
56 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
58 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
61 g.BTMValue = uint64(BTMValue)
63 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.ActiveNetParams.VMGasRate); !ok {
64 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
67 if g.GasLeft, ok = checked.AddInt64(g.GasLeft, consensus.ActiveNetParams.DefaultGasCredit); !ok {
68 return errors.Wrap(ErrGasCalculate, "setGas calc free gas")
71 if g.GasLeft > consensus.ActiveNetParams.MaxGasAmount {
72 g.GasLeft = consensus.ActiveNetParams.MaxGasAmount
75 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.ActiveNetParams.StorageGasRate); !ok {
76 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
81 func (g *GasState) setGasValid() error {
83 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
84 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
87 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
88 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
95 func (g *GasState) updateUsage(gasLeft int64) error {
97 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
100 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
104 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
107 if !g.GasValid && (g.GasUsed > consensus.ActiveNetParams.DefaultGasCredit || g.StorageGas > g.GasLeft) {
108 return ErrOverGasCredit
113 // validationState contains the context that must propagate through
114 // the transaction graph when validating entries.
115 type validationState struct {
119 entryID bc.Hash // The ID of the nearest enclosing entry
120 sourcePos uint64 // The source position, for validate ValueSources
121 destPos uint64 // The destination position, for validate ValueDestinations
122 cache map[bc.Hash]error // Memoized per-entry validation results
125 func checkValid(vs *validationState, e bc.Entry) (err error) {
127 entryID := bc.EntryID(e)
128 if err, ok = vs.cache[entryID]; ok {
133 vs.cache[entryID] = err
136 switch e := e.(type) {
138 for i, resID := range e.ResultIds {
139 resultEntry := vs.tx.Entries[*resID]
142 if err = checkValid(&vs2, resultEntry); err != nil {
143 return errors.Wrapf(err, "checking result %d", i)
147 if e.Version == 1 && len(e.ResultIds) == 0 {
148 return ErrEmptyResults
152 parity := make(map[bc.AssetID]int64)
153 for i, src := range e.Sources {
154 if src.Value.Amount > math.MaxInt64 {
155 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
157 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
159 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])
161 parity[*src.Value.AssetId] = sum
164 for i, dest := range e.WitnessDestinations {
165 sum, ok := parity[*dest.Value.AssetId]
167 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
169 if dest.Value.Amount > math.MaxInt64 {
170 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
172 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
174 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)
176 parity[*dest.Value.AssetId] = diff
179 btmAmount := int64(0)
180 for assetID, amount := range parity {
181 if assetID == *consensus.BTMAssetID {
183 } else if amount != 0 {
184 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
188 if err = vs.gasStatus.setGas(btmAmount, int64(vs.tx.SerializedSize)); err != nil {
192 for _, BTMInputID := range vs.tx.GasInputIDs {
193 e, ok := vs.tx.Entries[BTMInputID]
195 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
199 vs2.entryID = BTMInputID
200 if err := checkValid(&vs2, e); err != nil {
201 return errors.Wrap(err, "checking gas input")
205 for i, dest := range e.WitnessDestinations {
207 vs2.destPos = uint64(i)
208 if err = checkValidDest(&vs2, dest); err != nil {
209 return errors.Wrapf(err, "checking mux destination %d", i)
213 if err := vs.gasStatus.setGasValid(); err != nil {
217 for i, src := range e.Sources {
219 vs2.sourcePos = uint64(i)
220 if err = checkValidSrc(&vs2, src); err != nil {
221 return errors.Wrapf(err, "checking mux source %d", i)
225 case *bc.IntraChainOutput:
228 if err = checkValidSrc(&vs2, e.Source); err != nil {
229 return errors.Wrap(err, "checking output source")
232 case *bc.CrossChainOutput:
235 if err = checkValidSrc(&vs2, e.Source); err != nil {
236 return errors.Wrap(err, "checking output source")
240 if len(e.Vote) != 64 {
246 if err = checkValidSrc(&vs2, e.Source); err != nil {
247 return errors.Wrap(err, "checking vote output source")
250 if e.Source.Value.Amount < consensus.ActiveNetParams.MinVoteOutputAmount {
251 return ErrVoteOutputAmount
254 if *e.Source.Value.AssetId != *consensus.BTMAssetID {
255 return ErrVoteOutputAseet
261 if err = checkValidSrc(&vs2, e.Source); err != nil {
262 return errors.Wrap(err, "checking retirement source")
265 case *bc.CrossChainInput:
266 if e.MainchainOutputId == nil {
267 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
270 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
272 return errors.Wrap(err, "getting mainchain output")
275 assetID := e.AssetDefinition.ComputeAssetID()
276 if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
277 return errors.New("incorrect asset_id while checking CrossChainInput")
281 VmVersion: e.ControlProgram.VmVersion,
282 Code: config.FederationWScript(config.CommonConfig),
285 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
286 return errors.Wrap(err, "checking cross-chain input control program")
289 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
295 return errors.WithDetailf(
297 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
298 mainchainOutput.Source.Value.Amount,
299 mainchainOutput.Source.Value.AssetId.Bytes(),
300 e.WitnessDestination.Value.Amount,
301 e.WitnessDestination.Value.AssetId.Bytes(),
307 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
308 return errors.Wrap(err, "checking cross-chain input destination")
310 vs.gasStatus.StorageGas = 0
313 if e.SpentOutputId == nil {
314 return errors.Wrap(ErrMissingField, "spend without spent output ID")
317 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
319 return errors.Wrap(err, "getting spend prevout")
322 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
324 return errors.Wrap(err, "checking control program")
326 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
330 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
335 return errors.WithDetailf(
337 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
338 spentOutput.Source.Value.Amount,
339 spentOutput.Source.Value.AssetId.Bytes(),
340 e.WitnessDestination.Value.Amount,
341 e.WitnessDestination.Value.AssetId.Bytes(),
346 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
347 return errors.Wrap(err, "checking spend destination")
351 if e.SpentOutputId == nil {
352 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
355 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
357 return errors.Wrap(err, "getting vetoInput prevout")
360 if len(voteOutput.Vote) != 64 {
364 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
366 return errors.Wrap(err, "checking control program")
368 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
372 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
377 return errors.WithDetailf(
379 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
380 voteOutput.Source.Value.Amount,
381 voteOutput.Source.Value.AssetId.Bytes(),
382 e.WitnessDestination.Value.Amount,
383 e.WitnessDestination.Value.AssetId.Bytes(),
388 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
389 return errors.Wrap(err, "checking vetoInput destination")
393 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
394 return ErrWrongCoinbaseTransaction
397 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
398 return ErrWrongCoinbaseAsset
401 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
402 return ErrCoinbaseArbitraryOversize
407 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
408 return errors.Wrap(err, "checking coinbase destination")
410 vs.gasStatus.StorageGas = 0
413 return fmt.Errorf("entry has unexpected type %T", e)
419 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
421 return errors.Wrap(ErrMissingField, "empty value source")
424 return errors.Wrap(ErrMissingField, "missing ref on value source")
426 if vs.Value == nil || vs.Value.AssetId == nil {
427 return errors.Wrap(ErrMissingField, "missing value on value source")
430 e, ok := vstate.tx.Entries[*vs.Ref]
432 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
436 vstate2.entryID = *vs.Ref
437 if err := checkValid(&vstate2, e); err != nil {
438 return errors.Wrap(err, "checking value source")
441 var dest *bc.ValueDestination
442 switch ref := e.(type) {
444 if vs.Position != 0 {
445 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
447 dest = ref.WitnessDestination
450 if vs.Position != 0 {
451 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
453 dest = ref.WitnessDestination
455 case *bc.CrossChainInput:
456 if vs.Position != 0 {
457 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
459 dest = ref.WitnessDestination
462 if vs.Position != 0 {
463 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
465 dest = ref.WitnessDestination
468 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
469 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
471 dest = ref.WitnessDestinations[vs.Position]
474 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
477 if dest.Ref == nil || *dest.Ref != vstate.entryID {
478 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
481 if dest.Position != vstate.sourcePos {
482 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
485 eq, err := dest.Value.Equal(vs.Value)
487 return errors.Sub(ErrMissingField, err)
490 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
496 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
498 return errors.Wrap(ErrMissingField, "empty value destination")
501 return errors.Wrap(ErrMissingField, "missing ref on value destination")
503 if vd.Value == nil || vd.Value.AssetId == nil {
504 return errors.Wrap(ErrMissingField, "missing value on value destination")
507 e, ok := vs.tx.Entries[*vd.Ref]
509 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
512 var src *bc.ValueSource
513 switch ref := e.(type) {
514 case *bc.IntraChainOutput:
515 if vd.Position != 0 {
516 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
520 case *bc.CrossChainOutput:
521 if vd.Position != 0 {
522 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
527 if vd.Position != 0 {
528 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
533 if vd.Position != 0 {
534 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
539 if vd.Position >= uint64(len(ref.Sources)) {
540 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
542 src = ref.Sources[vd.Position]
545 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
548 if src.Ref == nil || *src.Ref != vs.entryID {
549 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
552 if src.Position != vs.destPos {
553 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
556 eq, err := src.Value.Equal(vd.Value)
558 return errors.Sub(ErrMissingField, err)
561 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
567 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
568 for _, id := range tx.InputIDs {
570 return ErrEmptyInputIDs
576 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
577 if tx.TimeRange == 0 {
581 if tx.TimeRange < block.Height {
582 return ErrBadTimeRange
588 func applySoftFork001(vs *validationState, err error) {
589 if err == nil || vs.block.Height < consensus.ActiveNetParams.SoftForkPoint[consensus.SoftFork001] {
593 if rootErr := errors.Root(err); rootErr == ErrVotePubKey || rootErr == ErrVoteOutputAmount || rootErr == ErrVoteOutputAseet {
594 vs.gasStatus.GasValid = false
598 // ValidateTx validates a transaction.
599 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
600 gasStatus := &GasState{GasValid: false}
601 if block.Version == 1 && tx.Version != 1 {
602 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
604 if tx.SerializedSize == 0 {
605 return gasStatus, ErrWrongTransactionSize
607 if err := checkTimeRange(tx, block); err != nil {
608 return gasStatus, err
610 if err := checkInputID(tx, block.Height); err != nil {
611 return gasStatus, err
614 vs := &validationState{
618 gasStatus: gasStatus,
619 cache: make(map[bc.Hash]error),
622 err := checkValid(vs, tx.TxHeader)
623 applySoftFork001(vs, err)
624 return vs.gasStatus, err
627 type validateTxWork struct {
633 // ValidateTxResult is the result of async tx validate
634 type ValidateTxResult struct {
640 // GetGasState return the gasStatus
641 func (r *ValidateTxResult) GetGasState() *GasState {
645 // GetError return the err
646 func (r *ValidateTxResult) GetError() error {
650 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
653 case work := <-workCh:
654 gasStatus, err := ValidateTx(work.tx, work.block)
655 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
663 // ValidateTxs validates txs in async mode
664 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
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