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")
248 if e.Source.Value.Amount < consensus.ActiveNetParams.MinVoteOutputAmount {
249 return ErrVoteOutputAmount
255 if err = checkValidSrc(&vs2, e.Source); err != nil {
256 return errors.Wrap(err, "checking retirement source")
259 case *bc.CrossChainInput:
260 if e.MainchainOutputId == nil {
261 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
264 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
266 return errors.Wrap(err, "getting mainchain output")
269 assetID := e.AssetDefinition.ComputeAssetID()
270 if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
271 return errors.New("incorrect asset_id while checking CrossChainInput")
275 VmVersion: e.ControlProgram.VmVersion,
276 Code: config.FederationWScript(config.CommonConfig),
279 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
280 return errors.Wrap(err, "checking cross-chain input control program")
283 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
289 return errors.WithDetailf(
291 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
292 mainchainOutput.Source.Value.Amount,
293 mainchainOutput.Source.Value.AssetId.Bytes(),
294 e.WitnessDestination.Value.Amount,
295 e.WitnessDestination.Value.AssetId.Bytes(),
301 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
302 return errors.Wrap(err, "checking cross-chain input destination")
304 vs.gasStatus.StorageGas = 0
307 if e.SpentOutputId == nil {
308 return errors.Wrap(ErrMissingField, "spend without spent output ID")
311 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
313 return errors.Wrap(err, "getting spend prevout")
316 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
318 return errors.Wrap(err, "checking control program")
320 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
324 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
329 return errors.WithDetailf(
331 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
332 spentOutput.Source.Value.Amount,
333 spentOutput.Source.Value.AssetId.Bytes(),
334 e.WitnessDestination.Value.Amount,
335 e.WitnessDestination.Value.AssetId.Bytes(),
340 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
341 return errors.Wrap(err, "checking spend destination")
345 if e.SpentOutputId == nil {
346 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
349 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
351 return errors.Wrap(err, "getting vetoInput prevout")
354 if len(voteOutput.Vote) != 64 {
358 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
360 return errors.Wrap(err, "checking control program")
362 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
366 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
371 return errors.WithDetailf(
373 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
374 voteOutput.Source.Value.Amount,
375 voteOutput.Source.Value.AssetId.Bytes(),
376 e.WitnessDestination.Value.Amount,
377 e.WitnessDestination.Value.AssetId.Bytes(),
382 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
383 return errors.Wrap(err, "checking vetoInput destination")
387 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
388 return ErrWrongCoinbaseTransaction
391 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
392 return ErrWrongCoinbaseAsset
395 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
396 return ErrCoinbaseArbitraryOversize
401 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
402 return errors.Wrap(err, "checking coinbase destination")
404 vs.gasStatus.StorageGas = 0
407 return fmt.Errorf("entry has unexpected type %T", e)
413 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
415 return errors.Wrap(ErrMissingField, "empty value source")
418 return errors.Wrap(ErrMissingField, "missing ref on value source")
420 if vs.Value == nil || vs.Value.AssetId == nil {
421 return errors.Wrap(ErrMissingField, "missing value on value source")
424 e, ok := vstate.tx.Entries[*vs.Ref]
426 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
430 vstate2.entryID = *vs.Ref
431 if err := checkValid(&vstate2, e); err != nil {
432 return errors.Wrap(err, "checking value source")
435 var dest *bc.ValueDestination
436 switch ref := e.(type) {
438 if vs.Position != 0 {
439 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
441 dest = ref.WitnessDestination
444 if vs.Position != 0 {
445 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
447 dest = ref.WitnessDestination
449 case *bc.CrossChainInput:
450 if vs.Position != 0 {
451 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
453 dest = ref.WitnessDestination
456 if vs.Position != 0 {
457 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
459 dest = ref.WitnessDestination
462 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
463 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
465 dest = ref.WitnessDestinations[vs.Position]
468 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
471 if dest.Ref == nil || *dest.Ref != vstate.entryID {
472 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
475 if dest.Position != vstate.sourcePos {
476 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
479 eq, err := dest.Value.Equal(vs.Value)
481 return errors.Sub(ErrMissingField, err)
484 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
490 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
492 return errors.Wrap(ErrMissingField, "empty value destination")
495 return errors.Wrap(ErrMissingField, "missing ref on value destination")
497 if vd.Value == nil || vd.Value.AssetId == nil {
498 return errors.Wrap(ErrMissingField, "missing value on value destination")
501 e, ok := vs.tx.Entries[*vd.Ref]
503 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
506 var src *bc.ValueSource
507 switch ref := e.(type) {
508 case *bc.IntraChainOutput:
509 if vd.Position != 0 {
510 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
514 case *bc.CrossChainOutput:
515 if vd.Position != 0 {
516 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
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 retirement destination", vd.Position)
533 if vd.Position >= uint64(len(ref.Sources)) {
534 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
536 src = ref.Sources[vd.Position]
539 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
542 if src.Ref == nil || *src.Ref != vs.entryID {
543 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
546 if src.Position != vs.destPos {
547 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
550 eq, err := src.Value.Equal(vd.Value)
552 return errors.Sub(ErrMissingField, err)
555 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
561 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
562 for _, id := range tx.InputIDs {
564 return ErrEmptyInputIDs
570 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
571 if tx.TimeRange == 0 {
575 if tx.TimeRange < block.Height {
576 return ErrBadTimeRange
582 // ValidateTx validates a transaction.
583 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
584 gasStatus := &GasState{GasValid: false}
585 if block.Version == 1 && tx.Version != 1 {
586 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
588 if tx.SerializedSize == 0 {
589 return gasStatus, ErrWrongTransactionSize
591 if err := checkTimeRange(tx, block); err != nil {
592 return gasStatus, err
594 if err := checkInputID(tx, block.Height); err != nil {
595 return gasStatus, err
598 vs := &validationState{
602 gasStatus: gasStatus,
603 cache: make(map[bc.Hash]error),
605 return vs.gasStatus, checkValid(vs, tx.TxHeader)
608 type validateTxWork struct {
614 // ValidateTxResult is the result of async tx validate
615 type ValidateTxResult struct {
621 // GetGasState return the gasStatus
622 func (r *ValidateTxResult) GetGasState() *GasState {
626 // GetError return the err
627 func (r *ValidateTxResult) GetError() error {
631 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
634 case work := <-workCh:
635 gasStatus, err := ValidateTx(work.tx, work.block)
636 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
644 // ValidateTxs validates txs in async mode
645 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
647 //init the goroutine validate worker
648 var wg sync.WaitGroup
649 workCh := make(chan *validateTxWork, txSize)
650 resultCh := make(chan *ValidateTxResult, txSize)
651 closeCh := make(chan struct{})
652 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
654 go validateTxWorker(workCh, resultCh, closeCh, &wg)
658 for i, tx := range txs {
659 workCh <- &validateTxWork{i: i, tx: tx, block: block}
662 //collect validate results
663 results := make([]*ValidateTxResult, txSize)
664 for i := 0; i < txSize; i++ {
666 results[result.i] = result