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")
44 // GasState record the gas usage status
45 type GasState struct {
53 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
55 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
58 g.BTMValue = uint64(BTMValue)
61 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
62 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
65 if g.GasLeft > consensus.MaxGasAmount {
66 g.GasLeft = consensus.MaxGasAmount
69 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
70 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
75 func (g *GasState) setGasValid() error {
77 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
78 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
81 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
82 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
89 func (g *GasState) updateUsage(gasLeft int64) error {
91 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
94 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
98 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
101 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
102 return ErrOverGasCredit
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
119 func checkValid(vs *validationState, e bc.Entry) (err error) {
121 entryID := bc.EntryID(e)
122 if err, ok = vs.cache[entryID]; ok {
127 vs.cache[entryID] = err
130 switch e := e.(type) {
132 for i, resID := range e.ResultIds {
133 resultEntry := vs.tx.Entries[*resID]
136 if err = checkValid(&vs2, resultEntry); err != nil {
137 return errors.Wrapf(err, "checking result %d", i)
141 if e.Version == 1 && len(e.ResultIds) == 0 {
142 return ErrEmptyResults
146 parity := make(map[bc.AssetID]int64)
147 for i, src := range e.Sources {
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)
190 vs2.entryID = BTMInputID
191 if err := checkValid(&vs2, e); err != nil {
192 return errors.Wrap(err, "checking gas input")
196 for i, dest := range e.WitnessDestinations {
198 vs2.destPos = uint64(i)
199 if err = checkValidDest(&vs2, dest); err != nil {
200 return errors.Wrapf(err, "checking mux destination %d", i)
204 if err := vs.gasStatus.setGasValid(); err != nil {
208 for i, src := range e.Sources {
210 vs2.sourcePos = uint64(i)
211 if err = checkValidSrc(&vs2, src); err != nil {
212 return errors.Wrapf(err, "checking mux source %d", i)
216 case *bc.IntraChainOutput:
219 if err = checkValidSrc(&vs2, e.Source); err != nil {
220 return errors.Wrap(err, "checking output source")
223 case *bc.CrossChainOutput:
226 if err = checkValidSrc(&vs2, e.Source); err != nil {
227 return errors.Wrap(err, "checking output source")
231 if len(e.Vote) != 64 {
236 if err = checkValidSrc(&vs2, e.Source); err != nil {
237 return errors.Wrap(err, "checking vote output source")
243 if err = checkValidSrc(&vs2, e.Source); err != nil {
244 return errors.Wrap(err, "checking retirement source")
247 case *bc.CrossChainInput:
248 _, err := vm.Verify(NewTxVMContext(vs, e, e.ControlProgram, e.WitnessArguments), consensus.DefaultGasCredit)
250 return errors.Wrap(err, "checking cross-chain input control program")
255 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
256 return errors.Wrap(err, "checking cross-chain input destination")
260 if e.SpentOutputId == nil {
261 return errors.Wrap(ErrMissingField, "spend without spent output ID")
264 controlProgram *bc.Program
265 value *bc.AssetAmount
267 entryOutput, err := vs.tx.Entry(*e.SpentOutputId)
269 return errors.Wrap(err, "getting spend prevout")
272 switch output := entryOutput.(type) {
273 case *bc.IntraChainOutput:
274 controlProgram = output.ControlProgram
275 value = output.Source.Value
277 if len(output.Vote) != 64 {
280 controlProgram = output.ControlProgram
281 value = output.Source.Value
283 return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", e.SpentOutputId.Bytes(), entryOutput)
286 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, controlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
288 return errors.Wrap(err, "checking control program")
290 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
294 eq, err := value.Equal(e.WitnessDestination.Value)
299 return errors.WithDetailf(
301 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
303 value.AssetId.Bytes(),
304 e.WitnessDestination.Value.Amount,
305 e.WitnessDestination.Value.AssetId.Bytes(),
310 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
311 return errors.Wrap(err, "checking spend destination")
315 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
316 return ErrWrongCoinbaseTransaction
319 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
320 return ErrWrongCoinbaseAsset
323 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
324 return ErrCoinbaseArbitraryOversize
329 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
330 return errors.Wrap(err, "checking coinbase destination")
332 vs.gasStatus.StorageGas = 0
335 return fmt.Errorf("entry has unexpected type %T", e)
341 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
343 return errors.Wrap(ErrMissingField, "empty value source")
346 return errors.Wrap(ErrMissingField, "missing ref on value source")
348 if vs.Value == nil || vs.Value.AssetId == nil {
349 return errors.Wrap(ErrMissingField, "missing value on value source")
352 e, ok := vstate.tx.Entries[*vs.Ref]
354 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
358 vstate2.entryID = *vs.Ref
359 if err := checkValid(&vstate2, e); err != nil {
360 return errors.Wrap(err, "checking value source")
363 var dest *bc.ValueDestination
364 switch ref := e.(type) {
366 if vs.Position != 0 {
367 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
369 dest = ref.WitnessDestination
371 case *bc.CrossChainInput:
372 if vs.Position != 0 {
373 return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
375 dest = ref.WitnessDestination
378 if vs.Position != 0 {
379 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
381 dest = ref.WitnessDestination
384 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
385 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
387 dest = ref.WitnessDestinations[vs.Position]
390 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
393 if dest.Ref == nil || *dest.Ref != vstate.entryID {
394 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
397 if dest.Position != vstate.sourcePos {
398 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
401 eq, err := dest.Value.Equal(vs.Value)
403 return errors.Sub(ErrMissingField, err)
406 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
412 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
414 return errors.Wrap(ErrMissingField, "empty value destination")
417 return errors.Wrap(ErrMissingField, "missing ref on value destination")
419 if vd.Value == nil || vd.Value.AssetId == nil {
420 return errors.Wrap(ErrMissingField, "missing value on value destination")
423 e, ok := vs.tx.Entries[*vd.Ref]
425 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
428 var src *bc.ValueSource
429 switch ref := e.(type) {
430 case *bc.IntraChainOutput:
431 if vd.Position != 0 {
432 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
436 case *bc.CrossChainOutput:
437 if vd.Position != 0 {
438 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
443 if vd.Position != 0 {
444 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
449 if vd.Position != 0 {
450 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
455 if vd.Position >= uint64(len(ref.Sources)) {
456 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
458 src = ref.Sources[vd.Position]
461 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
464 if src.Ref == nil || *src.Ref != vs.entryID {
465 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
468 if src.Position != vs.destPos {
469 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
472 eq, err := src.Value.Equal(vd.Value)
474 return errors.Sub(ErrMissingField, err)
477 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
483 func checkFedaration(tx *bc.Tx) error {
484 for _, id := range tx.InputIDs {
485 switch inp := tx.Entries[id].(type) {
486 case *bc.CrossChainInput:
487 fedProg := config.FederationProgrom(config.CommonConfig)
488 if !bytes.Equal(inp.ControlProgram.Code, fedProg) {
489 return errors.New("The federal controlProgram is incorrect")
498 func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
499 for _, id := range tx.InputIDs {
500 if blockHeight >= ruleAA && id.IsZero() {
501 return ErrEmptyInputIDs
505 if err := checkFedaration(tx); err != nil {
509 for _, id := range tx.GasInputIDs {
510 spend, err := tx.Spend(id)
516 outputEntry, err := tx.Entry(*spend.SpentOutputId)
520 switch output := outputEntry.(type) {
521 case *bc.IntraChainOutput:
522 code = output.ControlProgram.Code
524 code = output.ControlProgram.Code
526 return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", id.Bytes(), outputEntry)
529 if !segwit.IsP2WScript(code) {
530 return ErrNotStandardTx
536 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
537 if tx.TimeRange == 0 {
541 if tx.TimeRange < block.Height {
542 return ErrBadTimeRange
548 // ValidateTx validates a transaction.
549 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
550 gasStatus := &GasState{GasValid: false}
551 if block.Version == 1 && tx.Version != 1 {
552 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
554 if tx.SerializedSize == 0 {
555 return gasStatus, ErrWrongTransactionSize
557 if err := checkTimeRange(tx, block); err != nil {
558 return gasStatus, err
560 if err := checkStandardTx(tx, block.Height); err != nil {
561 return gasStatus, err
564 vs := &validationState{
568 gasStatus: gasStatus,
569 cache: make(map[bc.Hash]error),
571 return vs.gasStatus, checkValid(vs, tx.TxHeader)