8 "github.com/vapor/config"
9 "github.com/vapor/consensus"
10 "github.com/vapor/consensus/segwit"
11 "github.com/vapor/errors"
12 "github.com/vapor/math/checked"
13 "github.com/vapor/protocol/bc"
14 "github.com/vapor/protocol/vm"
19 // validate transaction error
21 ErrTxVersion = errors.New("invalid transaction version")
22 ErrWrongTransactionSize = errors.New("invalid transaction size")
23 ErrBadTimeRange = errors.New("invalid transaction time range")
24 ErrEmptyInputIDs = errors.New("got the empty InputIDs")
25 ErrNotStandardTx = errors.New("not standard transaction")
26 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
27 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
28 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
29 ErrEmptyResults = errors.New("transaction has no results")
30 ErrMismatchedAssetID = errors.New("mismatched assetID")
31 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
32 ErrMismatchedReference = errors.New("mismatched reference")
33 ErrMismatchedValue = errors.New("mismatched value")
34 ErrMissingField = errors.New("missing required field")
35 ErrNoSource = errors.New("no source for value")
36 ErrOverflow = errors.New("arithmetic overflow/underflow")
37 ErrPosition = errors.New("invalid source or destination position")
38 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
39 ErrOverGasCredit = errors.New("all gas credit has been spend")
40 ErrGasCalculate = errors.New("gas usage calculate got a math error")
41 ErrVotePubKey = errors.New("invalid public key of vote")
42 ErrVoteOutputAmount = errors.New("invalid vote amount")
45 // GasState record the gas usage status
46 type GasState struct {
54 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
56 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
59 g.BTMValue = uint64(BTMValue)
62 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
63 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
66 if g.GasLeft > consensus.MaxGasAmount {
67 g.GasLeft = consensus.MaxGasAmount
70 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
71 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
76 func (g *GasState) setGasValid() error {
78 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
79 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
82 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
83 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
90 func (g *GasState) updateUsage(gasLeft int64) error {
92 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
95 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
99 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
102 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
103 return ErrOverGasCredit
108 // validationState contains the context that must propagate through
109 // the transaction graph when validating entries.
110 type validationState struct {
114 entryID bc.Hash // The ID of the nearest enclosing entry
115 sourcePos uint64 // The source position, for validate ValueSources
116 destPos uint64 // The destination position, for validate ValueDestinations
117 cache map[bc.Hash]error // Memoized per-entry validation results
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 _, BTMInputID := range vs.tx.GasInputIDs {
185 e, ok := vs.tx.Entries[BTMInputID]
187 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
191 vs2.entryID = BTMInputID
192 if err := checkValid(&vs2, e); err != nil {
193 return errors.Wrap(err, "checking gas input")
197 for i, dest := range e.WitnessDestinations {
199 vs2.destPos = uint64(i)
200 if err = checkValidDest(&vs2, dest); err != nil {
201 return errors.Wrapf(err, "checking mux destination %d", i)
205 if err := vs.gasStatus.setGasValid(); err != nil {
209 for i, src := range e.Sources {
211 vs2.sourcePos = uint64(i)
212 if err = checkValidSrc(&vs2, src); err != nil {
213 return errors.Wrapf(err, "checking mux source %d", i)
217 case *bc.IntraChainOutput:
220 if err = checkValidSrc(&vs2, e.Source); err != nil {
221 return errors.Wrap(err, "checking output source")
224 case *bc.CrossChainOutput:
227 if err = checkValidSrc(&vs2, e.Source); err != nil {
228 return errors.Wrap(err, "checking output source")
232 if len(e.Vote) != 64 {
237 if err = checkValidSrc(&vs2, e.Source); err != nil {
238 return errors.Wrap(err, "checking vote output source")
240 if e.Source.Value.Amount < consensus.MinVoteOutputAmount {
241 return ErrVoteOutputAmount
247 if err = checkValidSrc(&vs2, e.Source); err != nil {
248 return errors.Wrap(err, "checking retirement source")
251 case *bc.CrossChainInput:
252 _, err := vm.Verify(NewTxVMContext(vs, e, e.ControlProgram, e.WitnessArguments), consensus.DefaultGasCredit)
254 return errors.Wrap(err, "checking cross-chain input control program")
259 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
260 return errors.Wrap(err, "checking cross-chain input destination")
262 vs.gasStatus.StorageGas = 0
265 if e.SpentOutputId == nil {
266 return errors.Wrap(ErrMissingField, "spend without spent output ID")
269 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
271 return errors.Wrap(err, "getting spend prevout")
274 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
276 return errors.Wrap(err, "checking control program")
278 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
282 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
287 return errors.WithDetailf(
289 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
290 spentOutput.Source.Value.Amount,
291 spentOutput.Source.Value.AssetId.Bytes(),
292 e.WitnessDestination.Value.Amount,
293 e.WitnessDestination.Value.AssetId.Bytes(),
298 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
299 return errors.Wrap(err, "checking spend destination")
303 if e.SpentOutputId == nil {
304 return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
307 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
309 return errors.Wrap(err, "getting vetoInput prevout")
311 if len(voteOutput.Vote) != 64 {
315 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
317 return errors.Wrap(err, "checking control program")
319 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
323 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
328 return errors.WithDetailf(
330 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
331 voteOutput.Source.Value.Amount,
332 voteOutput.Source.Value.AssetId.Bytes(),
333 e.WitnessDestination.Value.Amount,
334 e.WitnessDestination.Value.AssetId.Bytes(),
339 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
340 return errors.Wrap(err, "checking vetoInput destination")
344 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
345 return ErrWrongCoinbaseTransaction
348 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
349 return ErrWrongCoinbaseAsset
352 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
353 return ErrCoinbaseArbitraryOversize
358 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
359 return errors.Wrap(err, "checking coinbase destination")
361 vs.gasStatus.StorageGas = 0
364 return fmt.Errorf("entry has unexpected type %T", e)
370 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
372 return errors.Wrap(ErrMissingField, "empty value source")
375 return errors.Wrap(ErrMissingField, "missing ref on value source")
377 if vs.Value == nil || vs.Value.AssetId == nil {
378 return errors.Wrap(ErrMissingField, "missing value on value source")
381 e, ok := vstate.tx.Entries[*vs.Ref]
383 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
387 vstate2.entryID = *vs.Ref
388 if err := checkValid(&vstate2, e); err != nil {
389 return errors.Wrap(err, "checking value source")
392 var dest *bc.ValueDestination
393 switch ref := e.(type) {
395 if vs.Position != 0 {
396 return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
398 dest = ref.WitnessDestination
401 if vs.Position != 0 {
402 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
404 dest = ref.WitnessDestination
406 case *bc.CrossChainInput:
407 if vs.Position != 0 {
408 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
410 dest = ref.WitnessDestination
413 if vs.Position != 0 {
414 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
416 dest = ref.WitnessDestination
419 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
420 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
422 dest = ref.WitnessDestinations[vs.Position]
425 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
428 if dest.Ref == nil || *dest.Ref != vstate.entryID {
429 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
432 if dest.Position != vstate.sourcePos {
433 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
436 eq, err := dest.Value.Equal(vs.Value)
438 return errors.Sub(ErrMissingField, err)
441 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
447 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
449 return errors.Wrap(ErrMissingField, "empty value destination")
452 return errors.Wrap(ErrMissingField, "missing ref on value destination")
454 if vd.Value == nil || vd.Value.AssetId == nil {
455 return errors.Wrap(ErrMissingField, "missing value on value destination")
458 e, ok := vs.tx.Entries[*vd.Ref]
460 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
463 var src *bc.ValueSource
464 switch ref := e.(type) {
465 case *bc.IntraChainOutput:
466 if vd.Position != 0 {
467 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
471 case *bc.CrossChainOutput:
472 if vd.Position != 0 {
473 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
478 if vd.Position != 0 {
479 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
484 if vd.Position != 0 {
485 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
490 if vd.Position >= uint64(len(ref.Sources)) {
491 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
493 src = ref.Sources[vd.Position]
496 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
499 if src.Ref == nil || *src.Ref != vs.entryID {
500 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
503 if src.Position != vs.destPos {
504 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
507 eq, err := src.Value.Equal(vd.Value)
509 return errors.Sub(ErrMissingField, err)
512 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
518 func checkFedaration(tx *bc.Tx) error {
519 for _, id := range tx.InputIDs {
520 switch inp := tx.Entries[id].(type) {
521 case *bc.CrossChainInput:
522 fedProg := config.FederationProgrom(config.CommonConfig)
523 if !bytes.Equal(inp.ControlProgram.Code, fedProg) {
524 return errors.New("The federal controlProgram is incorrect")
533 func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
534 for _, id := range tx.InputIDs {
535 if blockHeight >= ruleAA && id.IsZero() {
536 return ErrEmptyInputIDs
540 if err := checkFedaration(tx); err != nil {
544 for _, id := range tx.GasInputIDs {
545 spend, err := tx.Spend(id)
551 outputEntry, err := tx.Entry(*spend.SpentOutputId)
555 switch output := outputEntry.(type) {
556 case *bc.IntraChainOutput:
557 code = output.ControlProgram.Code
559 code = output.ControlProgram.Code
561 return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", id.Bytes(), outputEntry)
564 if !segwit.IsP2WScript(code) {
565 return ErrNotStandardTx
571 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
572 if tx.TimeRange == 0 {
576 if tx.TimeRange < block.Height {
577 return ErrBadTimeRange
583 // ValidateTx validates a transaction.
584 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
585 gasStatus := &GasState{GasValid: false}
586 if block.Version == 1 && tx.Version != 1 {
587 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
589 if tx.SerializedSize == 0 {
590 return gasStatus, ErrWrongTransactionSize
592 if err := checkTimeRange(tx, block); err != nil {
593 return gasStatus, err
595 if err := checkStandardTx(tx, block.Height); err != nil {
596 return gasStatus, err
599 vs := &validationState{
603 gasStatus: gasStatus,
604 cache: make(map[bc.Hash]error),
606 return vs.gasStatus, checkValid(vs, tx.TxHeader)