OSDN Git Service

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