OSDN Git Service

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