OSDN Git Service

Merge pull request #21 from Bytom/dev_modify_pegin_address_to_contract
[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/bytom"
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     []*bytom.Hash `json:"tx_hashes"`
366         StatusHashes []*bytom.Hash `json:"status_hashes"`
367         Flags        []uint32      `json:"flags"`
368         MatchedTxIDs []*bytom.Hash `json:"matched_tx_ids"`
369 }
370
371 func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
372         assetID := bytom.AssetID{}
373         assetID.V0 = prevout.Source.Value.AssetId.GetV0()
374         assetID.V1 = prevout.Source.Value.AssetId.GetV1()
375         assetID.V2 = prevout.Source.Value.AssetId.GetV2()
376         assetID.V3 = prevout.Source.Value.AssetId.GetV3()
377         //bytomPrevout.Source.Value.AssetId = &assetId
378
379         sourceID := bytom.Hash{}
380         sourceID.V0 = prevout.Source.Ref.GetV0()
381         sourceID.V1 = prevout.Source.Ref.GetV1()
382         sourceID.V2 = prevout.Source.Ref.GetV2()
383         sourceID.V3 = prevout.Source.Ref.GetV3()
384
385         assetAmount := &bytom.AssetAmount{
386                 AssetId: &assetID,
387                 Amount:  prevout.Source.Value.Amount,
388         }
389
390         src := &bytom.ValueSource{
391                 Ref:      &sourceID,
392                 Value:    assetAmount,
393                 Position: prevout.Source.Position,
394         }
395         prog := &bytom.Program{prevout.ControlProgram.VmVersion, prevout.ControlProgram.Code}
396         bytomPrevout := bytom.NewOutput(src, prog, prevout.Source.Position)
397
398         if len(peginWitness) != 5 {
399                 return errors.New("peginWitness is error")
400         }
401         amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
402         if err != nil {
403                 return err
404         }
405         if !consensus.MoneyRange(amount) {
406                 return errors.New("Amount out of range")
407         }
408
409         if len(peginWitness[1]) != 64 {
410                 return errors.New("The length of gennesisBlockHash is not correct")
411         }
412
413         claimScript := peginWitness[2]
414
415         rawTx := &bytomtypes.Tx{}
416         err = rawTx.UnmarshalText(peginWitness[3])
417         if err != nil {
418                 return err
419         }
420
421         merkleBlock := &MerkleBlock{}
422         err = json.Unmarshal(peginWitness[4], merkleBlock)
423         if err != nil {
424                 return err
425         }
426         // proof验证
427         var flags []uint8
428         for flag := range merkleBlock.Flags {
429                 flags = append(flags, uint8(flag))
430         }
431         blockHeader := &bytomtypes.BlockHeader{}
432         if err = blockHeader.UnmarshalText(merkleBlock.BlockHeader); err != nil {
433                 return err
434         }
435
436         if !bytomtypes.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, blockHeader.BlockCommitment.TransactionsMerkleRoot) {
437                 return errors.New("Merkleblock validation failed")
438         }
439
440         // 交易进行验证
441         if err = checkPeginTx(rawTx, bytomPrevout, amount, claimScript); err != nil {
442                 return err
443         }
444
445         // Check the genesis block corresponds to a valid peg (only one for now)
446         if !bytes.Equal(peginWitness[1], []byte(consensus.ActiveNetParams.ParentGenesisBlockHash)) {
447                 return errors.New("ParentGenesisBlockHash don't match")
448         }
449         // TODO Finally, validate peg-in via rpc call
450
451         if util.ValidatePegin {
452                 if err := util.IsConfirmedBytomBlock(blockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
453                         return err
454                 }
455         }
456
457         return nil
458 }
459
460 func checkPeginTx(rawTx *bytomtypes.Tx, prevout *bytom.Output, claimAmount uint64, claimScript []byte) error {
461         // Check the transaction nout/value matches
462         amount := rawTx.Outputs[prevout.Source.Position].Amount
463         if claimAmount != amount {
464                 return errors.New("transaction nout/value do not matches")
465         }
466         // Check that the witness program matches the p2ch on the p2sh-p2wsh transaction output
467         //federationRedeemScript := vmutil.CalculateContract(consensus.ActiveNetParams.FedpegXPubs, claimScript)
468         //scriptHash := crypto.Sha256(federationRedeemScript)
469         peginContractPrograms, err := pegin_contract.GetPeginContractPrograms(claimScript)
470         if err != nil {
471                 return err
472         }
473
474         scriptHash := crypto.Sha256(peginContractPrograms)
475         controlProg, err := vmutil.P2WSHProgram(scriptHash)
476         if err != nil {
477                 return err
478         }
479         if !bytes.Equal(rawTx.Outputs[prevout.Source.Position].ControlProgram, controlProg) {
480                 return errors.New("The output control program of transaction does not match the control program of the system's alliance contract")
481         }
482         return nil
483 }
484
485 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
486         if vs == nil {
487                 return errors.Wrap(ErrMissingField, "empty value source")
488         }
489         if vs.Ref == nil {
490                 return errors.Wrap(ErrMissingField, "missing ref on value source")
491         }
492         if vs.Value == nil || vs.Value.AssetId == nil {
493                 return errors.Wrap(ErrMissingField, "missing value on value source")
494         }
495
496         e, ok := vstate.tx.Entries[*vs.Ref]
497         if !ok {
498                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
499         }
500
501         vstate2 := *vstate
502         vstate2.entryID = *vs.Ref
503         if err := checkValid(&vstate2, e); err != nil {
504                 return errors.Wrap(err, "checking value source")
505         }
506
507         var dest *bc.ValueDestination
508         switch ref := e.(type) {
509         case *bc.Coinbase:
510                 if vs.Position != 0 {
511                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
512                 }
513                 dest = ref.WitnessDestination
514
515         case *bc.Issuance:
516                 if vs.Position != 0 {
517                         return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
518                 }
519                 dest = ref.WitnessDestination
520
521         case *bc.Spend:
522                 if vs.Position != 0 {
523                         return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
524                 }
525                 dest = ref.WitnessDestination
526
527         case *bc.Mux:
528                 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
529                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
530                 }
531                 dest = ref.WitnessDestinations[vs.Position]
532         case *bc.Claim:
533                 if vs.Position != 0 {
534                         return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
535                 }
536                 dest = ref.WitnessDestination
537         default:
538                 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
539         }
540
541         if dest.Ref == nil || *dest.Ref != vstate.entryID {
542                 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
543         }
544
545         if dest.Position != vstate.sourcePos {
546                 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
547         }
548
549         eq, err := dest.Value.Equal(vs.Value)
550         if err != nil {
551                 return errors.Sub(ErrMissingField, err)
552         }
553         if !eq {
554                 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
555         }
556
557         return nil
558 }
559
560 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
561         if vd == nil {
562                 return errors.Wrap(ErrMissingField, "empty value destination")
563         }
564         if vd.Ref == nil {
565                 return errors.Wrap(ErrMissingField, "missing ref on value destination")
566         }
567         if vd.Value == nil || vd.Value.AssetId == nil {
568                 return errors.Wrap(ErrMissingField, "missing value on value source")
569         }
570
571         e, ok := vs.tx.Entries[*vd.Ref]
572         if !ok {
573                 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
574         }
575
576         var src *bc.ValueSource
577         switch ref := e.(type) {
578         case *bc.Output:
579                 if vd.Position != 0 {
580                         return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
581                 }
582                 src = ref.Source
583
584         case *bc.Retirement:
585                 if vd.Position != 0 {
586                         return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
587                 }
588                 src = ref.Source
589
590         case *bc.Mux:
591                 if vd.Position >= uint64(len(ref.Sources)) {
592                         return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
593                 }
594                 src = ref.Sources[vd.Position]
595
596         default:
597                 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
598         }
599
600         if src.Ref == nil || *src.Ref != vs.entryID {
601                 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
602         }
603
604         if src.Position != vs.destPos {
605                 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
606         }
607
608         eq, err := src.Value.Equal(vd.Value)
609         if err != nil {
610                 return errors.Sub(ErrMissingField, err)
611         }
612         if !eq {
613                 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
614         }
615
616         return nil
617 }
618
619 func checkStandardTx(tx *bc.Tx) error {
620         for _, id := range tx.GasInputIDs {
621                 spend, err := tx.Spend(id)
622                 if err != nil {
623                         return err
624                 }
625                 spentOutput, err := tx.Output(*spend.SpentOutputId)
626                 if err != nil {
627                         return err
628                 }
629
630                 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
631                         return ErrNotStandardTx
632                 }
633         }
634
635         for _, id := range tx.ResultIds {
636                 e, ok := tx.Entries[*id]
637                 if !ok {
638                         return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
639                 }
640
641                 output, ok := e.(*bc.Output)
642                 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
643                         continue
644                 }
645
646                 if !segwit.IsP2WScript(output.ControlProgram.Code) {
647                         return ErrNotStandardTx
648                 }
649         }
650         return nil
651 }
652
653 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
654         if tx.TimeRange == 0 {
655                 return nil
656         }
657
658         if tx.TimeRange < block.Height {
659                 return ErrBadTimeRange
660         }
661         return nil
662 }
663
664 // ValidateTx validates a transaction.
665 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
666         gasStatus := &GasState{GasValid: false}
667         if block.Version == 1 && tx.Version != 1 {
668                 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
669         }
670         if tx.SerializedSize == 0 {
671                 return gasStatus, ErrWrongTransactionSize
672         }
673         if err := checkTimeRange(tx, block); err != nil {
674                 return gasStatus, err
675         }
676         if err := checkStandardTx(tx); err != nil {
677                 return gasStatus, err
678         }
679         vs := &validationState{
680                 block:     block,
681                 tx:        tx,
682                 entryID:   tx.ID,
683                 gasStatus: gasStatus,
684                 cache:     make(map[bc.Hash]error),
685         }
686         return vs.gasStatus, checkValid(vs, tx.TxHeader)
687 }