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
21 // validate transaction error
23 ErrTxVersion = errors.New("invalid transaction version")
24 ErrWrongTransactionSize = errors.New("invalid transaction size")
25 ErrBadTimeRange = errors.New("invalid transaction time range")
26 ErrEmptyInputIDs = errors.New("got the empty InputIDs")
27 ErrNotStandardTx = errors.New("not standard transaction")
28 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
29 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
30 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
31 ErrEmptyResults = errors.New("transaction has no results")
32 ErrMismatchedAssetID = errors.New("mismatched assetID")
33 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
34 ErrMismatchedReference = errors.New("mismatched reference")
35 ErrMismatchedValue = errors.New("mismatched value")
36 ErrMissingField = errors.New("missing required field")
37 ErrNoSource = errors.New("no source for value")
38 ErrOverflow = errors.New("arithmetic overflow/underflow")
39 ErrPosition = errors.New("invalid source or destination position")
40 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
41 ErrOverGasCredit = errors.New("all gas credit has been spend")
42 ErrGasCalculate = errors.New("gas usage calculate got a math error")
43 ErrVotePubKey = errors.New("invalid public key of vote")
44 ErrVoteOutputAmount = errors.New("invalid vote amount")
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)
64 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
65 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
68 if g.GasLeft > consensus.MaxGasAmount {
69 g.GasLeft = consensus.MaxGasAmount
72 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
73 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
78 func (g *GasState) setGasValid() error {
80 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
81 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
84 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
85 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
92 func (g *GasState) updateUsage(gasLeft int64) error {
94 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
97 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
101 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
104 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
105 return ErrOverGasCredit
110 // validationState contains the context that must propagate through
111 // the transaction graph when validating entries.
112 type validationState struct {
116 entryID bc.Hash // The ID of the nearest enclosing entry
117 sourcePos uint64 // The source position, for validate ValueSources
118 destPos uint64 // The destination position, for validate ValueDestinations
119 cache map[bc.Hash]error // Memoized per-entry validation results
122 func checkValid(vs *validationState, e bc.Entry) (err error) {
124 entryID := bc.EntryID(e)
125 if err, ok = vs.cache[entryID]; ok {
130 vs.cache[entryID] = err
133 switch e := e.(type) {
135 for i, resID := range e.ResultIds {
136 resultEntry := vs.tx.Entries[*resID]
139 if err = checkValid(&vs2, resultEntry); err != nil {
140 return errors.Wrapf(err, "checking result %d", i)
144 if e.Version == 1 && len(e.ResultIds) == 0 {
145 return ErrEmptyResults
149 parity := make(map[bc.AssetID]int64)
150 for i, src := range e.Sources {
151 if src.Value.Amount > math.MaxInt64 {
152 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
154 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
156 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])
158 parity[*src.Value.AssetId] = sum
161 for i, dest := range e.WitnessDestinations {
162 sum, ok := parity[*dest.Value.AssetId]
164 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
166 if dest.Value.Amount > math.MaxInt64 {
167 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
169 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
171 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)
173 parity[*dest.Value.AssetId] = diff
176 for assetID, amount := range parity {
177 if assetID == *consensus.BTMAssetID {
178 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
181 } else if amount != 0 {
182 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
186 for _, BTMInputID := range vs.tx.GasInputIDs {
187 e, ok := vs.tx.Entries[BTMInputID]
189 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
193 vs2.entryID = BTMInputID
194 if err := checkValid(&vs2, e); err != nil {
195 return errors.Wrap(err, "checking gas input")
199 for i, dest := range e.WitnessDestinations {
201 vs2.destPos = uint64(i)
202 if err = checkValidDest(&vs2, dest); err != nil {
203 return errors.Wrapf(err, "checking mux destination %d", i)
207 if err := vs.gasStatus.setGasValid(); err != nil {
211 for i, src := range e.Sources {
213 vs2.sourcePos = uint64(i)
214 if err = checkValidSrc(&vs2, src); err != nil {
215 return errors.Wrapf(err, "checking mux source %d", i)
219 case *bc.IntraChainOutput:
222 if err = checkValidSrc(&vs2, e.Source); err != nil {
223 return errors.Wrap(err, "checking output source")
226 case *bc.CrossChainOutput:
229 if err = checkValidSrc(&vs2, e.Source); err != nil {
230 return errors.Wrap(err, "checking output source")
234 if len(e.Vote) != 64 {
239 if err = checkValidSrc(&vs2, e.Source); err != nil {
240 return errors.Wrap(err, "checking vote output source")
242 if e.Source.Value.Amount < consensus.MinVoteOutputAmount {
243 return ErrVoteOutputAmount
249 if err = checkValidSrc(&vs2, e.Source); err != nil {
250 return errors.Wrap(err, "checking retirement source")
253 case *bc.CrossChainInput:
255 assetID := e.AssetDefinition.ComputeAssetID()
256 if *e.Value.AssetId != *consensus.BTMAssetID && *e.Value.AssetId != assetID {
257 return errors.New("incorrect asset_id while checking CrossChainInput")
260 code := config.FederationWScript(config.CommonConfig)
262 VmVersion: e.ControlProgram.VmVersion,
265 _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.DefaultGasCredit)
267 return errors.Wrap(err, "checking cross-chain input control program")
272 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
273 return errors.Wrap(err, "checking cross-chain input destination")
275 vs.gasStatus.StorageGas = 0
278 if e.SpentOutputId == nil {
279 return errors.Wrap(ErrMissingField, "spend without spent output ID")
282 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
284 return errors.Wrap(err, "getting spend prevout")
287 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
289 return errors.Wrap(err, "checking control program")
291 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
295 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
300 return errors.WithDetailf(
302 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
303 spentOutput.Source.Value.Amount,
304 spentOutput.Source.Value.AssetId.Bytes(),
305 e.WitnessDestination.Value.Amount,
306 e.WitnessDestination.Value.AssetId.Bytes(),
311 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
312 return errors.Wrap(err, "checking spend destination")
316 if e.SpentOutputId == nil {
317 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
320 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
322 return errors.Wrap(err, "getting vetoInput prevout")
324 if len(voteOutput.Vote) != 64 {
328 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
330 return errors.Wrap(err, "checking control program")
332 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
336 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
341 return errors.WithDetailf(
343 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
344 voteOutput.Source.Value.Amount,
345 voteOutput.Source.Value.AssetId.Bytes(),
346 e.WitnessDestination.Value.Amount,
347 e.WitnessDestination.Value.AssetId.Bytes(),
352 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
353 return errors.Wrap(err, "checking vetoInput destination")
357 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
358 return ErrWrongCoinbaseTransaction
361 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
362 return ErrWrongCoinbaseAsset
365 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
366 return ErrCoinbaseArbitraryOversize
371 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
372 return errors.Wrap(err, "checking coinbase destination")
374 vs.gasStatus.StorageGas = 0
377 return fmt.Errorf("entry has unexpected type %T", e)
383 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
385 return errors.Wrap(ErrMissingField, "empty value source")
388 return errors.Wrap(ErrMissingField, "missing ref on value source")
390 if vs.Value == nil || vs.Value.AssetId == nil {
391 return errors.Wrap(ErrMissingField, "missing value on value source")
394 e, ok := vstate.tx.Entries[*vs.Ref]
396 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
400 vstate2.entryID = *vs.Ref
401 if err := checkValid(&vstate2, e); err != nil {
402 return errors.Wrap(err, "checking value source")
405 var dest *bc.ValueDestination
406 switch ref := e.(type) {
408 if vs.Position != 0 {
409 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
411 dest = ref.WitnessDestination
414 if vs.Position != 0 {
415 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
417 dest = ref.WitnessDestination
419 case *bc.CrossChainInput:
420 if vs.Position != 0 {
421 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
423 dest = ref.WitnessDestination
426 if vs.Position != 0 {
427 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
429 dest = ref.WitnessDestination
432 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
433 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
435 dest = ref.WitnessDestinations[vs.Position]
438 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
441 if dest.Ref == nil || *dest.Ref != vstate.entryID {
442 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
445 if dest.Position != vstate.sourcePos {
446 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
449 eq, err := dest.Value.Equal(vs.Value)
451 return errors.Sub(ErrMissingField, err)
454 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
460 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
462 return errors.Wrap(ErrMissingField, "empty value destination")
465 return errors.Wrap(ErrMissingField, "missing ref on value destination")
467 if vd.Value == nil || vd.Value.AssetId == nil {
468 return errors.Wrap(ErrMissingField, "missing value on value destination")
471 e, ok := vs.tx.Entries[*vd.Ref]
473 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
476 var src *bc.ValueSource
477 switch ref := e.(type) {
478 case *bc.IntraChainOutput:
479 if vd.Position != 0 {
480 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
484 case *bc.CrossChainOutput:
485 if vd.Position != 0 {
486 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
491 if vd.Position != 0 {
492 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
497 if vd.Position != 0 {
498 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
503 if vd.Position >= uint64(len(ref.Sources)) {
504 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
506 src = ref.Sources[vd.Position]
509 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
512 if src.Ref == nil || *src.Ref != vs.entryID {
513 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
516 if src.Position != vs.destPos {
517 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
520 eq, err := src.Value.Equal(vd.Value)
522 return errors.Sub(ErrMissingField, err)
525 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
531 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
532 for _, id := range tx.InputIDs {
533 if blockHeight >= ruleAA && id.IsZero() {
534 return ErrEmptyInputIDs
540 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
541 if tx.TimeRange == 0 {
545 if tx.TimeRange < block.Height {
546 return ErrBadTimeRange
552 // ValidateTx validates a transaction.
553 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
554 gasStatus := &GasState{GasValid: false}
555 if block.Version == 1 && tx.Version != 1 {
556 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
558 if tx.SerializedSize == 0 {
559 return gasStatus, ErrWrongTransactionSize
561 if err := checkTimeRange(tx, block); err != nil {
562 return gasStatus, err
564 if err := checkInputID(tx, block.Height); err != nil {
565 return gasStatus, err
568 vs := &validationState{
572 gasStatus: gasStatus,
573 cache: make(map[bc.Hash]error),
575 return vs.gasStatus, checkValid(vs, tx.TxHeader)
578 type validateTxWork struct {
584 type validateTxResult struct {
590 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *validateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
593 case work := <-workCh:
594 gasStatus, err := ValidateTx(work.tx, work.block)
595 resultCh <- &validateTxResult{i: work.i, gasStatus: gasStatus, err: err}
603 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*validateTxResult {
605 //init the goroutine validate worker
606 var wg sync.WaitGroup
607 workCh := make(chan *validateTxWork, txSize)
608 resultCh := make(chan *validateTxResult, txSize)
609 closeCh := make(chan struct{})
610 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
612 go validateTxWorker(workCh, resultCh, closeCh, &wg)
616 for i, tx := range txs {
617 workCh <- &validateTxWork{i: i, tx: tx, block: block}
620 //collect validate results
621 results := make([]*validateTxResult, txSize)
622 for i := 0; i < txSize; i++ {
624 results[result.i] = result