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:
254 if e.MainchainOutputId == nil {
255 return errors.Wrap(ErrMissingField, "crosschain input without mainchain output ID")
258 mainchainOutput, err := vs.tx.IntraChainOutput(*e.MainchainOutputId)
260 return errors.Wrap(err, "getting mainchain output")
263 assetID := e.AssetDefinition.ComputeAssetID()
264 if *mainchainOutput.Source.Value.AssetId != *consensus.BTMAssetID && *mainchainOutput.Source.Value.AssetId != assetID {
265 return errors.New("incorrect asset_id while checking CrossChainInput")
268 code := config.FederationWScript(config.CommonConfig)
270 VmVersion: e.ControlProgram.VmVersion,
274 if _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.DefaultGasCredit); err != nil {
275 return errors.Wrap(err, "checking cross-chain input control program")
280 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
281 return errors.Wrap(err, "checking cross-chain input destination")
283 vs.gasStatus.StorageGas = 0
286 if e.SpentOutputId == nil {
287 return errors.Wrap(ErrMissingField, "spend without spent output ID")
290 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
292 return errors.Wrap(err, "getting spend prevout")
295 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
297 return errors.Wrap(err, "checking control program")
299 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
303 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
308 return errors.WithDetailf(
310 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
311 spentOutput.Source.Value.Amount,
312 spentOutput.Source.Value.AssetId.Bytes(),
313 e.WitnessDestination.Value.Amount,
314 e.WitnessDestination.Value.AssetId.Bytes(),
319 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
320 return errors.Wrap(err, "checking spend destination")
324 if e.SpentOutputId == nil {
325 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
328 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
330 return errors.Wrap(err, "getting vetoInput prevout")
332 if len(voteOutput.Vote) != 64 {
336 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
338 return errors.Wrap(err, "checking control program")
340 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
344 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
349 return errors.WithDetailf(
351 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
352 voteOutput.Source.Value.Amount,
353 voteOutput.Source.Value.AssetId.Bytes(),
354 e.WitnessDestination.Value.Amount,
355 e.WitnessDestination.Value.AssetId.Bytes(),
360 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
361 return errors.Wrap(err, "checking vetoInput destination")
365 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
366 return ErrWrongCoinbaseTransaction
369 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
370 return ErrWrongCoinbaseAsset
373 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
374 return ErrCoinbaseArbitraryOversize
379 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
380 return errors.Wrap(err, "checking coinbase destination")
382 vs.gasStatus.StorageGas = 0
385 return fmt.Errorf("entry has unexpected type %T", e)
391 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
393 return errors.Wrap(ErrMissingField, "empty value source")
396 return errors.Wrap(ErrMissingField, "missing ref on value source")
398 if vs.Value == nil || vs.Value.AssetId == nil {
399 return errors.Wrap(ErrMissingField, "missing value on value source")
402 e, ok := vstate.tx.Entries[*vs.Ref]
404 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
408 vstate2.entryID = *vs.Ref
409 if err := checkValid(&vstate2, e); err != nil {
410 return errors.Wrap(err, "checking value source")
413 var dest *bc.ValueDestination
414 switch ref := e.(type) {
416 if vs.Position != 0 {
417 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
419 dest = ref.WitnessDestination
422 if vs.Position != 0 {
423 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
425 dest = ref.WitnessDestination
427 case *bc.CrossChainInput:
428 if vs.Position != 0 {
429 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
431 dest = ref.WitnessDestination
434 if vs.Position != 0 {
435 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
437 dest = ref.WitnessDestination
440 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
441 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
443 dest = ref.WitnessDestinations[vs.Position]
446 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
449 if dest.Ref == nil || *dest.Ref != vstate.entryID {
450 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
453 if dest.Position != vstate.sourcePos {
454 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
457 eq, err := dest.Value.Equal(vs.Value)
459 return errors.Sub(ErrMissingField, err)
462 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
468 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
470 return errors.Wrap(ErrMissingField, "empty value destination")
473 return errors.Wrap(ErrMissingField, "missing ref on value destination")
475 if vd.Value == nil || vd.Value.AssetId == nil {
476 return errors.Wrap(ErrMissingField, "missing value on value destination")
479 e, ok := vs.tx.Entries[*vd.Ref]
481 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
484 var src *bc.ValueSource
485 switch ref := e.(type) {
486 case *bc.IntraChainOutput:
487 if vd.Position != 0 {
488 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
492 case *bc.CrossChainOutput:
493 if vd.Position != 0 {
494 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
499 if vd.Position != 0 {
500 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
505 if vd.Position != 0 {
506 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
511 if vd.Position >= uint64(len(ref.Sources)) {
512 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
514 src = ref.Sources[vd.Position]
517 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
520 if src.Ref == nil || *src.Ref != vs.entryID {
521 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
524 if src.Position != vs.destPos {
525 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
528 eq, err := src.Value.Equal(vd.Value)
530 return errors.Sub(ErrMissingField, err)
533 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
539 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
540 for _, id := range tx.InputIDs {
541 if blockHeight >= ruleAA && id.IsZero() {
542 return ErrEmptyInputIDs
548 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
549 if tx.TimeRange == 0 {
553 if tx.TimeRange < block.Height {
554 return ErrBadTimeRange
560 // ValidateTx validates a transaction.
561 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
562 gasStatus := &GasState{GasValid: false}
563 if block.Version == 1 && tx.Version != 1 {
564 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
566 if tx.SerializedSize == 0 {
567 return gasStatus, ErrWrongTransactionSize
569 if err := checkTimeRange(tx, block); err != nil {
570 return gasStatus, err
572 if err := checkInputID(tx, block.Height); err != nil {
573 return gasStatus, err
576 vs := &validationState{
580 gasStatus: gasStatus,
581 cache: make(map[bc.Hash]error),
583 return vs.gasStatus, checkValid(vs, tx.TxHeader)
586 type validateTxWork struct {
592 type validateTxResult struct {
598 func (r *validateTxResult) GetGasState() *GasState {
602 func (r *validateTxResult) GetError() error {
606 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *validateTxResult, closeCh chan struct{}, wg *sync.WaitGroup) {
609 case work := <-workCh:
610 gasStatus, err := ValidateTx(work.tx, work.block)
611 resultCh <- &validateTxResult{i: work.i, gasStatus: gasStatus, err: err}
619 func ValidateTxs(txs []*bc.Tx, block *bc.Block) []*validateTxResult {
621 //init the goroutine validate worker
622 var wg sync.WaitGroup
623 workCh := make(chan *validateTxWork, txSize)
624 resultCh := make(chan *validateTxResult, txSize)
625 closeCh := make(chan struct{})
626 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
628 go validateTxWorker(workCh, resultCh, closeCh, &wg)
632 for i, tx := range txs {
633 workCh <- &validateTxWork{i: i, tx: tx, block: block}
636 //collect validate results
637 results := make([]*validateTxResult, txSize)
638 for i := 0; i < txSize; i++ {
640 results[result.i] = result