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.ActiveNetParams.VMGasRate); !ok {
64 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
67 if g.GasLeft > consensus.ActiveNetParams.MaxGasAmount {
68 g.GasLeft = consensus.ActiveNetParams.MaxGasAmount
71 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.ActiveNetParams.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.ActiveNetParams.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")
245 if err = checkValidSrc(&vs2, e.Source); err != nil {
246 return errors.Wrap(err, "checking retirement source")
249 case *bc.CrossChainInput:
250 if e.MainchainOutputId == nil {
251 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
254 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
256 return errors.Wrap(err, "getting mainchain output")
259 assetID := e.AssetDefinition.ComputeAssetID()
260 if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
261 return errors.New("incorrect asset_id while checking CrossChainInput")
265 VmVersion: e.ControlProgram.VmVersion,
266 Code: config.FederationWScript(config.CommonConfig),
269 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.ActiveNetParams.DefaultGasCredit); err != nil {
270 return errors.Wrap(err, "checking cross-chain input control program")
273 eq, err := mainchainOutput.Source.Value.Equal(e.WitnessDestination.Value)
279 return errors.WithDetailf(
281 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
282 mainchainOutput.Source.Value.Amount,
283 mainchainOutput.Source.Value.AssetId.Bytes(),
284 e.WitnessDestination.Value.Amount,
285 e.WitnessDestination.Value.AssetId.Bytes(),
291 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
292 return errors.Wrap(err, "checking cross-chain input destination")
294 vs.gasStatus.StorageGas = 0
297 if e.SpentOutputId == nil {
298 return errors.Wrap(ErrMissingField, "spend without spent output ID")
301 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
303 return errors.Wrap(err, "getting spend prevout")
306 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
308 return errors.Wrap(err, "checking control program")
310 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
314 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
319 return errors.WithDetailf(
321 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
322 spentOutput.Source.Value.Amount,
323 spentOutput.Source.Value.AssetId.Bytes(),
324 e.WitnessDestination.Value.Amount,
325 e.WitnessDestination.Value.AssetId.Bytes(),
330 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
331 return errors.Wrap(err, "checking spend destination")
335 if e.SpentOutputId == nil {
336 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
339 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
341 return errors.Wrap(err, "getting vetoInput prevout")
344 if len(voteOutput.Vote) != 64 {
348 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
350 return errors.Wrap(err, "checking control program")
352 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
356 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
361 return errors.WithDetailf(
363 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
364 voteOutput.Source.Value.Amount,
365 voteOutput.Source.Value.AssetId.Bytes(),
366 e.WitnessDestination.Value.Amount,
367 e.WitnessDestination.Value.AssetId.Bytes(),
372 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
373 return errors.Wrap(err, "checking vetoInput destination")
377 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
378 return ErrWrongCoinbaseTransaction
381 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
382 return ErrWrongCoinbaseAsset
385 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.ActiveNetParams.CoinbaseArbitrarySizeLimit {
386 return ErrCoinbaseArbitraryOversize
391 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
392 return errors.Wrap(err, "checking coinbase destination")
394 vs.gasStatus.StorageGas = 0
397 return fmt.Errorf("entry has unexpected type %T", e)
403 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
405 return errors.Wrap(ErrMissingField, "empty value source")
408 return errors.Wrap(ErrMissingField, "missing ref on value source")
410 if vs.Value == nil || vs.Value.AssetId == nil {
411 return errors.Wrap(ErrMissingField, "missing value on value source")
414 e, ok := vstate.tx.Entries[*vs.Ref]
416 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
420 vstate2.entryID = *vs.Ref
421 if err := checkValid(&vstate2, e); err != nil {
422 return errors.Wrap(err, "checking value source")
425 var dest *bc.ValueDestination
426 switch ref := e.(type) {
428 if vs.Position != 0 {
429 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
431 dest = ref.WitnessDestination
434 if vs.Position != 0 {
435 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
437 dest = ref.WitnessDestination
439 case *bc.CrossChainInput:
440 if vs.Position != 0 {
441 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
443 dest = ref.WitnessDestination
446 if vs.Position != 0 {
447 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
449 dest = ref.WitnessDestination
452 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
453 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
455 dest = ref.WitnessDestinations[vs.Position]
458 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
461 if dest.Ref == nil || *dest.Ref != vstate.entryID {
462 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
465 if dest.Position != vstate.sourcePos {
466 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
469 eq, err := dest.Value.Equal(vs.Value)
471 return errors.Sub(ErrMissingField, err)
474 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
480 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
482 return errors.Wrap(ErrMissingField, "empty value destination")
485 return errors.Wrap(ErrMissingField, "missing ref on value destination")
487 if vd.Value == nil || vd.Value.AssetId == nil {
488 return errors.Wrap(ErrMissingField, "missing value on value destination")
491 e, ok := vs.tx.Entries[*vd.Ref]
493 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
496 var src *bc.ValueSource
497 switch ref := e.(type) {
498 case *bc.IntraChainOutput:
499 if vd.Position != 0 {
500 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
504 case *bc.CrossChainOutput:
505 if vd.Position != 0 {
506 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
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 retirement destination", vd.Position)
523 if vd.Position >= uint64(len(ref.Sources)) {
524 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
526 src = ref.Sources[vd.Position]
529 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
532 if src.Ref == nil || *src.Ref != vs.entryID {
533 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
536 if src.Position != vs.destPos {
537 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
540 eq, err := src.Value.Equal(vd.Value)
542 return errors.Sub(ErrMissingField, err)
545 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
551 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
552 for _, id := range tx.InputIDs {
554 return ErrEmptyInputIDs
560 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
561 if tx.TimeRange == 0 {
565 if tx.TimeRange < block.Height {
566 return ErrBadTimeRange
572 // ValidateTx validates a transaction.
573 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
574 gasStatus := &GasState{GasValid: false}
575 if block.Version == 1 && tx.Version != 1 {
576 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
578 if tx.SerializedSize == 0 {
579 return gasStatus, ErrWrongTransactionSize
581 if err := checkTimeRange(tx, block); err != nil {
582 return gasStatus, err
584 if err := checkInputID(tx, block.Height); err != nil {
585 return gasStatus, err
588 vs := &validationState{
592 gasStatus: gasStatus,
593 cache: make(map[bc.Hash]error),
595 return vs.gasStatus, checkValid(vs, tx.TxHeader)
598 type validateTxWork struct {
604 // ValidateTxResult is the result of async tx validate
605 type ValidateTxResult struct {
611 // GetGasState return the gasStatus
612 func (r *ValidateTxResult) GetGasState() *GasState {
616 // GetError return the err
617 func (r *ValidateTxResult) GetError() error {
621 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
624 case work := <-workCh:
625 gasStatus, err := ValidateTx(work.tx, work.block)
626 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
634 // ValidateTxs validates txs in async mode
635 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*ValidateTxResult {
637 //init the goroutine validate worker
638 var wg sync.WaitGroup
639 workCh := make(chan *validateTxWork, txSize)
640 resultCh := make(chan *ValidateTxResult, txSize)
641 closeCh := make(chan struct{})
642 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
644 go validateTxWorker(workCh, resultCh, closeCh, &wg)
648 for i, tx := range txs {
649 workCh <- &validateTxWork{i: i, tx: tx, block: block}
652 //collect validate results
653 results := make([]*ValidateTxResult, txSize)
654 for i := 0; i < txSize; i++ {
656 results[result.i] = result