9 "github.com/bytom/bytom/consensus"
10 "github.com/bytom/bytom/errors"
11 "github.com/bytom/bytom/math/checked"
12 "github.com/bytom/bytom/protocol/bc"
13 "github.com/bytom/bytom/protocol/vm"
16 // validate transaction error
18 ErrTxVersion = errors.New("invalid transaction version")
19 ErrWrongTransactionSize = errors.New("invalid transaction size")
20 ErrBadTimeRange = errors.New("invalid transaction time range")
21 ErrInputDoubleSend = errors.New("got the double spend input")
22 ErrNotStandardTx = errors.New("not standard transaction")
23 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
24 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
25 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
26 ErrEmptyResults = errors.New("transaction has no results")
27 ErrMismatchedAssetID = errors.New("mismatched assetID")
28 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
29 ErrMismatchedReference = errors.New("mismatched reference")
30 ErrMismatchedValue = errors.New("mismatched value")
31 ErrMissingField = errors.New("missing required field")
32 ErrNoSource = errors.New("no source for value")
33 ErrOverflow = errors.New("arithmetic overflow/underflow")
34 ErrPosition = errors.New("invalid source or destination position")
35 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
36 ErrOverGasCredit = errors.New("all gas credit has been spend")
37 ErrGasCalculate = errors.New("gas usage calculate got a math error")
38 ErrVotePubKey = errors.New("invalid public key of vote")
39 ErrVoteOutputAmount = errors.New("invalid vote amount")
40 ErrVoteOutputAseet = errors.New("incorrect asset_id while checking vote asset")
43 // GasState record the gas usage status
44 type GasState struct {
51 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
53 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
56 g.BTMValue = uint64(BTMValue)
59 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
60 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
63 if g.GasLeft > consensus.MaxGasAmount {
64 g.GasLeft = consensus.MaxGasAmount
67 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
68 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
73 func (g *GasState) setGasValid() error {
75 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
76 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
79 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
80 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
86 func (g *GasState) updateUsage(gasLeft int64) error {
88 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
91 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
95 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
98 if g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft {
99 return ErrOverGasCredit
104 // ProgramConverterFunc represent a func convert control program
105 type ProgramConverterFunc func(prog []byte) ([]byte, error)
107 // validationState contains the context that must propagate through
108 // the transaction graph when validating entries.
109 type validationState struct {
113 entryID bc.Hash // The ID of the nearest enclosing entry
114 sourcePos uint64 // The source position, for validate ValueSources
115 destPos uint64 // The destination position, for validate ValueDestinations
116 cache map[bc.Hash]error // Memoized per-entry validation results
117 converter ProgramConverterFunc // Program converter function
120 func checkValid(vs *validationState, e bc.Entry) (err error) {
122 entryID := bc.EntryID(e)
123 if err, ok = vs.cache[entryID]; ok {
128 vs.cache[entryID] = err
131 switch e := e.(type) {
133 for i, resID := range e.ResultIds {
134 resultEntry := vs.tx.Entries[*resID]
137 if err = checkValid(&vs2, resultEntry); err != nil {
138 return errors.Wrapf(err, "checking result %d", i)
142 if e.Version == 1 && len(e.ResultIds) == 0 {
143 return ErrEmptyResults
147 parity := make(map[bc.AssetID]int64)
148 for i, src := range e.Sources {
149 if src.Value.Amount > math.MaxInt64 {
150 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
152 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
154 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])
156 parity[*src.Value.AssetId] = sum
159 for i, dest := range e.WitnessDestinations {
160 sum, ok := parity[*dest.Value.AssetId]
162 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
164 if dest.Value.Amount > math.MaxInt64 {
165 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
167 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
169 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)
171 parity[*dest.Value.AssetId] = diff
174 for assetID, amount := range parity {
175 if assetID == *consensus.BTMAssetID {
176 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
179 } else if amount != 0 {
180 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
184 for i, dest := range e.WitnessDestinations {
186 vs2.destPos = uint64(i)
187 if err = checkValidDest(&vs2, dest); err != nil {
188 return errors.Wrapf(err, "checking mux destination %d", i)
192 for i, src := range e.Sources {
194 vs2.sourcePos = uint64(i)
195 if err = checkValidSrc(&vs2, src); err != nil {
196 return errors.Wrapf(err, "checking mux source %d", i)
200 if err := vs.gasStatus.setGasValid(); err != nil {
207 if err = checkValidSrc(&vs2, e.Source); err != nil {
208 return errors.Wrap(err, "checking output source")
214 if err = checkValidSrc(&vs2, e.Source); err != nil {
215 return errors.Wrap(err, "checking retirement source")
218 if len(e.Vote) != 64 {
224 if err = checkValidSrc(&vs2, e.Source); err != nil {
225 return errors.Wrap(err, "checking vote output source")
228 if e.Source.Value.Amount < consensus.MinVoteOutputAmount {
229 return ErrVoteOutputAmount
232 if *e.Source.Value.AssetId != *consensus.BTMAssetID {
233 return ErrVoteOutputAseet
236 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
237 if computedAssetID != *e.Value.AssetId {
238 return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
241 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, [][]byte{}, e.WitnessArguments), vs.gasStatus.GasLeft)
243 return errors.Wrap(err, "checking issuance program")
245 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
251 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
252 return errors.Wrap(err, "checking issuance destination")
256 if e.SpentOutputId == nil {
257 return errors.Wrap(ErrMissingField, "spend without spent output ID")
259 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
261 return errors.Wrap(err, "getting spend prevout")
264 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, spentOutput.StateData, e.WitnessArguments), vs.gasStatus.GasLeft)
266 return errors.Wrap(err, "checking control program")
268 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
272 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
277 return errors.WithDetailf(
279 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
280 spentOutput.Source.Value.Amount,
281 spentOutput.Source.Value.AssetId.Bytes(),
282 e.WitnessDestination.Value.Amount,
283 e.WitnessDestination.Value.AssetId.Bytes(),
289 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
290 return errors.Wrap(err, "checking spend destination")
293 if e.SpentOutputId == nil {
294 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
297 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
299 return errors.Wrap(err, "getting vetoInput prevout")
302 if len(voteOutput.Vote) != 64 {
306 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, voteOutput.StateData, 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 := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
319 return errors.WithDetailf(
321 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
322 voteOutput.Source.Value.Amount,
323 voteOutput.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 vetoInput destination")
335 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
336 return ErrWrongCoinbaseTransaction
339 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
340 return ErrWrongCoinbaseAsset
343 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
344 return ErrCoinbaseArbitraryOversize
349 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
350 return errors.Wrap(err, "checking coinbase destination")
352 vs.gasStatus.StorageGas = 0
355 return fmt.Errorf("entry has unexpected type %T", e)
361 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
363 return errors.Wrap(ErrMissingField, "empty value source")
366 return errors.Wrap(ErrMissingField, "missing ref on value source")
368 if vs.Value == nil || vs.Value.AssetId == nil {
369 return errors.Wrap(ErrMissingField, "missing value on value source")
372 e, ok := vstate.tx.Entries[*vs.Ref]
374 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
378 vstate2.entryID = *vs.Ref
379 if err := checkValid(&vstate2, e); err != nil {
380 return errors.Wrap(err, "checking value source")
383 var dest *bc.ValueDestination
384 switch ref := e.(type) {
386 if vs.Position != 0 {
387 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
389 dest = ref.WitnessDestination
392 if vs.Position != 0 {
393 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
395 dest = ref.WitnessDestination
398 if vs.Position != 0 {
399 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
401 dest = ref.WitnessDestination
404 if vs.Position != 0 {
405 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
407 dest = ref.WitnessDestination
410 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
411 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
413 dest = ref.WitnessDestinations[vs.Position]
416 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
419 if dest.Ref == nil || *dest.Ref != vstate.entryID {
420 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
423 if dest.Position != vstate.sourcePos {
424 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
427 eq, err := dest.Value.Equal(vs.Value)
429 return errors.Sub(ErrMissingField, err)
432 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
438 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
440 return errors.Wrap(ErrMissingField, "empty value destination")
443 return errors.Wrap(ErrMissingField, "missing ref on value destination")
445 if vd.Value == nil || vd.Value.AssetId == nil {
446 return errors.Wrap(ErrMissingField, "missing value on value destination")
449 e, ok := vs.tx.Entries[*vd.Ref]
451 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
454 var src *bc.ValueSource
455 switch ref := e.(type) {
457 if vd.Position != 0 {
458 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
463 if vd.Position != 0 {
464 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
469 if vd.Position != 0 {
470 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
475 if vd.Position >= uint64(len(ref.Sources)) {
476 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
478 src = ref.Sources[vd.Position]
481 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
484 if src.Ref == nil || *src.Ref != vs.entryID {
485 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
488 if src.Position != vs.destPos {
489 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
492 eq, err := src.Value.Equal(vd.Value)
494 return errors.Sub(ErrMissingField, err)
497 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
503 func checkDoubleSpend(tx *bc.Tx) error {
504 usedInputMap := make(map[bc.Hash]bool)
505 for _, id := range tx.InputIDs {
506 if _, ok := usedInputMap[id]; ok {
507 return ErrInputDoubleSend
510 usedInputMap[id] = true
516 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
517 if tx.TimeRange == 0 {
521 if tx.TimeRange < block.Height {
522 return ErrBadTimeRange
527 // ValidateTx validates a transaction.
528 func ValidateTx(tx *bc.Tx, block *bc.Block, converter ProgramConverterFunc) (*GasState, error) {
529 if block.Version == 1 && tx.Version != 1 {
530 return nil, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
533 if tx.SerializedSize == 0 {
534 return nil, ErrWrongTransactionSize
537 if err := checkTimeRange(tx, block); err != nil {
541 if err := checkDoubleSpend(tx); err != nil {
545 vs := &validationState{
549 gasStatus: &GasState{},
550 cache: make(map[bc.Hash]error),
551 converter: converter,
554 if err := checkValid(vs, tx.TxHeader); err != nil {
558 return vs.gasStatus, nil
561 type validateTxWork struct {
567 // ValidateTxResult is the result of async tx validate
568 type ValidateTxResult struct {
574 // GetGasState return the gasStatus
575 func (r *ValidateTxResult) GetGasState() *GasState {
579 // GetError return the err
580 func (r *ValidateTxResult) GetError() error {
584 func validateTxWorker(workCh chan *validateTxWork, resultCh chan *ValidateTxResult, wg *sync.WaitGroup, converter ProgramConverterFunc) {
585 for work := range workCh {
586 gasStatus, err := ValidateTx(work.tx, work.block, converter)
587 resultCh <- &ValidateTxResult{i: work.i, gasStatus: gasStatus, err: err}
592 // ValidateTxs validates txs in async mode
593 func ValidateTxs(txs []*bc.Tx, block *bc.Block, converter ProgramConverterFunc) []*ValidateTxResult {
595 validateWorkerNum := runtime.NumCPU()
596 //init the goroutine validate worker
597 var wg sync.WaitGroup
598 workCh := make(chan *validateTxWork, txSize)
599 resultCh := make(chan *ValidateTxResult, txSize)
600 for i := 0; i <= validateWorkerNum && i < txSize; i++ {
602 go validateTxWorker(workCh, resultCh, &wg, converter)
606 for i, tx := range txs {
607 workCh <- &validateTxWork{i: i, tx: tx, block: block}
611 //collect validate results
612 results := make([]*ValidateTxResult, txSize)
613 for i := 0; i < txSize; i++ {
615 results[result.i] = result