OSDN Git Service

add cancel vote (#172)
[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
269                 spentOutput, err := vs.tx.IntraChainOutput(*e.SpentOutputId)
270                 if err != nil {
271                         return errors.Wrap(err, "getting spend prevout")
272                 }
273
274                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
275                 if err != nil {
276                         return errors.Wrap(err, "checking control program")
277                 }
278                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
279                         return err
280                 }
281
282                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
283                 if err != nil {
284                         return err
285                 }
286                 if !eq {
287                         return errors.WithDetailf(
288                                 ErrMismatchedValue,
289                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
290                                 spentOutput.Source.Value.Amount,
291                                 spentOutput.Source.Value.AssetId.Bytes(),
292                                 e.WitnessDestination.Value.Amount,
293                                 e.WitnessDestination.Value.AssetId.Bytes(),
294                         )
295                 }
296                 vs2 := *vs
297                 vs2.destPos = 0
298                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
299                         return errors.Wrap(err, "checking spend destination")
300                 }
301
302         case *bc.VetoInput:
303                 if e.SpentOutputId == nil {
304                         return errors.Wrap(ErrMissingField, "vetoInput without vetoInput output ID")
305                 }
306
307                 voteOutput, err := vs.tx.VoteOutput(*e.SpentOutputId)
308                 if err != nil {
309                         return errors.Wrap(err, "getting vetoInput prevout")
310                 }
311                 if len(voteOutput.Vote) != 64 {
312                         return ErrVotePubKey
313                 }
314
315                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, voteOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
316                 if err != nil {
317                         return errors.Wrap(err, "checking control program")
318                 }
319                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
320                         return err
321                 }
322
323                 eq, err := voteOutput.Source.Value.Equal(e.WitnessDestination.Value)
324                 if err != nil {
325                         return err
326                 }
327                 if !eq {
328                         return errors.WithDetailf(
329                                 ErrMismatchedValue,
330                                 "previous output is for %d unit(s) of %x, vetoInput wants %d unit(s) of %x",
331                                 voteOutput.Source.Value.Amount,
332                                 voteOutput.Source.Value.AssetId.Bytes(),
333                                 e.WitnessDestination.Value.Amount,
334                                 e.WitnessDestination.Value.AssetId.Bytes(),
335                         )
336                 }
337                 vs2 := *vs
338                 vs2.destPos = 0
339                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
340                         return errors.Wrap(err, "checking vetoInput destination")
341                 }
342
343         case *bc.Coinbase:
344                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
345                         return ErrWrongCoinbaseTransaction
346                 }
347
348                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
349                         return ErrWrongCoinbaseAsset
350                 }
351
352                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
353                         return ErrCoinbaseArbitraryOversize
354                 }
355
356                 vs2 := *vs
357                 vs2.destPos = 0
358                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
359                         return errors.Wrap(err, "checking coinbase destination")
360                 }
361                 vs.gasStatus.StorageGas = 0
362
363         default:
364                 return fmt.Errorf("entry has unexpected type %T", e)
365         }
366
367         return nil
368 }
369
370 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
371         if vs == nil {
372                 return errors.Wrap(ErrMissingField, "empty value source")
373         }
374         if vs.Ref == nil {
375                 return errors.Wrap(ErrMissingField, "missing ref on value source")
376         }
377         if vs.Value == nil || vs.Value.AssetId == nil {
378                 return errors.Wrap(ErrMissingField, "missing value on value source")
379         }
380
381         e, ok := vstate.tx.Entries[*vs.Ref]
382         if !ok {
383                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
384         }
385
386         vstate2 := *vstate
387         vstate2.entryID = *vs.Ref
388         if err := checkValid(&vstate2, e); err != nil {
389                 return errors.Wrap(err, "checking value source")
390         }
391
392         var dest *bc.ValueDestination
393         switch ref := e.(type) {
394         case *bc.VetoInput:
395                 if vs.Position != 0 {
396                         return errors.Wrapf(ErrPosition, "invalid position %d for veto-input source", vs.Position)
397                 }
398                 dest = ref.WitnessDestination
399
400         case *bc.Coinbase:
401                 if vs.Position != 0 {
402                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
403                 }
404                 dest = ref.WitnessDestination
405
406         case *bc.CrossChainInput:
407                 if vs.Position != 0 {
408                         return errors.Wrapf(ErrPosition, "invalid position %d for cross-chain input source", vs.Position)
409                 }
410                 dest = ref.WitnessDestination
411
412         case *bc.Spend:
413                 if vs.Position != 0 {
414                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
415                 }
416                 dest = ref.WitnessDestination
417
418         case *bc.Mux:
419                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
420                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
421                 }
422                 dest = ref.WitnessDestinations[vs.Position]
423
424         default:
425                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, cross-chain input, spend, or mux", e)
426         }
427
428         if dest.Ref == nil || *dest.Ref != vstate.entryID {
429                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
430         }
431
432         if dest.Position != vstate.sourcePos {
433                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
434         }
435
436         eq, err := dest.Value.Equal(vs.Value)
437         if err != nil {
438                 return errors.Sub(ErrMissingField, err)
439         }
440         if !eq {
441                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
442         }
443
444         return nil
445 }
446
447 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
448         if vd == nil {
449                 return errors.Wrap(ErrMissingField, "empty value destination")
450         }
451         if vd.Ref == nil {
452                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
453         }
454         if vd.Value == nil || vd.Value.AssetId == nil {
455                 return errors.Wrap(ErrMissingField, "missing value on value destination")
456         }
457
458         e, ok := vs.tx.Entries[*vd.Ref]
459         if !ok {
460                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
461         }
462
463         var src *bc.ValueSource
464         switch ref := e.(type) {
465         case *bc.IntraChainOutput:
466                 if vd.Position != 0 {
467                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
468                 }
469                 src = ref.Source
470
471         case *bc.CrossChainOutput:
472                 if vd.Position != 0 {
473                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
474                 }
475                 src = ref.Source
476
477         case *bc.VoteOutput:
478                 if vd.Position != 0 {
479                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
480                 }
481                 src = ref.Source
482
483         case *bc.Retirement:
484                 if vd.Position != 0 {
485                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
486                 }
487                 src = ref.Source
488
489         case *bc.Mux:
490                 if vd.Position >= uint64(len(ref.Sources)) {
491                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
492                 }
493                 src = ref.Sources[vd.Position]
494
495         default:
496                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be intra-chain/cross-chain output, retirement, or mux", e)
497         }
498
499         if src.Ref == nil || *src.Ref != vs.entryID {
500                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
501         }
502
503         if src.Position != vs.destPos {
504                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
505         }
506
507         eq, err := src.Value.Equal(vd.Value)
508         if err != nil {
509                 return errors.Sub(ErrMissingField, err)
510         }
511         if !eq {
512                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
513         }
514
515         return nil
516 }
517
518 func checkFedaration(tx *bc.Tx) error {
519         for _, id := range tx.InputIDs {
520                 switch inp := tx.Entries[id].(type) {
521                 case *bc.CrossChainInput:
522                         fedProg := config.FederationProgrom(config.CommonConfig)
523                         if !bytes.Equal(inp.ControlProgram.Code, fedProg) {
524                                 return errors.New("The federal controlProgram is incorrect")
525                         }
526                 default:
527                         continue
528                 }
529         }
530         return nil
531 }
532
533 func checkStandardTx(tx *bc.Tx, blockHeight uint64) error {
534         for _, id := range tx.InputIDs {
535                 if blockHeight >= ruleAA && id.IsZero() {
536                         return ErrEmptyInputIDs
537                 }
538         }
539
540         if err := checkFedaration(tx); err != nil {
541                 return err
542         }
543
544         for _, id := range tx.GasInputIDs {
545                 spend, err := tx.Spend(id)
546                 if err != nil {
547                         continue
548                 }
549
550                 code := []byte{}
551                 outputEntry, err := tx.Entry(*spend.SpentOutputId)
552                 if err != nil {
553                         return err
554                 }
555                 switch output := outputEntry.(type) {
556                 case *bc.IntraChainOutput:
557                         code = output.ControlProgram.Code
558                 case *bc.VoteOutput:
559                         code = output.ControlProgram.Code
560                 default:
561                         return errors.Wrapf(bc.ErrEntryType, "entry %x has unexpected type %T", id.Bytes(), outputEntry)
562                 }
563
564                 if !segwit.IsP2WScript(code) {
565                         return ErrNotStandardTx
566                 }
567         }
568         return nil
569 }
570
571 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
572         if tx.TimeRange == 0 {
573                 return nil
574         }
575
576         if tx.TimeRange < block.Height {
577                 return ErrBadTimeRange
578         }
579
580         return nil
581 }
582
583 // ValidateTx validates a transaction.
584 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
585         gasStatus := &GasState{GasValid: false}
586         if block.Version == 1 && tx.Version != 1 {
587                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
588         }
589         if tx.SerializedSize == 0 {
590                 return gasStatus, ErrWrongTransactionSize
591         }
592         if err := checkTimeRange(tx, block); err != nil {
593                 return gasStatus, err
594         }
595         if err := checkStandardTx(tx, block.Height); err != nil {
596                 return gasStatus, err
597         }
598
599         vs := &validationState{
600                 block:     block,
601                 tx:        tx,
602                 entryID:   tx.ID,
603                 gasStatus: gasStatus,
604                 cache:     make(map[bc.Hash]error),
605         }
606         return vs.gasStatus, checkValid(vs, tx.TxHeader)
607 }