OSDN Git Service

add dpos consensus
[bytom/vapor.git] / protocol / validation / tx.go
1 package validation
2
3 import (
4         "bytes"
5         "encoding/json"
6         "fmt"
7         "math"
8         "strconv"
9
10         "github.com/vapor/consensus"
11         "github.com/vapor/consensus/segwit"
12         "github.com/vapor/crypto"
13         "github.com/vapor/equity/pegin_contract"
14         "github.com/vapor/errors"
15         "github.com/vapor/math/checked"
16         "github.com/vapor/protocol/bc"
17         "github.com/vapor/protocol/bc/types"
18         bytomtypes "github.com/vapor/protocol/bc/types/bytom/types"
19         "github.com/vapor/protocol/vm"
20         "github.com/vapor/protocol/vm/vmutil"
21         "github.com/vapor/util"
22 )
23
24 // validate transaction error
25 var (
26         ErrTxVersion                 = errors.New("invalid transaction version")
27         ErrWrongTransactionSize      = errors.New("invalid transaction size")
28         ErrBadTimeRange              = errors.New("invalid transaction time range")
29         ErrNotStandardTx             = errors.New("not standard transaction")
30         ErrWrongCoinbaseTransaction  = errors.New("wrong coinbase transaction")
31         ErrWrongCoinbaseAsset        = errors.New("wrong coinbase assetID")
32         ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
33         ErrEmptyResults              = errors.New("transaction has no results")
34         ErrMismatchedAssetID         = errors.New("mismatched assetID")
35         ErrMismatchedPosition        = errors.New("mismatched value source/dest position")
36         ErrMismatchedReference       = errors.New("mismatched reference")
37         ErrMismatchedValue           = errors.New("mismatched value")
38         ErrMissingField              = errors.New("missing required field")
39         ErrNoSource                  = errors.New("no source for value")
40         ErrOverflow                  = errors.New("arithmetic overflow/underflow")
41         ErrPosition                  = errors.New("invalid source or destination position")
42         ErrUnbalanced                = errors.New("unbalanced asset amount between input and output")
43         ErrOverGasCredit             = errors.New("all gas credit has been spend")
44         ErrGasCalculate              = errors.New("gas usage calculate got a math error")
45 )
46
47 // GasState record the gas usage status
48 type GasState struct {
49         BTMValue   uint64
50         GasLeft    int64
51         GasUsed    int64
52         GasValid   bool
53         StorageGas int64
54 }
55
56 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
57         if BTMValue < 0 {
58                 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
59         }
60
61         g.BTMValue = uint64(BTMValue)
62
63         var ok bool
64         if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
65                 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
66         }
67
68         if g.GasLeft > consensus.MaxGasAmount {
69                 g.GasLeft = consensus.MaxGasAmount
70         }
71
72         if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
73                 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
74         }
75         return nil
76 }
77
78 func (g *GasState) setGasValid() error {
79         var ok bool
80         if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
81                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
82         }
83
84         if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
85                 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
86         }
87
88         g.GasValid = true
89         return nil
90 }
91
92 func (g *GasState) updateUsage(gasLeft int64) error {
93         if gasLeft < 0 {
94                 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
95         }
96
97         if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
98                 g.GasUsed += gasUsed
99                 g.GasLeft = gasLeft
100         } else {
101                 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
102         }
103
104         if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
105                 return ErrOverGasCredit
106         }
107         return nil
108 }
109
110 // validationState contains the context that must propagate through
111 // the transaction graph when validating entries.
112 type validationState struct {
113         block     *bc.Block
114         tx        *bc.Tx
115         gasStatus *GasState
116         entryID   bc.Hash           // The ID of the nearest enclosing entry
117         sourcePos uint64            // The source position, for validate ValueSources
118         destPos   uint64            // The destination position, for validate ValueDestinations
119         cache     map[bc.Hash]error // Memoized per-entry validation results
120 }
121
122 func checkValid(vs *validationState, e bc.Entry) (err error) {
123         var ok bool
124         entryID := bc.EntryID(e)
125         if err, ok = vs.cache[entryID]; ok {
126                 return err
127         }
128
129         defer func() {
130                 vs.cache[entryID] = err
131         }()
132
133         switch e := e.(type) {
134         case *bc.TxHeader:
135                 for i, resID := range e.ResultIds {
136                         resultEntry := vs.tx.Entries[*resID]
137                         vs2 := *vs
138                         vs2.entryID = *resID
139                         if err = checkValid(&vs2, resultEntry); err != nil {
140                                 return errors.Wrapf(err, "checking result %d", i)
141                         }
142                 }
143
144                 if e.Version == 1 && len(e.ResultIds) == 0 {
145                         return ErrEmptyResults
146                 }
147
148         case *bc.Mux:
149                 parity := make(map[bc.AssetID]int64)
150                 for i, src := range e.Sources {
151                         e, ok := vs.tx.Entries[*src.Ref]
152                         if !ok {
153                                 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", *src.Ref)
154                         }
155                         switch e.(type) {
156                         case *bc.Dpos:
157                                 continue
158                         default:
159                         }
160
161                         if src.Value.Amount > math.MaxInt64 {
162                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
163                         }
164                         sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
165                         if !ok {
166                                 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])
167                         }
168                         parity[*src.Value.AssetId] = sum
169                 }
170
171                 for i, dest := range e.WitnessDestinations {
172                         sum, ok := parity[*dest.Value.AssetId]
173                         if !ok {
174                                 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
175                         }
176                         if dest.Value.Amount > math.MaxInt64 {
177                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
178                         }
179                         diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
180                         if !ok {
181                                 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)
182                         }
183                         parity[*dest.Value.AssetId] = diff
184                 }
185
186                 for assetID, amount := range parity {
187                         if assetID == *consensus.BTMAssetID {
188                                 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
189                                         return err
190                                 }
191                         } else if amount != 0 {
192                                 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
193                         }
194                 }
195
196                 for _, BTMInputID := range vs.tx.GasInputIDs {
197                         e, ok := vs.tx.Entries[BTMInputID]
198                         if !ok {
199                                 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
200                         }
201                         vs2 := *vs
202                         vs2.entryID = BTMInputID
203                         if err := checkValid(&vs2, e); err != nil {
204                                 return errors.Wrap(err, "checking gas input")
205                         }
206                 }
207
208                 for i, dest := range e.WitnessDestinations {
209                         vs2 := *vs
210                         vs2.destPos = uint64(i)
211                         if err = checkValidDest(&vs2, dest); err != nil {
212                                 return errors.Wrapf(err, "checking mux destination %d", i)
213                         }
214                 }
215
216                 if len(vs.tx.GasInputIDs) > 0 {
217                         if err := vs.gasStatus.setGasValid(); err != nil {
218                                 return err
219                         }
220                 }
221
222                 for i, src := range e.Sources {
223                         vs2 := *vs
224                         vs2.sourcePos = uint64(i)
225                         if err = checkValidSrc(&vs2, src); err != nil {
226                                 return errors.Wrapf(err, "checking mux source %d", i)
227                         }
228                 }
229
230         case *bc.Output:
231                 vs2 := *vs
232                 vs2.sourcePos = 0
233                 if err = checkValidSrc(&vs2, e.Source); err != nil {
234                         return errors.Wrap(err, "checking output source")
235                 }
236
237         case *bc.Retirement:
238                 vs2 := *vs
239                 vs2.sourcePos = 0
240                 if err = checkValidSrc(&vs2, e.Source); err != nil {
241                         return errors.Wrap(err, "checking retirement source")
242                 }
243
244         case *bc.Issuance:
245                 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
246                 if computedAssetID != *e.Value.AssetId {
247                         return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
248                 }
249
250                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
251                 if err != nil {
252                         return errors.Wrap(err, "checking issuance program")
253                 }
254                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
255                         return err
256                 }
257
258                 destVS := *vs
259                 destVS.destPos = 0
260                 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
261                         return errors.Wrap(err, "checking issuance destination")
262                 }
263
264         case *bc.Spend:
265                 if e.SpentOutputId == nil {
266                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
267                 }
268                 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
269                 if err != nil {
270                         return errors.Wrap(err, "getting spend prevout")
271                 }
272                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
273                 if err != nil {
274                         return errors.Wrap(err, "checking control program")
275                 }
276                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
277                         return err
278                 }
279
280                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
281                 if err != nil {
282                         return err
283                 }
284                 if !eq {
285                         return errors.WithDetailf(
286                                 ErrMismatchedValue,
287                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
288                                 spentOutput.Source.Value.Amount,
289                                 spentOutput.Source.Value.AssetId.Bytes(),
290                                 e.WitnessDestination.Value.Amount,
291                                 e.WitnessDestination.Value.AssetId.Bytes(),
292                         )
293                 }
294
295                 vs2 := *vs
296                 vs2.destPos = 0
297                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
298                         return errors.Wrap(err, "checking spend destination")
299                 }
300
301         case *bc.Coinbase:
302                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
303                         return ErrWrongCoinbaseTransaction
304                 }
305
306                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
307                         return ErrWrongCoinbaseAsset
308                 }
309
310                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
311                         return ErrCoinbaseArbitraryOversize
312                 }
313
314                 vs2 := *vs
315                 vs2.destPos = 0
316                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
317                         return errors.Wrap(err, "checking coinbase destination")
318                 }
319
320                 // special case for coinbase transaction, it's valid unit all the verify has been passed
321                 vs.gasStatus.GasValid = true
322         case *bc.Claim:
323                 // 对交易的合法性进行验证
324                 if e.SpentOutputId == nil {
325                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
326                 }
327                 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
328                 if err != nil {
329                         return errors.Wrap(err, "getting spend prevout")
330                 }
331                 stack := e.GetPeginwitness()
332                 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
333
334                         return errors.New("pegin-no-witness")
335                 }
336
337                 if err := IsValidPeginWitness(stack, *spentOutput); err != nil {
338                         return err
339                 }
340
341                 // 判断cliam tx的输入是否已经被用
342
343                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
344                 if err != nil {
345                         return err
346                 }
347                 if !eq {
348                         return errors.WithDetailf(
349                                 ErrMismatchedValue,
350                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
351                                 spentOutput.Source.Value.Amount,
352                                 spentOutput.Source.Value.AssetId.Bytes(),
353                                 e.WitnessDestination.Value.Amount,
354                                 e.WitnessDestination.Value.AssetId.Bytes(),
355                         )
356                 }
357
358                 vs2 := *vs
359                 vs2.destPos = 0
360                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
361                         return errors.Wrap(err, "checking spend destination")
362                 }
363                 vs.gasStatus.GasValid = true
364         case *bc.Dpos:
365                 //fmt.Printf("kkkkkkkkkkkkkkkkkkkkkkkkkkk %T\n", e)
366         default:
367                 return fmt.Errorf("entry has unexpected type %T", e)
368         }
369
370         return nil
371 }
372
373 type MerkleBlock struct {
374         BlockHeader  []byte     `json:"block_header"`
375         TxHashes     []*bc.Hash `json:"tx_hashes"`
376         StatusHashes []*bc.Hash `json:"status_hashes"`
377         Flags        []uint32   `json:"flags"`
378         MatchedTxIDs []*bc.Hash `json:"matched_tx_ids"`
379 }
380
381 func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
382
383         assetAmount := &bc.AssetAmount{
384                 AssetId: prevout.Source.Value.AssetId,
385                 Amount:  prevout.Source.Value.Amount,
386         }
387
388         src := &bc.ValueSource{
389                 Ref:      prevout.Source.Ref,
390                 Value:    assetAmount,
391                 Position: prevout.Source.Position,
392         }
393         prog := &bc.Program{prevout.ControlProgram.VmVersion, prevout.ControlProgram.Code}
394         bytomPrevout := bc.NewOutput(src, prog, prevout.Source.Position)
395
396         if len(peginWitness) != 5 {
397                 return errors.New("peginWitness is error")
398         }
399         amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
400         if err != nil {
401                 return err
402         }
403         if !consensus.MoneyRange(amount) {
404                 return errors.New("Amount out of range")
405         }
406         /*
407                 if len(peginWitness[1]) != 32 {
408                         return errors.New("The length of gennesisBlockHash is not correct")
409                 }
410         */
411         claimScript := peginWitness[2]
412
413         rawTx := &bytomtypes.Tx{}
414         err = rawTx.UnmarshalText(peginWitness[3])
415         if err != nil {
416                 return err
417         }
418
419         merkleBlock := &MerkleBlock{}
420         err = json.Unmarshal(peginWitness[4], merkleBlock)
421         if err != nil {
422                 return err
423         }
424         // proof验证
425         var flags []uint8
426         for flag := range merkleBlock.Flags {
427                 flags = append(flags, uint8(flag))
428         }
429         blockHeader := &bytomtypes.BlockHeader{}
430         if err = blockHeader.UnmarshalText(merkleBlock.BlockHeader); err != nil {
431                 return err
432         }
433
434         if !types.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, blockHeader.BlockCommitment.TransactionsMerkleRoot) {
435                 return errors.New("Merkleblock validation failed")
436         }
437
438         // 交易进行验证
439         if err = checkPeginTx(rawTx, bytomPrevout, amount, claimScript); err != nil {
440                 return err
441         }
442         var b bc.Hash
443         b.UnmarshalText(peginWitness[1])
444         // Check the genesis block corresponds to a valid peg (only one for now)
445         if b.String() != consensus.ActiveNetParams.ParentGenesisBlockHash {
446                 return errors.New("ParentGenesisBlockHash don't match")
447         }
448         // TODO Finally, validate peg-in via rpc call
449
450         if util.ValidatePegin {
451                 if err := util.IsConfirmedBytomBlock(blockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
452                         return err
453                 }
454         }
455
456         return nil
457 }
458
459 func checkPeginTx(rawTx *bytomtypes.Tx, prevout *bc.Output, claimAmount uint64, claimScript []byte) error {
460         // Check the transaction nout/value matches
461         amount := rawTx.Outputs[prevout.Source.Position].Amount
462         if claimAmount != amount {
463                 return errors.New("transaction nout/value do not matches")
464         }
465         // Check that the witness program matches the p2ch on the p2sh-p2wsh transaction output
466         //federationRedeemScript := vmutil.CalculateContract(consensus.ActiveNetParams.FedpegXPubs, claimScript)
467         //scriptHash := crypto.Sha256(federationRedeemScript)
468         peginContractPrograms, err := pegin_contract.GetPeginContractPrograms(claimScript)
469         if err != nil {
470                 return err
471         }
472
473         scriptHash := crypto.Sha256(peginContractPrograms)
474         controlProg, err := vmutil.P2WSHProgram(scriptHash)
475         if err != nil {
476                 return err
477         }
478         if !bytes.Equal(rawTx.Outputs[prevout.Source.Position].ControlProgram, controlProg) {
479                 return errors.New("The output control program of transaction does not match the control program of the system's alliance contract")
480         }
481         return nil
482 }
483
484 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
485         if vs == nil {
486                 return errors.Wrap(ErrMissingField, "empty value source")
487         }
488         if vs.Ref == nil {
489                 return errors.Wrap(ErrMissingField, "missing ref on value source")
490         }
491         if vs.Value == nil || vs.Value.AssetId == nil {
492                 return errors.Wrap(ErrMissingField, "missing value on value source")
493         }
494
495         e, ok := vstate.tx.Entries[*vs.Ref]
496         if !ok {
497                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
498         }
499
500         vstate2 := *vstate
501         vstate2.entryID = *vs.Ref
502         if err := checkValid(&vstate2, e); err != nil {
503                 return errors.Wrap(err, "checking value source")
504         }
505
506         var dest *bc.ValueDestination
507         switch ref := e.(type) {
508         case *bc.Coinbase:
509                 if vs.Position != 0 {
510                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
511                 }
512                 dest = ref.WitnessDestination
513
514         case *bc.Issuance:
515                 if vs.Position != 0 {
516                         return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
517                 }
518                 dest = ref.WitnessDestination
519
520         case *bc.Spend:
521                 if vs.Position != 0 {
522                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
523                 }
524                 dest = ref.WitnessDestination
525
526         case *bc.Mux:
527                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
528                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
529                 }
530                 dest = ref.WitnessDestinations[vs.Position]
531         case *bc.Claim:
532                 if vs.Position != 0 {
533                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
534                 }
535                 dest = ref.WitnessDestination
536         case *bc.Dpos:
537                 if vs.Position != 0 {
538                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
539                 }
540                 dest = ref.WitnessDestination
541         default:
542                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
543         }
544
545         if dest.Ref == nil || *dest.Ref != vstate.entryID {
546                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
547         }
548
549         if dest.Position != vstate.sourcePos {
550                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
551         }
552
553         eq, err := dest.Value.Equal(vs.Value)
554         if err != nil {
555                 return errors.Sub(ErrMissingField, err)
556         }
557         if !eq {
558                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
559         }
560
561         return nil
562 }
563
564 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
565         if vd == nil {
566                 return errors.Wrap(ErrMissingField, "empty value destination")
567         }
568         if vd.Ref == nil {
569                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
570         }
571         if vd.Value == nil || vd.Value.AssetId == nil {
572                 return errors.Wrap(ErrMissingField, "missing value on value source")
573         }
574
575         e, ok := vs.tx.Entries[*vd.Ref]
576         if !ok {
577                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
578         }
579
580         var src *bc.ValueSource
581         switch ref := e.(type) {
582         case *bc.Output:
583                 if vd.Position != 0 {
584                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
585                 }
586                 src = ref.Source
587
588         case *bc.Retirement:
589                 if vd.Position != 0 {
590                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
591                 }
592                 src = ref.Source
593
594         case *bc.Mux:
595                 if vd.Position >= uint64(len(ref.Sources)) {
596                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
597                 }
598                 src = ref.Sources[vd.Position]
599
600         default:
601                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
602         }
603
604         if src.Ref == nil || *src.Ref != vs.entryID {
605                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
606         }
607
608         if src.Position != vs.destPos {
609                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
610         }
611
612         eq, err := src.Value.Equal(vd.Value)
613         if err != nil {
614                 return errors.Sub(ErrMissingField, err)
615         }
616         if !eq {
617                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
618         }
619
620         return nil
621 }
622
623 func checkStandardTx(tx *bc.Tx) error {
624         for _, id := range tx.GasInputIDs {
625                 spend, err := tx.Spend(id)
626                 if err != nil {
627                         return err
628                 }
629                 spentOutput, err := tx.Output(*spend.SpentOutputId)
630                 if err != nil {
631                         return err
632                 }
633
634                 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
635                         return ErrNotStandardTx
636                 }
637         }
638
639         for _, id := range tx.ResultIds {
640                 e, ok := tx.Entries[*id]
641                 if !ok {
642                         return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
643                 }
644
645                 output, ok := e.(*bc.Output)
646                 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
647                         continue
648                 }
649
650                 if !segwit.IsP2WScript(output.ControlProgram.Code) {
651                         return ErrNotStandardTx
652                 }
653         }
654         return nil
655 }
656
657 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
658         if tx.TimeRange == 0 {
659                 return nil
660         }
661
662         if tx.TimeRange < block.Height {
663                 return ErrBadTimeRange
664         }
665         return nil
666 }
667
668 // ValidateTx validates a transaction.
669 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
670         gasStatus := &GasState{GasValid: false}
671         if block.Version == 1 && tx.Version != 1 {
672                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
673         }
674         if tx.SerializedSize == 0 {
675                 return gasStatus, ErrWrongTransactionSize
676         }
677         if err := checkTimeRange(tx, block); err != nil {
678                 return gasStatus, err
679         }
680         if err := checkStandardTx(tx); err != nil {
681                 return gasStatus, err
682         }
683         vs := &validationState{
684                 block:     block,
685                 tx:        tx,
686                 entryID:   tx.ID,
687                 gasStatus: gasStatus,
688                 cache:     make(map[bc.Hash]error),
689         }
690         return vs.gasStatus, checkValid(vs, tx.TxHeader)
691 }