9 "github.com/bytom/vapor/common"
10 "github.com/bytom/vapor/config"
11 "github.com/bytom/vapor/consensus"
12 "github.com/bytom/vapor/errors"
13 "github.com/bytom/vapor/math/checked"
14 "github.com/bytom/vapor/protocol/bc"
15 "github.com/bytom/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")
279 VmVersion: e.AssetDefinition.IssuanceProgram.VmVersion,
280 Code: e.AssetDefinition.IssuanceProgram.Code,
283 if !common.IsOpenFederationIssueAsset(e.RawDefinitionByte) {
284 prog.Code = config.FederationWScript(config.CommonConfig)
287 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
288 return errors.Wrap(err, "checking cross-chain input control program")
291 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
297 return errors.WithDetailf(
299 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
300 mainchainOutput.Source.Value.Amount,
301 mainchainOutput.Source.Value.AssetId.Bytes(),
302 e.WitnessDestination.Value.Amount,
303 e.WitnessDestination.Value.AssetId.Bytes(),
309 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
310 return errors.Wrap(err, "checking cross-chain input destination")
312 vs.gasStatus.StorageGas = 0
315 if e.SpentOutputId == nil {
316 return errors.Wrap(ErrMissingField, "spend without spent output ID")
319 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
321 return errors.Wrap(err, "getting spend prevout")
324 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
326 return errors.Wrap(err, "checking control program")
328 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
332 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
337 return errors.WithDetailf(
339 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
340 spentOutput.Source.Value.Amount,
341 spentOutput.Source.Value.AssetId.Bytes(),
342 e.WitnessDestination.Value.Amount,
343 e.WitnessDestination.Value.AssetId.Bytes(),
348 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
349 return errors.Wrap(err, "checking spend destination")
353 if e.SpentOutputId == nil {
354 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
357 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
359 return errors.Wrap(err, "getting vetoInput prevout")
362 if len(voteOutput.Vote) != 64 {
366 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
368 return errors.Wrap(err, "checking control program")
370 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
374 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
379 return errors.WithDetailf(
381 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
382 voteOutput.Source.Value.Amount,
383 voteOutput.Source.Value.AssetId.Bytes(),
384 e.WitnessDestination.Value.Amount,
385 e.WitnessDestination.Value.AssetId.Bytes(),
390 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
391 return errors.Wrap(err, "checking vetoInput destination")
395 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
396 return ErrWrongCoinbaseTransaction
399 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
400 return ErrWrongCoinbaseAsset
403 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
404 return ErrCoinbaseArbitraryOversize
409 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
410 return errors.Wrap(err, "checking coinbase destination")
412 vs.gasStatus.StorageGas = 0
415 return fmt.Errorf("entry has unexpected type %T", e)
421 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
423 return errors.Wrap(ErrMissingField, "empty value source")
426 return errors.Wrap(ErrMissingField, "missing ref on value source")
428 if vs.Value == nil || vs.Value.AssetId == nil {
429 return errors.Wrap(ErrMissingField, "missing value on value source")
432 e, ok := vstate.tx.Entries[*vs.Ref]
434 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
438 vstate2.entryID = *vs.Ref
439 if err := checkValid(&vstate2, e); err != nil {
440 return errors.Wrap(err, "checking value source")
443 var dest *bc.ValueDestination
444 switch ref := e.(type) {
446 if vs.Position != 0 {
447 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
449 dest = ref.WitnessDestination
452 if vs.Position != 0 {
453 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
455 dest = ref.WitnessDestination
457 case *bc.CrossChainInput:
458 if vs.Position != 0 {
459 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
461 dest = ref.WitnessDestination
464 if vs.Position != 0 {
465 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
467 dest = ref.WitnessDestination
470 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
471 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
473 dest = ref.WitnessDestinations[vs.Position]
476 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
479 if dest.Ref == nil || *dest.Ref != vstate.entryID {
480 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
483 if dest.Position != vstate.sourcePos {
484 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
487 eq, err := dest.Value.Equal(vs.Value)
489 return errors.Sub(ErrMissingField, err)
492 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
498 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
500 return errors.Wrap(ErrMissingField, "empty value destination")
503 return errors.Wrap(ErrMissingField, "missing ref on value destination")
505 if vd.Value == nil || vd.Value.AssetId == nil {
506 return errors.Wrap(ErrMissingField, "missing value on value destination")
509 e, ok := vs.tx.Entries[*vd.Ref]
511 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
514 var src *bc.ValueSource
515 switch ref := e.(type) {
516 case *bc.IntraChainOutput:
517 if vd.Position != 0 {
518 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
522 case *bc.CrossChainOutput:
523 if vd.Position != 0 {
524 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
529 if vd.Position != 0 {
530 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
535 if vd.Position != 0 {
536 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
541 if vd.Position >= uint64(len(ref.Sources)) {
542 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
544 src = ref.Sources[vd.Position]
547 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
550 if src.Ref == nil || *src.Ref != vs.entryID {
551 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
554 if src.Position != vs.destPos {
555 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
558 eq, err := src.Value.Equal(vd.Value)
560 return errors.Sub(ErrMissingField, err)
563 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
569 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
570 for _, id := range tx.InputIDs {
572 return ErrEmptyInputIDs
578 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
579 if tx.TimeRange == 0 {
583 if tx.TimeRange < block.Height {
584 return ErrBadTimeRange
590 func applySoftFork001(vs *validationState, err error) {
591 if err == nil || vs.block.Height < consensus.ActiveNetParams.SoftForkPoint[consensus.SoftFork001] {
595 if rootErr := errors.Root(err); rootErr == ErrVotePubKey || rootErr == ErrVoteOutputAmount || rootErr == ErrVoteOutputAseet {
596 vs.gasStatus.GasValid = false
600 // ValidateTx validates a transaction.
601 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
602 gasStatus := &GasState{GasValid: false}
603 if block.Version == 1 && tx.Version != 1 {
604 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
606 if tx.SerializedSize == 0 {
607 return gasStatus, ErrWrongTransactionSize
609 if err := checkTimeRange(tx, block); err != nil {
610 return gasStatus, err
612 if err := checkInputID(tx, block.Height); err != nil {
613 return gasStatus, err
616 vs := &validationState{
620 gasStatus: gasStatus,
621 cache: make(map[bc.Hash]error),
624 err := checkValid(vs, tx.TxHeader)
625 applySoftFork001(vs, err)
626 return vs.gasStatus, err
629 type validateTxWork struct {
635 // ValidateTxResult is the result of async tx validate
636 type ValidateTxResult struct {
642 // GetGasState return the gasStatus
643 func (r *ValidateTxResult) GetGasState() *GasState {
647 // GetError return the err
648 func (r *ValidateTxResult) GetError() error {
652 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
655 case work := <-workCh:
656 gasStatus, err := ValidateTx(work.tx, work.block)
657 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
665 // ValidateTxs validates txs in async mode
666 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
668 validateWorkerNum := runtime.NumCPU()
669 //init the goroutine validate worker
670 var wg sync.WaitGroup
671 workCh := make(chan *validateTxWork, txSize)
672 resultCh := make(chan *ValidateTxResult, txSize)
673 closeCh := make(chan struct{})
674 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
676 go validateTxWorker(workCh, resultCh, closeCh, &wg)
680 for i, tx := range txs {
681 workCh <- &validateTxWork{i: i, tx: tx, block: block}
684 //collect validate results
685 results := make([]*ValidateTxResult, txSize)
686 for i := 0; i < txSize; i++ {
688 results[result.i] = result