OSDN Git Service

421cc8a4377ff9df17cc69368411cdc03014ad21
[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                         if src.Value.Amount > math.MaxInt64 {
152                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
153                         }
154                         sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
155                         if !ok {
156                                 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])
157                         }
158                         parity[*src.Value.AssetId] = sum
159                 }
160
161                 for i, dest := range e.WitnessDestinations {
162                         sum, ok := parity[*dest.Value.AssetId]
163                         if !ok {
164                                 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
165                         }
166                         if dest.Value.Amount > math.MaxInt64 {
167                                 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
168                         }
169                         diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
170                         if !ok {
171                                 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)
172                         }
173                         parity[*dest.Value.AssetId] = diff
174                 }
175
176                 for assetID, amount := range parity {
177                         if assetID == *consensus.BTMAssetID {
178                                 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
179                                         return err
180                                 }
181                         } else if amount != 0 {
182                                 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
183                         }
184                 }
185
186                 for _, BTMInputID := range vs.tx.GasInputIDs {
187                         e, ok := vs.tx.Entries[BTMInputID]
188                         if !ok {
189                                 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
190                         }
191
192                         vs2 := *vs
193                         vs2.entryID = BTMInputID
194                         if err := checkValid(&vs2, e); err != nil {
195                                 return errors.Wrap(err, "checking gas input")
196                         }
197                 }
198
199                 for i, dest := range e.WitnessDestinations {
200                         vs2 := *vs
201                         vs2.destPos = uint64(i)
202                         if err = checkValidDest(&vs2, dest); err != nil {
203                                 return errors.Wrapf(err, "checking mux destination %d", i)
204                         }
205                 }
206
207                 if len(vs.tx.GasInputIDs) > 0 {
208                         if err := vs.gasStatus.setGasValid(); err != nil {
209                                 return err
210                         }
211                 }
212
213                 for i, src := range e.Sources {
214                         vs2 := *vs
215                         vs2.sourcePos = uint64(i)
216                         if err = checkValidSrc(&vs2, src); err != nil {
217                                 return errors.Wrapf(err, "checking mux source %d", i)
218                         }
219                 }
220
221         case *bc.Output:
222                 vs2 := *vs
223                 vs2.sourcePos = 0
224                 if err = checkValidSrc(&vs2, e.Source); err != nil {
225                         return errors.Wrap(err, "checking output source")
226                 }
227
228         case *bc.Retirement:
229                 vs2 := *vs
230                 vs2.sourcePos = 0
231                 if err = checkValidSrc(&vs2, e.Source); err != nil {
232                         return errors.Wrap(err, "checking retirement source")
233                 }
234
235         case *bc.Issuance:
236                 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
237                 if computedAssetID != *e.Value.AssetId {
238                         return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
239                 }
240
241                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
242                 if err != nil {
243                         return errors.Wrap(err, "checking issuance program")
244                 }
245                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
246                         return err
247                 }
248
249                 destVS := *vs
250                 destVS.destPos = 0
251                 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
252                         return errors.Wrap(err, "checking issuance destination")
253                 }
254
255         case *bc.Spend:
256                 if e.SpentOutputId == nil {
257                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
258                 }
259                 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
260                 if err != nil {
261                         return errors.Wrap(err, "getting spend prevout")
262                 }
263
264                 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
265                 if err != nil {
266                         return errors.Wrap(err, "checking control program")
267                 }
268                 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
269                         return err
270                 }
271
272                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
273                 if err != nil {
274                         return err
275                 }
276                 if !eq {
277                         return errors.WithDetailf(
278                                 ErrMismatchedValue,
279                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
280                                 spentOutput.Source.Value.Amount,
281                                 spentOutput.Source.Value.AssetId.Bytes(),
282                                 e.WitnessDestination.Value.Amount,
283                                 e.WitnessDestination.Value.AssetId.Bytes(),
284                         )
285                 }
286
287                 vs2 := *vs
288                 vs2.destPos = 0
289                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
290                         return errors.Wrap(err, "checking spend destination")
291                 }
292
293         case *bc.Coinbase:
294                 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
295                         return ErrWrongCoinbaseTransaction
296                 }
297
298                 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
299                         return ErrWrongCoinbaseAsset
300                 }
301
302                 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
303                         return ErrCoinbaseArbitraryOversize
304                 }
305
306                 vs2 := *vs
307                 vs2.destPos = 0
308                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
309                         return errors.Wrap(err, "checking coinbase destination")
310                 }
311
312                 // special case for coinbase transaction, it's valid unit all the verify has been passed
313                 vs.gasStatus.GasValid = true
314         case *bc.Claim:
315                 // 对交易的合法性进行验证
316                 if e.SpentOutputId == nil {
317                         return errors.Wrap(ErrMissingField, "spend without spent output ID")
318                 }
319                 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
320                 if err != nil {
321                         return errors.Wrap(err, "getting spend prevout")
322                 }
323                 stack := e.GetPeginwitness()
324                 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
325
326                         return errors.New("pegin-no-witness")
327                 }
328
329                 if err := IsValidPeginWitness(stack, *spentOutput); err != nil {
330                         return err
331                 }
332
333                 // 判断cliam tx的输入是否已经被用
334
335                 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
336                 if err != nil {
337                         return err
338                 }
339                 if !eq {
340                         return errors.WithDetailf(
341                                 ErrMismatchedValue,
342                                 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
343                                 spentOutput.Source.Value.Amount,
344                                 spentOutput.Source.Value.AssetId.Bytes(),
345                                 e.WitnessDestination.Value.Amount,
346                                 e.WitnessDestination.Value.AssetId.Bytes(),
347                         )
348                 }
349
350                 vs2 := *vs
351                 vs2.destPos = 0
352                 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
353                         return errors.Wrap(err, "checking spend destination")
354                 }
355                 vs.gasStatus.GasValid = true
356         default:
357                 return fmt.Errorf("entry has unexpected type %T", e)
358         }
359
360         return nil
361 }
362
363 type MerkleBlock struct {
364         BlockHeader  []byte     `json:"block_header"`
365         TxHashes     []*bc.Hash `json:"tx_hashes"`
366         StatusHashes []*bc.Hash `json:"status_hashes"`
367         Flags        []uint32   `json:"flags"`
368         MatchedTxIDs []*bc.Hash `json:"matched_tx_ids"`
369 }
370
371 func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
372         /*
373                 assetID := bc.AssetID{}
374                 assetID.V0 = prevout.Source.Value.AssetId.GetV0()
375                 assetID.V1 = prevout.Source.Value.AssetId.GetV1()
376                 assetID.V2 = prevout.Source.Value.AssetId.GetV2()
377                 assetID.V3 = prevout.Source.Value.AssetId.GetV3()
378                 //bytomPrevout.Source.Value.AssetId = &assetId
379
380                 sourceID := bc.Hash{}
381                 sourceID.V0 = prevout.Source.Ref.GetV0()
382                 sourceID.V1 = prevout.Source.Ref.GetV1()
383                 sourceID.V2 = prevout.Source.Ref.GetV2()
384                 sourceID.V3 = prevout.Source.Ref.GetV3()
385         */
386
387         assetAmount := &bc.AssetAmount{
388                 AssetId: prevout.Source.Value.AssetId,
389                 Amount:  prevout.Source.Value.Amount,
390         }
391
392         src := &bc.ValueSource{
393                 Ref:      prevout.Source.Ref,
394                 Value:    assetAmount,
395                 Position: prevout.Source.Position,
396         }
397         prog := &bc.Program{prevout.ControlProgram.VmVersion, prevout.ControlProgram.Code}
398         bytomPrevout := bc.NewOutput(src, prog, prevout.Source.Position)
399
400         if len(peginWitness) != 5 {
401                 return errors.New("peginWitness is error")
402         }
403         amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
404         if err != nil {
405                 return err
406         }
407         if !consensus.MoneyRange(amount) {
408                 return errors.New("Amount out of range")
409         }
410
411         if len(peginWitness[1]) != 64 {
412                 return errors.New("The length of gennesisBlockHash is not correct")
413         }
414
415         claimScript := peginWitness[2]
416
417         rawTx := &bytomtypes.Tx{}
418         err = rawTx.UnmarshalText(peginWitness[3])
419         if err != nil {
420                 return err
421         }
422
423         merkleBlock := &MerkleBlock{}
424         err = json.Unmarshal(peginWitness[4], merkleBlock)
425         if err != nil {
426                 return err
427         }
428         // proof验证
429         var flags []uint8
430         for flag := range merkleBlock.Flags {
431                 flags = append(flags, uint8(flag))
432         }
433         blockHeader := &bytomtypes.BlockHeader{}
434         if err = blockHeader.UnmarshalText(merkleBlock.BlockHeader); err != nil {
435                 return err
436         }
437
438         if !types.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, blockHeader.BlockCommitment.TransactionsMerkleRoot) {
439                 return errors.New("Merkleblock validation failed")
440         }
441
442         // 交易进行验证
443         if err = checkPeginTx(rawTx, bytomPrevout, amount, claimScript); err != nil {
444                 return err
445         }
446
447         // Check the genesis block corresponds to a valid peg (only one for now)
448         if !bytes.Equal(peginWitness[1], []byte(consensus.ActiveNetParams.ParentGenesisBlockHash)) {
449                 return errors.New("ParentGenesisBlockHash don't match")
450         }
451         // TODO Finally, validate peg-in via rpc call
452
453         if util.ValidatePegin {
454                 if err := util.IsConfirmedBytomBlock(blockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
455                         return err
456                 }
457         }
458
459         return nil
460 }
461
462 func checkPeginTx(rawTx *bytomtypes.Tx, prevout *bc.Output, claimAmount uint64, claimScript []byte) error {
463         // Check the transaction nout/value matches
464         amount := rawTx.Outputs[prevout.Source.Position].Amount
465         if claimAmount != amount {
466                 return errors.New("transaction nout/value do not matches")
467         }
468         // Check that the witness program matches the p2ch on the p2sh-p2wsh transaction output
469         //federationRedeemScript := vmutil.CalculateContract(consensus.ActiveNetParams.FedpegXPubs, claimScript)
470         //scriptHash := crypto.Sha256(federationRedeemScript)
471         peginContractPrograms, err := pegin_contract.GetPeginContractPrograms(claimScript)
472         if err != nil {
473                 return err
474         }
475
476         scriptHash := crypto.Sha256(peginContractPrograms)
477         controlProg, err := vmutil.P2WSHProgram(scriptHash)
478         if err != nil {
479                 return err
480         }
481         if !bytes.Equal(rawTx.Outputs[prevout.Source.Position].ControlProgram, controlProg) {
482                 return errors.New("The output control program of transaction does not match the control program of the system's alliance contract")
483         }
484         return nil
485 }
486
487 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
488         if vs == nil {
489                 return errors.Wrap(ErrMissingField, "empty value source")
490         }
491         if vs.Ref == nil {
492                 return errors.Wrap(ErrMissingField, "missing ref on value source")
493         }
494         if vs.Value == nil || vs.Value.AssetId == nil {
495                 return errors.Wrap(ErrMissingField, "missing value on value source")
496         }
497
498         e, ok := vstate.tx.Entries[*vs.Ref]
499         if !ok {
500                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
501         }
502
503         vstate2 := *vstate
504         vstate2.entryID = *vs.Ref
505         if err := checkValid(&vstate2, e); err != nil {
506                 return errors.Wrap(err, "checking value source")
507         }
508
509         var dest *bc.ValueDestination
510         switch ref := e.(type) {
511         case *bc.Coinbase:
512                 if vs.Position != 0 {
513                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
514                 }
515                 dest = ref.WitnessDestination
516
517         case *bc.Issuance:
518                 if vs.Position != 0 {
519                         return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
520                 }
521                 dest = ref.WitnessDestination
522
523         case *bc.Spend:
524                 if vs.Position != 0 {
525                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
526                 }
527                 dest = ref.WitnessDestination
528
529         case *bc.Mux:
530                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
531                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
532                 }
533                 dest = ref.WitnessDestinations[vs.Position]
534         case *bc.Claim:
535                 if vs.Position != 0 {
536                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
537                 }
538                 dest = ref.WitnessDestination
539         default:
540                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
541         }
542
543         if dest.Ref == nil || *dest.Ref != vstate.entryID {
544                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
545         }
546
547         if dest.Position != vstate.sourcePos {
548                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
549         }
550
551         eq, err := dest.Value.Equal(vs.Value)
552         if err != nil {
553                 return errors.Sub(ErrMissingField, err)
554         }
555         if !eq {
556                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
557         }
558
559         return nil
560 }
561
562 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
563         if vd == nil {
564                 return errors.Wrap(ErrMissingField, "empty value destination")
565         }
566         if vd.Ref == nil {
567                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
568         }
569         if vd.Value == nil || vd.Value.AssetId == nil {
570                 return errors.Wrap(ErrMissingField, "missing value on value source")
571         }
572
573         e, ok := vs.tx.Entries[*vd.Ref]
574         if !ok {
575                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
576         }
577
578         var src *bc.ValueSource
579         switch ref := e.(type) {
580         case *bc.Output:
581                 if vd.Position != 0 {
582                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
583                 }
584                 src = ref.Source
585
586         case *bc.Retirement:
587                 if vd.Position != 0 {
588                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
589                 }
590                 src = ref.Source
591
592         case *bc.Mux:
593                 if vd.Position >= uint64(len(ref.Sources)) {
594                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
595                 }
596                 src = ref.Sources[vd.Position]
597
598         default:
599                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
600         }
601
602         if src.Ref == nil || *src.Ref != vs.entryID {
603                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
604         }
605
606         if src.Position != vs.destPos {
607                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
608         }
609
610         eq, err := src.Value.Equal(vd.Value)
611         if err != nil {
612                 return errors.Sub(ErrMissingField, err)
613         }
614         if !eq {
615                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
616         }
617
618         return nil
619 }
620
621 func checkStandardTx(tx *bc.Tx) error {
622         for _, id := range tx.GasInputIDs {
623                 spend, err := tx.Spend(id)
624                 if err != nil {
625                         return err
626                 }
627                 spentOutput, err := tx.Output(*spend.SpentOutputId)
628                 if err != nil {
629                         return err
630                 }
631
632                 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
633                         return ErrNotStandardTx
634                 }
635         }
636
637         for _, id := range tx.ResultIds {
638                 e, ok := tx.Entries[*id]
639                 if !ok {
640                         return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
641                 }
642
643                 output, ok := e.(*bc.Output)
644                 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
645                         continue
646                 }
647
648                 if !segwit.IsP2WScript(output.ControlProgram.Code) {
649                         return ErrNotStandardTx
650                 }
651         }
652         return nil
653 }
654
655 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
656         if tx.TimeRange == 0 {
657                 return nil
658         }
659
660         if tx.TimeRange < block.Height {
661                 return ErrBadTimeRange
662         }
663         return nil
664 }
665
666 // ValidateTx validates a transaction.
667 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
668         gasStatus := &GasState{GasValid: false}
669         if block.Version == 1 && tx.Version != 1 {
670                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
671         }
672         if tx.SerializedSize == 0 {
673                 return gasStatus, ErrWrongTransactionSize
674         }
675         if err := checkTimeRange(tx, block); err != nil {
676                 return gasStatus, err
677         }
678         if err := checkStandardTx(tx); err != nil {
679                 return gasStatus, err
680         }
681         vs := &validationState{
682                 block:     block,
683                 tx:        tx,
684                 entryID:   tx.ID,
685                 gasStatus: gasStatus,
686                 cache:     make(map[bc.Hash]error),
687         }
688         return vs.gasStatus, checkValid(vs, tx.TxHeader)
689 }