OSDN Git Service

65f4815f5263fa0d1cebc2690419a9806685aa8a
[bytom/vapor.git] / protocol / validation / tx.go
1 package validation
2
3 import (
4         "fmt"
5         "math"
6
7         "github.com/vapor/config"
8         "github.com/vapor/consensus"
9         "github.com/vapor/errors"
10         "github.com/vapor/math/checked"
11         "github.com/vapor/protocol/bc"
12         "github.com/vapor/protocol/vm"
13 )
14
15 const ruleAA = 142500
16
17 // validate transaction error
18 var (
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")
39         ErrVotePubKey                = errors.New("invalid public key of vote")
40         ErrVoteOutputAmount          = errors.New("invalid vote amount")
41 )
42
43 // GasState record the gas usage status
44 type GasState struct {
45         BTMValue   uint64
46         GasLeft    int64
47         GasUsed    int64
48         GasValid   bool
49         StorageGas int64
50 }
51
52 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
53         if BTMValue < 0 {
54                 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
55         }
56
57         g.BTMValue = uint64(BTMValue)
58
59         var ok bool
60         if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
61                 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
62         }
63
64         if g.GasLeft > consensus.MaxGasAmount {
65                 g.GasLeft = consensus.MaxGasAmount
66         }
67
68         if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
69                 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
70         }
71         return nil
72 }
73
74 func (g *GasState) setGasValid() error {
75         var ok bool
76         if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
77                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
78         }
79
80         if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
81                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
82         }
83
84         g.GasValid = true
85         return nil
86 }
87
88 func (g *GasState) updateUsage(gasLeft int64) error {
89         if gasLeft < 0 {
90                 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
91         }
92
93         if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
94                 g.GasUsed += gasUsed
95                 g.GasLeft = gasLeft
96         } else {
97                 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
98         }
99
100         if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
101                 return ErrOverGasCredit
102         }
103         return nil
104 }
105
106 // validationState contains the context that must propagate through
107 // the transaction graph when validating entries.
108 type validationState struct {
109         block     *bc.Block
110         tx        *bc.Tx
111         gasStatus *GasState
112         entryID   bc.Hash           // The ID of the nearest enclosing entry
113         sourcePos uint64            // The source position, for validate ValueSources
114         destPos   uint64            // The destination position, for validate ValueDestinations
115         cache     map[bc.Hash]error // Memoized per-entry validation results
116 }
117
118 func checkValid(vs *validationState, e bc.Entry) (err error) {
119         var ok bool
120         entryID := bc.EntryID(e)
121         if err, ok = vs.cache[entryID]; ok {
122                 return err
123         }
124
125         defer func() {
126                 vs.cache[entryID] = err
127         }()
128
129         switch e := e.(type) {
130         case *bc.TxHeader:
131                 for i, resID := range e.ResultIds {
132                         resultEntry := vs.tx.Entries[*resID]
133                         vs2 := *vs
134                         vs2.entryID = *resID
135                         if err = checkValid(&vs2, resultEntry); err != nil {
136                                 return errors.Wrapf(err, "checking result %d", i)
137                         }
138                 }
139
140                 if e.Version == 1 && len(e.ResultIds) == 0 {
141                         return ErrEmptyResults
142                 }
143
144         case *bc.Mux:
145                 parity := make(map[bc.AssetID]int64)
146                 for i, src := range e.Sources {
147                         if src.Value.Amount > math.MaxInt64 {
148                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
149                         }
150                         sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
151                         if !ok {
152                                 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])
153                         }
154                         parity[*src.Value.AssetId] = sum
155                 }
156
157                 for i, dest := range e.WitnessDestinations {
158                         sum, ok := parity[*dest.Value.AssetId]
159                         if !ok {
160                                 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
161                         }
162                         if dest.Value.Amount > math.MaxInt64 {
163                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
164                         }
165                         diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
166                         if !ok {
167                                 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)
168                         }
169                         parity[*dest.Value.AssetId] = diff
170                 }
171
172                 for assetID, amount := range parity {
173                         if assetID == *consensus.BTMAssetID {
174                                 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
175                                         return err
176                                 }
177                         } else if amount != 0 {
178                                 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
179                         }
180                 }
181
182                 for _, BTMInputID := range vs.tx.GasInputIDs {
183                         e, ok := vs.tx.Entries[BTMInputID]
184                         if !ok {
185                                 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
186                         }
187
188                         vs2 := *vs
189                         vs2.entryID = BTMInputID
190                         if err := checkValid(&vs2, e); err != nil {
191                                 return errors.Wrap(err, "checking gas input")
192                         }
193                 }
194
195                 for i, dest := range e.WitnessDestinations {
196                         vs2 := *vs
197                         vs2.destPos = uint64(i)
198                         if err = checkValidDest(&vs2, dest); err != nil {
199                                 return errors.Wrapf(err, "checking mux destination %d", i)
200                         }
201                 }
202
203                 if err := vs.gasStatus.setGasValid(); err != nil {
204                         return err
205                 }
206
207                 for i, src := range e.Sources {
208                         vs2 := *vs
209                         vs2.sourcePos = uint64(i)
210                         if err = checkValidSrc(&vs2, src); err != nil {
211                                 return errors.Wrapf(err, "checking mux source %d", i)
212                         }
213                 }
214
215         case *bc.IntraChainOutput:
216                 vs2 := *vs
217                 vs2.sourcePos = 0
218                 if err = checkValidSrc(&vs2, e.Source); err != nil {
219                         return errors.Wrap(err, "checking output source")
220                 }
221
222         case *bc.CrossChainOutput:
223                 vs2 := *vs
224                 vs2.sourcePos = 0
225                 if err = checkValidSrc(&vs2, e.Source); err != nil {
226                         return errors.Wrap(err, "checking output source")
227                 }
228
229         case *bc.VoteOutput:
230                 if len(e.Vote) != 64 {
231                         return ErrVotePubKey
232                 }
233                 vs2 := *vs
234                 vs2.sourcePos = 0
235                 if err = checkValidSrc(&vs2, e.Source); err != nil {
236                         return errors.Wrap(err, "checking vote output source")
237                 }
238                 if e.Source.Value.Amount < consensus.MinVoteOutputAmount {
239                         return ErrVoteOutputAmount
240                 }
241
242         case *bc.Retirement:
243                 vs2 := *vs
244                 vs2.sourcePos = 0
245                 if err = checkValidSrc(&vs2, e.Source); err != nil {
246                         return errors.Wrap(err, "checking retirement source")
247                 }
248
249         case *bc.CrossChainInput:
250                 // check assetID
251                 assetID := e.AssetDefinition.ComputeAssetID()
252                 if *e.Value.AssetId != *consensus.BTMAssetID && *e.Value.AssetId != assetID {
253                         return errors.New("incorrect asset_id while check CrossChainInput")
254                 }
255                 code := config.FederationProgrom(config.CommonConfig)
256                 prog := &bc.Program{
257                         VmVersion: e.ControlProgram.VmVersion,
258                         Code:      code,
259                 }
260                 _, err := vm.Verify(NewTxVMContext(vs, e, prog, e.WitnessArguments), consensus.DefaultGasCredit)
261                 if err != nil {
262                         return errors.Wrap(err, "checking cross-chain input control program")
263                 }
264
265                 vs2 := *vs
266                 vs2.destPos = 0
267                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
268                         return errors.Wrap(err, "checking cross-chain input destination")
269                 }
270                 vs.gasStatus.StorageGas = 0
271
272         case *bc.Spend:
273                 if e.SpentOutputId == nil {
274                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
275                 }
276
277                 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
278                 if err != nil {
279                         return errors.Wrap(err, "getting spend prevout")
280                 }
281
282                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
283                 if err != nil {
284                         return errors.Wrap(err, "checking control program")
285                 }
286                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
287                         return err
288                 }
289
290                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
291                 if err != nil {
292                         return err
293                 }
294                 if !eq {
295                         return errors.WithDetailf(
296                                 ErrMismatchedValue,
297                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
298                                 spentOutput.Source.Value.Amount,
299                                 spentOutput.Source.Value.AssetId.Bytes(),
300                                 e.WitnessDestination.Value.Amount,
301                                 e.WitnessDestination.Value.AssetId.Bytes(),
302                         )
303                 }
304                 vs2 := *vs
305                 vs2.destPos = 0
306                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
307                         return errors.Wrap(err, "checking spend destination")
308                 }
309
310         case *bc.VetoInput:
311                 if e.SpentOutputId == nil {
312                         return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
313                 }
314
315                 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
316                 if err != nil {
317                         return errors.Wrap(err, "getting vetoInput prevout")
318                 }
319                 if len(voteOutput.Vote) != 64 {
320                         return ErrVotePubKey
321                 }
322
323                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
324                 if err != nil {
325                         return errors.Wrap(err, "checking control program")
326                 }
327                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
328                         return err
329                 }
330
331                 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
332                 if err != nil {
333                         return err
334                 }
335                 if !eq {
336                         return errors.WithDetailf(
337                                 ErrMismatchedValue,
338                                 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
339                                 voteOutput.Source.Value.Amount,
340                                 voteOutput.Source.Value.AssetId.Bytes(),
341                                 e.WitnessDestination.Value.Amount,
342                                 e.WitnessDestination.Value.AssetId.Bytes(),
343                         )
344                 }
345                 vs2 := *vs
346                 vs2.destPos = 0
347                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
348                         return errors.Wrap(err, "checking vetoInput destination")
349                 }
350
351         case *bc.Coinbase:
352                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
353                         return ErrWrongCoinbaseTransaction
354                 }
355
356                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
357                         return ErrWrongCoinbaseAsset
358                 }
359
360                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
361                         return ErrCoinbaseArbitraryOversize
362                 }
363
364                 vs2 := *vs
365                 vs2.destPos = 0
366                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
367                         return errors.Wrap(err, "checking coinbase destination")
368                 }
369                 vs.gasStatus.StorageGas = 0
370
371         default:
372                 return fmt.Errorf("entry has unexpected type %T", e)
373         }
374
375         return nil
376 }
377
378 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
379         if vs == nil {
380                 return errors.Wrap(ErrMissingField, "empty value source")
381         }
382         if vs.Ref == nil {
383                 return errors.Wrap(ErrMissingField, "missing ref on value source")
384         }
385         if vs.Value == nil || vs.Value.AssetId == nil {
386                 return errors.Wrap(ErrMissingField, "missing value on value source")
387         }
388
389         e, ok := vstate.tx.Entries[*vs.Ref]
390         if !ok {
391                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
392         }
393
394         vstate2 := *vstate
395         vstate2.entryID = *vs.Ref
396         if err := checkValid(&vstate2, e); err != nil {
397                 return errors.Wrap(err, "checking value source")
398         }
399
400         var dest *bc.ValueDestination
401         switch ref := e.(type) {
402         case *bc.VetoInput:
403                 if vs.Position != 0 {
404                         return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
405                 }
406                 dest = ref.WitnessDestination
407
408         case *bc.Coinbase:
409                 if vs.Position != 0 {
410                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
411                 }
412                 dest = ref.WitnessDestination
413
414         case *bc.CrossChainInput:
415                 if vs.Position != 0 {
416                         return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
417                 }
418                 dest = ref.WitnessDestination
419
420         case *bc.Spend:
421                 if vs.Position != 0 {
422                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
423                 }
424                 dest = ref.WitnessDestination
425
426         case *bc.Mux:
427                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
428                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
429                 }
430                 dest = ref.WitnessDestinations[vs.Position]
431
432         default:
433                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
434         }
435
436         if dest.Ref == nil || *dest.Ref != vstate.entryID {
437                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
438         }
439
440         if dest.Position != vstate.sourcePos {
441                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
442         }
443
444         eq, err := dest.Value.Equal(vs.Value)
445         if err != nil {
446                 return errors.Sub(ErrMissingField, err)
447         }
448         if !eq {
449                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
450         }
451
452         return nil
453 }
454
455 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
456         if vd == nil {
457                 return errors.Wrap(ErrMissingField, "empty value destination")
458         }
459         if vd.Ref == nil {
460                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
461         }
462         if vd.Value == nil || vd.Value.AssetId == nil {
463                 return errors.Wrap(ErrMissingField, "missing value on value destination")
464         }
465
466         e, ok := vs.tx.Entries[*vd.Ref]
467         if !ok {
468                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
469         }
470
471         var src *bc.ValueSource
472         switch ref := e.(type) {
473         case *bc.IntraChainOutput:
474                 if vd.Position != 0 {
475                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
476                 }
477                 src = ref.Source
478
479         case *bc.CrossChainOutput:
480                 if vd.Position != 0 {
481                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
482                 }
483                 src = ref.Source
484
485         case *bc.VoteOutput:
486                 if vd.Position != 0 {
487                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
488                 }
489                 src = ref.Source
490
491         case *bc.Retirement:
492                 if vd.Position != 0 {
493                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
494                 }
495                 src = ref.Source
496
497         case *bc.Mux:
498                 if vd.Position >= uint64(len(ref.Sources)) {
499                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
500                 }
501                 src = ref.Sources[vd.Position]
502
503         default:
504                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
505         }
506
507         if src.Ref == nil || *src.Ref != vs.entryID {
508                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
509         }
510
511         if src.Position != vs.destPos {
512                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
513         }
514
515         eq, err := src.Value.Equal(vd.Value)
516         if err != nil {
517                 return errors.Sub(ErrMissingField, err)
518         }
519         if !eq {
520                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
521         }
522
523         return nil
524 }
525
526 func checkInputID(tx *bc.Tx, blockHeight uint64) error {
527         for _, id := range tx.InputIDs {
528                 if blockHeight >= ruleAA && id.IsZero() {
529                         return ErrEmptyInputIDs
530                 }
531         }
532         return nil
533 }
534
535 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
536         if tx.TimeRange == 0 {
537                 return nil
538         }
539
540         if tx.TimeRange < block.Height {
541                 return ErrBadTimeRange
542         }
543
544         return nil
545 }
546
547 // ValidateTx validates a transaction.
548 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
549         gasStatus := &GasState{GasValid: false}
550         if block.Version == 1 && tx.Version != 1 {
551                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
552         }
553         if tx.SerializedSize == 0 {
554                 return gasStatus, ErrWrongTransactionSize
555         }
556         if err := checkTimeRange(tx, block); err != nil {
557                 return gasStatus, err
558         }
559         if err := checkInputID(tx, block.Height); err != nil {
560                 return gasStatus, err
561         }
562
563         vs := &validationState{
564                 block:     block,
565                 tx:        tx,
566                 entryID:   tx.ID,
567                 gasStatus: gasStatus,
568                 cache:     make(map[bc.Hash]error),
569         }
570         return vs.gasStatus, checkValid(vs, tx.TxHeader)
571 }