7 "github.com/vapor/consensus"
8 "github.com/vapor/consensus/segwit"
9 "github.com/vapor/errors"
10 "github.com/vapor/math/checked"
11 "github.com/vapor/protocol/bc"
12 "github.com/vapor/protocol/vm"
17 // validate transaction error
19 ErrTxVersion = errors.New("invalid transaction version")
20 ErrWrongTransactionSize = errors.New("invalid transaction size")
21 ErrBadTimeRange = errors.New("invalid transaction time range")
22 ErrEmptyInputIDs = errors.New("got the empty InputIDs")
23 ErrNotStandardTx = errors.New("not standard transaction")
24 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
25 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
26 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
27 ErrEmptyResults = errors.New("transaction has no results")
28 ErrMismatchedAssetID = errors.New("mismatched assetID")
29 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
30 ErrMismatchedReference = errors.New("mismatched reference")
31 ErrMismatchedValue = errors.New("mismatched value")
32 ErrMissingField = errors.New("missing required field")
33 ErrNoSource = errors.New("no source for value")
34 ErrOverflow = errors.New("arithmetic overflow/underflow")
35 ErrPosition = errors.New("invalid source or destination position")
36 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
37 ErrOverGasCredit = errors.New("all gas credit has been spend")
38 ErrGasCalculate = errors.New("gas usage calculate got a math error")
41 // GasState record the gas usage status
42 type GasState struct {
50 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
52 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
55 g.BTMValue = uint64(BTMValue)
58 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
59 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
62 if g.GasLeft > consensus.MaxGasAmount {
63 g.GasLeft = consensus.MaxGasAmount
66 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
67 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
72 func (g *GasState) setGasValid() error {
74 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
75 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
78 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
79 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.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
99 return ErrOverGasCredit
104 // validationState contains the context that must propagate through
105 // the transaction graph when validating entries.
106 type validationState struct {
110 entryID bc.Hash // The ID of the nearest enclosing entry
111 sourcePos uint64 // The source position, for validate ValueSources
112 destPos uint64 // The destination position, for validate ValueDestinations
113 cache map[bc.Hash]error // Memoized per-entry validation results
116 func checkValid(vs *validationState, e bc.Entry) (err error) {
118 entryID := bc.EntryID(e)
119 if err, ok = vs.cache[entryID]; ok {
124 vs.cache[entryID] = err
127 switch e := e.(type) {
129 for i, resID := range e.ResultIds {
130 resultEntry := vs.tx.Entries[*resID]
133 if err = checkValid(&vs2, resultEntry); err != nil {
134 return errors.Wrapf(err, "checking result %d", i)
138 if e.Version == 1 && len(e.ResultIds) == 0 {
139 return ErrEmptyResults
143 parity := make(map[bc.AssetID]int64)
144 for i, src := range e.Sources {
145 if src.Value.Amount > math.MaxInt64 {
146 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
148 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
150 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])
152 parity[*src.Value.AssetId] = sum
155 for i, dest := range e.WitnessDestinations {
156 sum, ok := parity[*dest.Value.AssetId]
158 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
160 if dest.Value.Amount > math.MaxInt64 {
161 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
163 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
165 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)
167 parity[*dest.Value.AssetId] = diff
170 for assetID, amount := range parity {
171 if assetID == *consensus.BTMAssetID {
172 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
175 } else if amount != 0 {
176 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
180 for _, BTMInputID := range vs.tx.GasInputIDs {
181 e, ok := vs.tx.Entries[BTMInputID]
183 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
187 vs2.entryID = BTMInputID
188 if err := checkValid(&vs2, e); err != nil {
189 return errors.Wrap(err, "checking gas input")
193 for i, dest := range e.WitnessDestinations {
195 vs2.destPos = uint64(i)
196 if err = checkValidDest(&vs2, dest); err != nil {
197 return errors.Wrapf(err, "checking mux destination %d", i)
201 if err := vs.gasStatus.setGasValid(); err != nil {
205 for i, src := range e.Sources {
207 vs2.sourcePos = uint64(i)
208 if err = checkValidSrc(&vs2, src); err != nil {
209 return errors.Wrapf(err, "checking mux source %d", i)
216 if err = checkValidSrc(&vs2, e.Source); err != nil {
217 return errors.Wrap(err, "checking output source")
223 if err = checkValidSrc(&vs2, e.Source); err != nil {
224 return errors.Wrap(err, "checking retirement source")
228 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
229 if computedAssetID != *e.Value.AssetId {
230 return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
233 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
235 return errors.Wrap(err, "checking issuance program")
237 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
243 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
244 return errors.Wrap(err, "checking issuance destination")
248 if e.SpentOutputId == nil {
249 return errors.Wrap(ErrMissingField, "spend without spent output ID")
251 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
253 return errors.Wrap(err, "getting spend prevout")
256 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
258 return errors.Wrap(err, "checking control program")
260 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
264 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
269 return errors.WithDetailf(
271 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
272 spentOutput.Source.Value.Amount,
273 spentOutput.Source.Value.AssetId.Bytes(),
274 e.WitnessDestination.Value.Amount,
275 e.WitnessDestination.Value.AssetId.Bytes(),
281 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
282 return errors.Wrap(err, "checking spend destination")
286 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
287 return ErrWrongCoinbaseTransaction
290 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
291 return ErrWrongCoinbaseAsset
294 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
295 return ErrCoinbaseArbitraryOversize
300 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
301 return errors.Wrap(err, "checking coinbase destination")
303 vs.gasStatus.StorageGas = 0
306 return fmt.Errorf("entry has unexpected type %T", e)
312 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
314 return errors.Wrap(ErrMissingField, "empty value source")
317 return errors.Wrap(ErrMissingField, "missing ref on value source")
319 if vs.Value == nil || vs.Value.AssetId == nil {
320 return errors.Wrap(ErrMissingField, "missing value on value source")
323 e, ok := vstate.tx.Entries[*vs.Ref]
325 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
329 vstate2.entryID = *vs.Ref
330 if err := checkValid(&vstate2, e); err != nil {
331 return errors.Wrap(err, "checking value source")
334 var dest *bc.ValueDestination
335 switch ref := e.(type) {
337 if vs.Position != 0 {
338 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
340 dest = ref.WitnessDestination
343 if vs.Position != 0 {
344 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
346 dest = ref.WitnessDestination
349 if vs.Position != 0 {
350 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
352 dest = ref.WitnessDestination
355 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
356 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
358 dest = ref.WitnessDestinations[vs.Position]
361 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
364 if dest.Ref == nil || *dest.Ref != vstate.entryID {
365 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
368 if dest.Position != vstate.sourcePos {
369 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
372 eq, err := dest.Value.Equal(vs.Value)
374 return errors.Sub(ErrMissingField, err)
377 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
383 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
385 return errors.Wrap(ErrMissingField, "empty value destination")
388 return errors.Wrap(ErrMissingField, "missing ref on value destination")
390 if vd.Value == nil || vd.Value.AssetId == nil {
391 return errors.Wrap(ErrMissingField, "missing value on value destination")
394 e, ok := vs.tx.Entries[*vd.Ref]
396 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
399 var src *bc.ValueSource
400 switch ref := e.(type) {
402 if vd.Position != 0 {
403 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
408 if vd.Position != 0 {
409 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
414 if vd.Position >= uint64(len(ref.Sources)) {
415 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
417 src = ref.Sources[vd.Position]
420 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
423 if src.Ref == nil || *src.Ref != vs.entryID {
424 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
427 if src.Position != vs.destPos {
428 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
431 eq, err := src.Value.Equal(vd.Value)
433 return errors.Sub(ErrMissingField, err)
436 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
442 func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
443 for _, id := range tx.InputIDs {
444 if blockHeight >= ruleAA && id.IsZero() {
445 return ErrEmptyInputIDs
449 for _, id := range tx.GasInputIDs {
450 spend, err := tx.Spend(id)
454 spentOutput, err := tx.Output(*spend.SpentOutputId)
459 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
460 return ErrNotStandardTx
464 for _, id := range tx.ResultIds {
465 e, ok := tx.Entries[*id]
467 return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
470 output, ok := e.(*bc.Output)
471 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
475 if !segwit.IsP2WScript(output.ControlProgram.Code) {
476 return ErrNotStandardTx
482 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
483 if tx.TimeRange == 0 {
487 if tx.TimeRange < block.Height {
488 return ErrBadTimeRange
493 // ValidateTx validates a transaction.
494 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
495 gasStatus := &GasState{GasValid: false}
496 if block.Version == 1 && tx.Version != 1 {
497 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
499 if tx.SerializedSize == 0 {
500 return gasStatus, ErrWrongTransactionSize
502 if err := checkTimeRange(tx, block); err != nil {
503 return gasStatus, err
505 if err := checkStandardTx(tx, block.Height); err != nil {
506 return gasStatus, err
509 vs := &validationState{
513 gasStatus: gasStatus,
514 cache: make(map[bc.Hash]error),
516 return vs.gasStatus, checkValid(vs, tx.TxHeader)