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)
62 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.ActiveNetParams.VMGasRate); !ok {
63 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
66 if g.GasLeft, ok = checked.AddInt64(g.GasLeft, consensus.ActiveNetParams.DefaultGasCredit); !ok {
67 return errors.Wrap(ErrGasCalculate, "setGas calc free gas")
70 if g.GasLeft > consensus.ActiveNetParams.MaxGasAmount {
71 g.GasLeft = consensus.ActiveNetParams.MaxGasAmount
74 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.ActiveNetParams.StorageGasRate); !ok {
75 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
80 func (g *GasState) setGasValid() error {
82 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
83 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
86 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
87 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
94 func (g *GasState) updateUsage(gasLeft int64) error {
96 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
99 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
103 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
106 if !g.GasValid && (g.GasUsed > consensus.ActiveNetParams.DefaultGasCredit || g.StorageGas > g.GasLeft) {
107 return ErrOverGasCredit
112 // validationState contains the context that must propagate through
113 // the transaction graph when validating entries.
114 type validationState struct {
118 entryID bc.Hash // The ID of the nearest enclosing entry
119 sourcePos uint64 // The source position, for validate ValueSources
120 destPos uint64 // The destination position, for validate ValueDestinations
121 cache map[bc.Hash]error // Memoized per-entry validation results
124 func checkValid(vs *validationState, e bc.Entry) (err error) {
126 entryID := bc.EntryID(e)
127 if err, ok = vs.cache[entryID]; ok {
132 vs.cache[entryID] = err
135 switch e := e.(type) {
137 for i, resID := range e.ResultIds {
138 resultEntry := vs.tx.Entries[*resID]
141 if err = checkValid(&vs2, resultEntry); err != nil {
142 return errors.Wrapf(err, "checking result %d", i)
146 if e.Version == 1 && len(e.ResultIds) == 0 {
147 return ErrEmptyResults
151 parity := make(map[bc.AssetID]int64)
152 for i, src := range e.Sources {
153 if src.Value.Amount > math.MaxInt64 {
154 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
156 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
158 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])
160 parity[*src.Value.AssetId] = sum
163 for i, dest := range e.WitnessDestinations {
164 sum, ok := parity[*dest.Value.AssetId]
166 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
168 if dest.Value.Amount > math.MaxInt64 {
169 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
171 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
173 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)
175 parity[*dest.Value.AssetId] = diff
178 btmAmount := int64(0)
179 for assetID, amount := range parity {
180 if assetID == *consensus.BTMAssetID {
182 } else if amount != 0 {
183 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
187 if err = vs.gasStatus.setGas(btmAmount, int64(vs.tx.SerializedSize)); err != nil {
191 for _, BTMInputID := range vs.tx.GasInputIDs {
192 e, ok := vs.tx.Entries[BTMInputID]
194 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
198 vs2.entryID = BTMInputID
199 if err := checkValid(&vs2, e); err != nil {
200 return errors.Wrap(err, "checking gas input")
204 for i, dest := range e.WitnessDestinations {
206 vs2.destPos = uint64(i)
207 if err = checkValidDest(&vs2, dest); err != nil {
208 return errors.Wrapf(err, "checking mux destination %d", i)
212 if err := vs.gasStatus.setGasValid(); err != nil {
216 for i, src := range e.Sources {
218 vs2.sourcePos = uint64(i)
219 if err = checkValidSrc(&vs2, src); err != nil {
220 return errors.Wrapf(err, "checking mux source %d", i)
224 case *bc.IntraChainOutput:
227 if err = checkValidSrc(&vs2, e.Source); err != nil {
228 return errors.Wrap(err, "checking output source")
231 case *bc.CrossChainOutput:
234 if err = checkValidSrc(&vs2, e.Source); err != nil {
235 return errors.Wrap(err, "checking output source")
239 if len(e.Vote) != 64 {
244 if err = checkValidSrc(&vs2, e.Source); err != nil {
245 return errors.Wrap(err, "checking vote output source")
251 if err = checkValidSrc(&vs2, e.Source); err != nil {
252 return errors.Wrap(err, "checking retirement source")
255 case *bc.CrossChainInput:
256 if e.MainchainOutputId == nil {
257 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
260 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
262 return errors.Wrap(err, "getting mainchain output")
265 assetID := e.AssetDefinition.ComputeAssetID()
266 if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
267 return errors.New("incorrect asset_id while checking CrossChainInput")
271 VmVersion: e.ControlProgram.VmVersion,
272 Code: config.FederationWScript(config.CommonConfig),
275 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
276 return errors.Wrap(err, "checking cross-chain input control program")
279 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
285 return errors.WithDetailf(
287 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
288 mainchainOutput.Source.Value.Amount,
289 mainchainOutput.Source.Value.AssetId.Bytes(),
290 e.WitnessDestination.Value.Amount,
291 e.WitnessDestination.Value.AssetId.Bytes(),
297 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
298 return errors.Wrap(err, "checking cross-chain input destination")
300 vs.gasStatus.StorageGas = 0
303 if e.SpentOutputId == nil {
304 return errors.Wrap(ErrMissingField, "spend without spent output ID")
307 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
309 return errors.Wrap(err, "getting spend prevout")
312 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
314 return errors.Wrap(err, "checking control program")
316 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
320 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
325 return errors.WithDetailf(
327 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
328 spentOutput.Source.Value.Amount,
329 spentOutput.Source.Value.AssetId.Bytes(),
330 e.WitnessDestination.Value.Amount,
331 e.WitnessDestination.Value.AssetId.Bytes(),
336 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
337 return errors.Wrap(err, "checking spend destination")
341 if e.SpentOutputId == nil {
342 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
345 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
347 return errors.Wrap(err, "getting vetoInput prevout")
350 if len(voteOutput.Vote) != 64 {
354 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
356 return errors.Wrap(err, "checking control program")
358 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
362 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
367 return errors.WithDetailf(
369 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
370 voteOutput.Source.Value.Amount,
371 voteOutput.Source.Value.AssetId.Bytes(),
372 e.WitnessDestination.Value.Amount,
373 e.WitnessDestination.Value.AssetId.Bytes(),
378 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
379 return errors.Wrap(err, "checking vetoInput destination")
383 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
384 return ErrWrongCoinbaseTransaction
387 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
388 return ErrWrongCoinbaseAsset
391 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
392 return ErrCoinbaseArbitraryOversize
397 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
398 return errors.Wrap(err, "checking coinbase destination")
400 vs.gasStatus.StorageGas = 0
403 return fmt.Errorf("entry has unexpected type %T", e)
409 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
411 return errors.Wrap(ErrMissingField, "empty value source")
414 return errors.Wrap(ErrMissingField, "missing ref on value source")
416 if vs.Value == nil || vs.Value.AssetId == nil {
417 return errors.Wrap(ErrMissingField, "missing value on value source")
420 e, ok := vstate.tx.Entries[*vs.Ref]
422 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
426 vstate2.entryID = *vs.Ref
427 if err := checkValid(&vstate2, e); err != nil {
428 return errors.Wrap(err, "checking value source")
431 var dest *bc.ValueDestination
432 switch ref := e.(type) {
434 if vs.Position != 0 {
435 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
437 dest = ref.WitnessDestination
440 if vs.Position != 0 {
441 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
443 dest = ref.WitnessDestination
445 case *bc.CrossChainInput:
446 if vs.Position != 0 {
447 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
449 dest = ref.WitnessDestination
452 if vs.Position != 0 {
453 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
455 dest = ref.WitnessDestination
458 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
459 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
461 dest = ref.WitnessDestinations[vs.Position]
464 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
467 if dest.Ref == nil || *dest.Ref != vstate.entryID {
468 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
471 if dest.Position != vstate.sourcePos {
472 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
475 eq, err := dest.Value.Equal(vs.Value)
477 return errors.Sub(ErrMissingField, err)
480 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
486 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
488 return errors.Wrap(ErrMissingField, "empty value destination")
491 return errors.Wrap(ErrMissingField, "missing ref on value destination")
493 if vd.Value == nil || vd.Value.AssetId == nil {
494 return errors.Wrap(ErrMissingField, "missing value on value destination")
497 e, ok := vs.tx.Entries[*vd.Ref]
499 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
502 var src *bc.ValueSource
503 switch ref := e.(type) {
504 case *bc.IntraChainOutput:
505 if vd.Position != 0 {
506 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
510 case *bc.CrossChainOutput:
511 if vd.Position != 0 {
512 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
517 if vd.Position != 0 {
518 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
523 if vd.Position != 0 {
524 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
529 if vd.Position >= uint64(len(ref.Sources)) {
530 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
532 src = ref.Sources[vd.Position]
535 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
538 if src.Ref == nil || *src.Ref != vs.entryID {
539 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
542 if src.Position != vs.destPos {
543 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
546 eq, err := src.Value.Equal(vd.Value)
548 return errors.Sub(ErrMissingField, err)
551 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
557 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
558 for _, id := range tx.InputIDs {
560 return ErrEmptyInputIDs
566 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
567 if tx.TimeRange == 0 {
571 if tx.TimeRange < block.Height {
572 return ErrBadTimeRange
578 // ValidateTx validates a transaction.
579 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
580 gasStatus := &GasState{GasValid: false}
581 if block.Version == 1 && tx.Version != 1 {
582 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
584 if tx.SerializedSize == 0 {
585 return gasStatus, ErrWrongTransactionSize
587 if err := checkTimeRange(tx, block); err != nil {
588 return gasStatus, err
590 if err := checkInputID(tx, block.Height); err != nil {
591 return gasStatus, err
594 vs := &validationState{
598 gasStatus: gasStatus,
599 cache: make(map[bc.Hash]error),
601 return vs.gasStatus, checkValid(vs, tx.TxHeader)
604 type validateTxWork struct {
610 // ValidateTxResult is the result of async tx validate
611 type ValidateTxResult struct {
617 // GetGasState return the gasStatus
618 func (r *ValidateTxResult) GetGasState() *GasState {
622 // GetError return the err
623 func (r *ValidateTxResult) GetError() error {
627 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
630 case work := <-workCh:
631 gasStatus, err := ValidateTx(work.tx, work.block)
632 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
640 // ValidateTxs validates txs in async mode
641 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
643 //init the goroutine validate worker
644 var wg sync.WaitGroup
645 workCh := make(chan *validateTxWork, txSize)
646 resultCh := make(chan *ValidateTxResult, txSize)
647 closeCh := make(chan struct{})
648 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
650 go validateTxWorker(workCh, resultCh, closeCh, &wg)
654 for i, tx := range txs {
655 workCh <- &validateTxWork{i: i, tx: tx, block: block}
658 //collect validate results
659 results := make([]*ValidateTxResult, txSize)
660 for i := 0; i < txSize; i++ {
662 results[result.i] = result