OSDN Git Service

module claim
[bytom/vapor.git] / protocol / validation / tx.go
1 package validation
2
3 import (
4         "fmt"
5         "math"
6
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"
14 )
15
16 // validate transaction error
17 var (
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")
37 )
38
39 // GasState record the gas usage status
40 type GasState struct {
41         BTMValue   uint64
42         GasLeft    int64
43         GasUsed    int64
44         GasValid   bool
45         StorageGas int64
46 }
47
48 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
49         if BTMValue < 0 {
50                 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
51         }
52
53         g.BTMValue = uint64(BTMValue)
54
55         var ok bool
56         if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
57                 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
58         }
59
60         if g.GasLeft > consensus.MaxGasAmount {
61                 g.GasLeft = consensus.MaxGasAmount
62         }
63
64         if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
65                 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
66         }
67         return nil
68 }
69
70 func (g *GasState) setGasValid() error {
71         var ok bool
72         if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
73                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
74         }
75
76         if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
77                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
78         }
79
80         g.GasValid = true
81         return nil
82 }
83
84 func (g *GasState) updateUsage(gasLeft int64) error {
85         if gasLeft < 0 {
86                 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
87         }
88
89         if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
90                 g.GasUsed += gasUsed
91                 g.GasLeft = gasLeft
92         } else {
93                 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
94         }
95
96         if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
97                 return ErrOverGasCredit
98         }
99         return nil
100 }
101
102 // validationState contains the context that must propagate through
103 // the transaction graph when validating entries.
104 type validationState struct {
105         block     *bc.Block
106         tx        *bc.Tx
107         gasStatus *GasState
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
112 }
113
114 func checkValid(vs *validationState, e bc.Entry) (err error) {
115         var ok bool
116         entryID := bc.EntryID(e)
117         if err, ok = vs.cache[entryID]; ok {
118                 return err
119         }
120
121         defer func() {
122                 vs.cache[entryID] = err
123         }()
124
125         switch e := e.(type) {
126         case *bc.TxHeader:
127                 for i, resID := range e.ResultIds {
128                         resultEntry := vs.tx.Entries[*resID]
129                         vs2 := *vs
130                         vs2.entryID = *resID
131                         if err = checkValid(&vs2, resultEntry); err != nil {
132                                 return errors.Wrapf(err, "checking result %d", i)
133                         }
134                 }
135
136                 if e.Version == 1 && len(e.ResultIds) == 0 {
137                         return ErrEmptyResults
138                 }
139
140         case *bc.Mux:
141                 parity := make(map[bc.AssetID]int64)
142                 for i, src := range e.Sources {
143                         _, ok := vs.tx.Entries[*src.Ref]
144                         if !ok {
145                                 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", *src.Ref)
146                         }
147
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                         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 len(vs.tx.GasInputIDs) > 0 {
204                         if err := vs.gasStatus.setGasValid(); err != nil {
205                                 return err
206                         }
207                 }
208
209                 for i, src := range e.Sources {
210                         vs2 := *vs
211                         vs2.sourcePos = uint64(i)
212                         if err = checkValidSrc(&vs2, src); err != nil {
213                                 return errors.Wrapf(err, "checking mux source %d", i)
214                         }
215                 }
216
217         case *bc.Output:
218                 vs2 := *vs
219                 vs2.sourcePos = 0
220                 if err = checkValidSrc(&vs2, e.Source); err != nil {
221                         return errors.Wrap(err, "checking output source")
222                 }
223
224         case *bc.Retirement:
225                 vs2 := *vs
226                 vs2.sourcePos = 0
227                 if err = checkValidSrc(&vs2, e.Source); err != nil {
228                         return errors.Wrap(err, "checking retirement source")
229                 }
230
231         case *bc.Issuance:
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())
235                 }
236
237                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
238                 if err != nil {
239                         return errors.Wrap(err, "checking issuance program")
240                 }
241                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
242                         return err
243                 }
244
245                 destVS := *vs
246                 destVS.destPos = 0
247                 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
248                         return errors.Wrap(err, "checking issuance destination")
249                 }
250
251         case *bc.Spend:
252                 if e.SpentOutputId == nil {
253                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
254                 }
255                 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
256                 if err != nil {
257                         return errors.Wrap(err, "getting spend prevout")
258                 }
259                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
260                 if err != nil {
261                         return errors.Wrap(err, "checking control program")
262                 }
263                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
264                         return err
265                 }
266
267                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
268                 if err != nil {
269                         return err
270                 }
271                 if !eq {
272                         return errors.WithDetailf(
273                                 ErrMismatchedValue,
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(),
279                         )
280                 }
281
282                 vs2 := *vs
283                 vs2.destPos = 0
284                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
285                         return errors.Wrap(err, "checking spend destination")
286                 }
287
288         case *bc.Coinbase:
289                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
290                         return ErrWrongCoinbaseTransaction
291                 }
292
293                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
294                         return ErrWrongCoinbaseAsset
295                 }
296
297                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
298                         return ErrCoinbaseArbitraryOversize
299                 }
300
301                 vs2 := *vs
302                 vs2.destPos = 0
303                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
304                         return errors.Wrap(err, "checking coinbase destination")
305                 }
306
307                 // special case for coinbase transaction, it's valid unit all the verify has been passed
308                 vs.gasStatus.GasValid = true
309         case *bc.Claim:
310                 // 对交易的合法性进行验证
311                 if e.SpentOutputId == nil {
312                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
313                 }
314                 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
315                 if err != nil {
316                         return errors.Wrap(err, "getting spend prevout")
317                 }
318                 stack := e.GetPeginwitness()
319                 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
320
321                         return errors.New("pegin-no-witness")
322                 }
323
324                 // 根据claim链类型选择验证类型
325                 validation := &claim.BytomClaimValidation{}
326                 if err := validation.IsValidPeginWitness(stack, *spentOutput); err != nil {
327                         return err
328                 }
329
330                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
331                 if err != nil {
332                         return err
333                 }
334                 if !eq {
335                         return errors.WithDetailf(
336                                 ErrMismatchedValue,
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(),
342                         )
343                 }
344
345                 vs2 := *vs
346                 vs2.destPos = 0
347                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
348                         return errors.Wrap(err, "checking spend destination")
349                 }
350                 vs.gasStatus.GasValid = true
351         default:
352                 return fmt.Errorf("entry has unexpected type %T", e)
353         }
354
355         return nil
356 }
357
358 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
359         if vs == nil {
360                 return errors.Wrap(ErrMissingField, "empty value source")
361         }
362         if vs.Ref == nil {
363                 return errors.Wrap(ErrMissingField, "missing ref on value source")
364         }
365         if vs.Value == nil || vs.Value.AssetId == nil {
366                 return errors.Wrap(ErrMissingField, "missing value on value source")
367         }
368
369         e, ok := vstate.tx.Entries[*vs.Ref]
370         if !ok {
371                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
372         }
373
374         vstate2 := *vstate
375         vstate2.entryID = *vs.Ref
376         if err := checkValid(&vstate2, e); err != nil {
377                 return errors.Wrap(err, "checking value source")
378         }
379
380         var dest *bc.ValueDestination
381         switch ref := e.(type) {
382         case *bc.Coinbase:
383                 if vs.Position != 0 {
384                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
385                 }
386                 dest = ref.WitnessDestination
387
388         case *bc.Issuance:
389                 if vs.Position != 0 {
390                         return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
391                 }
392                 dest = ref.WitnessDestination
393
394         case *bc.Spend:
395                 if vs.Position != 0 {
396                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
397                 }
398                 dest = ref.WitnessDestination
399
400         case *bc.Mux:
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))
403                 }
404                 dest = ref.WitnessDestinations[vs.Position]
405         case *bc.Claim:
406                 if vs.Position != 0 {
407                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
408                 }
409                 dest = ref.WitnessDestination
410         default:
411                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
412         }
413
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())
416         }
417
418         if dest.Position != vstate.sourcePos {
419                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
420         }
421
422         eq, err := dest.Value.Equal(vs.Value)
423         if err != nil {
424                 return errors.Sub(ErrMissingField, err)
425         }
426         if !eq {
427                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
428         }
429
430         return nil
431 }
432
433 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
434         if vd == nil {
435                 return errors.Wrap(ErrMissingField, "empty value destination")
436         }
437         if vd.Ref == nil {
438                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
439         }
440         if vd.Value == nil || vd.Value.AssetId == nil {
441                 return errors.Wrap(ErrMissingField, "missing value on value source")
442         }
443
444         e, ok := vs.tx.Entries[*vd.Ref]
445         if !ok {
446                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
447         }
448
449         var src *bc.ValueSource
450         switch ref := e.(type) {
451         case *bc.Output:
452                 if vd.Position != 0 {
453                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
454                 }
455                 src = ref.Source
456
457         case *bc.Retirement:
458                 if vd.Position != 0 {
459                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
460                 }
461                 src = ref.Source
462
463         case *bc.Mux:
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))
466                 }
467                 src = ref.Sources[vd.Position]
468
469         default:
470                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
471         }
472
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())
475         }
476
477         if src.Position != vs.destPos {
478                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
479         }
480
481         eq, err := src.Value.Equal(vd.Value)
482         if err != nil {
483                 return errors.Sub(ErrMissingField, err)
484         }
485         if !eq {
486                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
487         }
488
489         return nil
490 }
491
492 func checkStandardTx(tx *bc.Tx) error {
493         for _, id := range tx.GasInputIDs {
494                 spend, err := tx.Spend(id)
495                 if err != nil {
496                         return err
497                 }
498                 spentOutput, err := tx.Output(*spend.SpentOutputId)
499                 if err != nil {
500                         return err
501                 }
502
503                 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
504                         return ErrNotStandardTx
505                 }
506         }
507
508         for _, id := range tx.ResultIds {
509                 e, ok := tx.Entries[*id]
510                 if !ok {
511                         return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
512                 }
513
514                 output, ok := e.(*bc.Output)
515                 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
516                         continue
517                 }
518
519                 if !segwit.IsP2WScript(output.ControlProgram.Code) {
520                         return ErrNotStandardTx
521                 }
522         }
523         return nil
524 }
525
526 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
527         if tx.TimeRange == 0 {
528                 return nil
529         }
530
531         if tx.TimeRange < block.Height {
532                 return ErrBadTimeRange
533         }
534         return nil
535 }
536
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)
542         }
543         if tx.SerializedSize == 0 {
544                 return gasStatus, ErrWrongTransactionSize
545         }
546         if err := checkTimeRange(tx, block); err != nil {
547                 return gasStatus, err
548         }
549         if err := checkStandardTx(tx); err != nil {
550                 return gasStatus, err
551         }
552         vs := &validationState{
553                 block:     block,
554                 tx:        tx,
555                 entryID:   tx.ID,
556                 gasStatus: gasStatus,
557                 cache:     make(map[bc.Hash]error),
558         }
559         return vs.gasStatus, checkValid(vs, tx.TxHeader)
560 }