OSDN Git Service

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