7 "github.com/vapor/claim"
8 "github.com/vapor/consensus"
9 "github.com/vapor/consensus/segwit"
10 "github.com/vapor/errors"
11 "github.com/vapor/math/checked"
12 "github.com/vapor/protocol/bc"
13 "github.com/vapor/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 ErrNotStandardTx = errors.New("not standard transaction")
22 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
23 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
24 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
25 ErrEmptyResults = errors.New("transaction has no results")
26 ErrMismatchedAssetID = errors.New("mismatched assetID")
27 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
28 ErrMismatchedReference = errors.New("mismatched reference")
29 ErrMismatchedValue = errors.New("mismatched value")
30 ErrMissingField = errors.New("missing required field")
31 ErrNoSource = errors.New("no source for value")
32 ErrOverflow = errors.New("arithmetic overflow/underflow")
33 ErrPosition = errors.New("invalid source or destination position")
34 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
35 ErrOverGasCredit = errors.New("all gas credit has been spend")
36 ErrGasCalculate = errors.New("gas usage calculate got a math error")
39 // GasState record the gas usage status
40 type GasState struct {
48 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
50 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
53 g.BTMValue = uint64(BTMValue)
56 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
57 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
60 if g.GasLeft > consensus.MaxGasAmount {
61 g.GasLeft = consensus.MaxGasAmount
64 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
65 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
70 func (g *GasState) setGasValid() error {
72 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
73 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
76 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
77 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
84 func (g *GasState) updateUsage(gasLeft int64) error {
86 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
89 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
93 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
96 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
97 return ErrOverGasCredit
102 // validationState contains the context that must propagate through
103 // the transaction graph when validating entries.
104 type validationState struct {
108 entryID bc.Hash // The ID of the nearest enclosing entry
109 sourcePos uint64 // The source position, for validate ValueSources
110 destPos uint64 // The destination position, for validate ValueDestinations
111 cache map[bc.Hash]error // Memoized per-entry validation results
114 func checkValid(vs *validationState, e bc.Entry) (err error) {
116 entryID := bc.EntryID(e)
117 if err, ok = vs.cache[entryID]; ok {
122 vs.cache[entryID] = err
125 switch e := e.(type) {
127 for i, resID := range e.ResultIds {
128 resultEntry := vs.tx.Entries[*resID]
131 if err = checkValid(&vs2, resultEntry); err != nil {
132 return errors.Wrapf(err, "checking result %d", i)
136 if e.Version == 1 && len(e.ResultIds) == 0 {
137 return ErrEmptyResults
141 parity := make(map[bc.AssetID]int64)
142 for i, src := range e.Sources {
143 _, ok := vs.tx.Entries[*src.Ref]
145 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", *src.Ref)
148 if src.Value.Amount > math.MaxInt64 {
149 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
151 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
153 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])
155 parity[*src.Value.AssetId] = sum
158 for i, dest := range e.WitnessDestinations {
159 sum, ok := parity[*dest.Value.AssetId]
161 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
163 if dest.Value.Amount > math.MaxInt64 {
164 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
166 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
168 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)
170 parity[*dest.Value.AssetId] = diff
173 for assetID, amount := range parity {
174 if assetID == *consensus.BTMAssetID {
175 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
178 } else if amount != 0 {
179 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
183 for _, BTMInputID := range vs.tx.GasInputIDs {
184 e, ok := vs.tx.Entries[BTMInputID]
186 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
189 vs2.entryID = BTMInputID
190 if err := checkValid(&vs2, e); err != nil {
191 return errors.Wrap(err, "checking gas input")
195 for i, dest := range e.WitnessDestinations {
197 vs2.destPos = uint64(i)
198 if err = checkValidDest(&vs2, dest); err != nil {
199 return errors.Wrapf(err, "checking mux destination %d", i)
203 if len(vs.tx.GasInputIDs) > 0 {
204 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)
220 if err = checkValidSrc(&vs2, e.Source); err != nil {
221 return errors.Wrap(err, "checking output source")
227 if err = checkValidSrc(&vs2, e.Source); err != nil {
228 return errors.Wrap(err, "checking retirement source")
232 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
233 if computedAssetID != *e.Value.AssetId {
234 return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
237 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
239 return errors.Wrap(err, "checking issuance program")
241 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
247 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
248 return errors.Wrap(err, "checking issuance destination")
252 if e.SpentOutputId == nil {
253 return errors.Wrap(ErrMissingField, "spend without spent output ID")
255 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
257 return errors.Wrap(err, "getting spend prevout")
259 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
261 return errors.Wrap(err, "checking control program")
263 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
267 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
272 return errors.WithDetailf(
274 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
275 spentOutput.Source.Value.Amount,
276 spentOutput.Source.Value.AssetId.Bytes(),
277 e.WitnessDestination.Value.Amount,
278 e.WitnessDestination.Value.AssetId.Bytes(),
284 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
285 return errors.Wrap(err, "checking spend destination")
289 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
290 return ErrWrongCoinbaseTransaction
293 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
294 return ErrWrongCoinbaseAsset
297 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
298 return ErrCoinbaseArbitraryOversize
303 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
304 return errors.Wrap(err, "checking coinbase destination")
307 // special case for coinbase transaction, it's valid unit all the verify has been passed
308 vs.gasStatus.GasValid = true
311 if e.SpentOutputId == nil {
312 return errors.Wrap(ErrMissingField, "spend without spent output ID")
314 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
316 return errors.Wrap(err, "getting spend prevout")
318 stack := e.GetPeginwitness()
319 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
321 return errors.New("pegin-no-witness")
325 validation := &claim.BytomClaimValidation{}
326 if err := validation.IsValidPeginWitness(stack, *spentOutput); err != nil {
330 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
335 return errors.WithDetailf(
337 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
338 spentOutput.Source.Value.Amount,
339 spentOutput.Source.Value.AssetId.Bytes(),
340 e.WitnessDestination.Value.Amount,
341 e.WitnessDestination.Value.AssetId.Bytes(),
347 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
348 return errors.Wrap(err, "checking spend destination")
350 vs.gasStatus.GasValid = true
352 return fmt.Errorf("entry has unexpected type %T", e)
358 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
360 return errors.Wrap(ErrMissingField, "empty value source")
363 return errors.Wrap(ErrMissingField, "missing ref on value source")
365 if vs.Value == nil || vs.Value.AssetId == nil {
366 return errors.Wrap(ErrMissingField, "missing value on value source")
369 e, ok := vstate.tx.Entries[*vs.Ref]
371 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
375 vstate2.entryID = *vs.Ref
376 if err := checkValid(&vstate2, e); err != nil {
377 return errors.Wrap(err, "checking value source")
380 var dest *bc.ValueDestination
381 switch ref := e.(type) {
383 if vs.Position != 0 {
384 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
386 dest = ref.WitnessDestination
389 if vs.Position != 0 {
390 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
392 dest = ref.WitnessDestination
395 if vs.Position != 0 {
396 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
398 dest = ref.WitnessDestination
401 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
402 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
404 dest = ref.WitnessDestinations[vs.Position]
406 if vs.Position != 0 {
407 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
409 dest = ref.WitnessDestination
411 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
414 if dest.Ref == nil || *dest.Ref != vstate.entryID {
415 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
418 if dest.Position != vstate.sourcePos {
419 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
422 eq, err := dest.Value.Equal(vs.Value)
424 return errors.Sub(ErrMissingField, err)
427 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
433 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
435 return errors.Wrap(ErrMissingField, "empty value destination")
438 return errors.Wrap(ErrMissingField, "missing ref on value destination")
440 if vd.Value == nil || vd.Value.AssetId == nil {
441 return errors.Wrap(ErrMissingField, "missing value on value source")
444 e, ok := vs.tx.Entries[*vd.Ref]
446 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
449 var src *bc.ValueSource
450 switch ref := e.(type) {
452 if vd.Position != 0 {
453 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
458 if vd.Position != 0 {
459 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
464 if vd.Position >= uint64(len(ref.Sources)) {
465 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
467 src = ref.Sources[vd.Position]
470 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
473 if src.Ref == nil || *src.Ref != vs.entryID {
474 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
477 if src.Position != vs.destPos {
478 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
481 eq, err := src.Value.Equal(vd.Value)
483 return errors.Sub(ErrMissingField, err)
486 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
492 func checkStandardTx(tx *bc.Tx) error {
493 for _, id := range tx.GasInputIDs {
494 spend, err := tx.Spend(id)
498 spentOutput, err := tx.Output(*spend.SpentOutputId)
503 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
504 return ErrNotStandardTx
508 for _, id := range tx.ResultIds {
509 e, ok := tx.Entries[*id]
511 return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
514 output, ok := e.(*bc.Output)
515 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
519 if !segwit.IsP2WScript(output.ControlProgram.Code) {
520 return ErrNotStandardTx
526 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
527 if tx.TimeRange == 0 {
531 if tx.TimeRange < block.Height {
532 return ErrBadTimeRange
537 // ValidateTx validates a transaction.
538 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
539 gasStatus := &GasState{GasValid: false}
540 if block.Version == 1 && tx.Version != 1 {
541 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
543 if tx.SerializedSize == 0 {
544 return gasStatus, ErrWrongTransactionSize
546 if err := checkTimeRange(tx, block); err != nil {
547 return gasStatus, err
549 if err := checkStandardTx(tx); err != nil {
550 return gasStatus, err
552 vs := &validationState{
556 gasStatus: gasStatus,
557 cache: make(map[bc.Hash]error),
559 return vs.gasStatus, checkValid(vs, tx.TxHeader)