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"
24 // validate transaction error
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")
47 // GasState record the gas usage status
48 type GasState struct {
56 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
58 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
61 g.BTMValue = uint64(BTMValue)
64 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
65 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
68 if g.GasLeft > consensus.MaxGasAmount {
69 g.GasLeft = consensus.MaxGasAmount
72 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
73 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
78 func (g *GasState) setGasValid() error {
80 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
81 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
84 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
85 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
92 func (g *GasState) updateUsage(gasLeft int64) error {
94 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
97 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
101 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
104 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
105 return ErrOverGasCredit
110 // validationState contains the context that must propagate through
111 // the transaction graph when validating entries.
112 type validationState struct {
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
122 func checkValid(vs *validationState, e bc.Entry) (err error) {
124 entryID := bc.EntryID(e)
125 if err, ok = vs.cache[entryID]; ok {
130 vs.cache[entryID] = err
133 switch e := e.(type) {
135 for i, resID := range e.ResultIds {
136 resultEntry := vs.tx.Entries[*resID]
139 if err = checkValid(&vs2, resultEntry); err != nil {
140 return errors.Wrapf(err, "checking result %d", i)
144 if e.Version == 1 && len(e.ResultIds) == 0 {
145 return ErrEmptyResults
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)
154 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
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])
158 parity[*src.Value.AssetId] = sum
161 for i, dest := range e.WitnessDestinations {
162 sum, ok := parity[*dest.Value.AssetId]
164 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
166 if dest.Value.Amount > math.MaxInt64 {
167 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
169 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
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)
173 parity[*dest.Value.AssetId] = diff
176 for assetID, amount := range parity {
177 if assetID == *consensus.BTMAssetID {
178 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
181 } else if amount != 0 {
182 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
186 for _, BTMInputID := range vs.tx.GasInputIDs {
187 e, ok := vs.tx.Entries[BTMInputID]
189 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
193 vs2.entryID = BTMInputID
194 if err := checkValid(&vs2, e); err != nil {
195 return errors.Wrap(err, "checking gas input")
199 for i, dest := range e.WitnessDestinations {
201 vs2.destPos = uint64(i)
202 if err = checkValidDest(&vs2, dest); err != nil {
203 return errors.Wrapf(err, "checking mux destination %d", i)
207 if len(vs.tx.GasInputIDs) > 0 {
208 if err := vs.gasStatus.setGasValid(); err != nil {
213 for i, src := range e.Sources {
215 vs2.sourcePos = uint64(i)
216 if err = checkValidSrc(&vs2, src); err != nil {
217 return errors.Wrapf(err, "checking mux source %d", i)
224 if err = checkValidSrc(&vs2, e.Source); err != nil {
225 return errors.Wrap(err, "checking output source")
231 if err = checkValidSrc(&vs2, e.Source); err != nil {
232 return errors.Wrap(err, "checking retirement source")
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())
241 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
243 return errors.Wrap(err, "checking issuance program")
245 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
251 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
252 return errors.Wrap(err, "checking issuance destination")
256 if e.SpentOutputId == nil {
257 return errors.Wrap(ErrMissingField, "spend without spent output ID")
259 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
261 return errors.Wrap(err, "getting spend prevout")
264 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
266 return errors.Wrap(err, "checking control program")
268 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
272 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
277 return errors.WithDetailf(
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(),
289 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
290 return errors.Wrap(err, "checking spend destination")
294 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
295 return ErrWrongCoinbaseTransaction
298 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
299 return ErrWrongCoinbaseAsset
302 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
303 return ErrCoinbaseArbitraryOversize
308 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
309 return errors.Wrap(err, "checking coinbase destination")
312 // special case for coinbase transaction, it's valid unit all the verify has been passed
313 vs.gasStatus.GasValid = true
316 if e.SpentOutputId == nil {
317 return errors.Wrap(ErrMissingField, "spend without spent output ID")
319 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
321 return errors.Wrap(err, "getting spend prevout")
323 stack := e.GetPeginwitness()
324 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
326 return errors.New("pegin-no-witness")
329 if err := IsValidPeginWitness(stack, *spentOutput); err != nil {
333 // 判断cliam tx的输入是否已经被用
335 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
340 return errors.WithDetailf(
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(),
352 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
353 return errors.Wrap(err, "checking spend destination")
355 vs.gasStatus.GasValid = true
357 return fmt.Errorf("entry has unexpected type %T", e)
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"`
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
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()
385 assetAmount := &bytom.AssetAmount{
387 Amount: prevout.Source.Value.Amount,
390 src := &bytom.ValueSource{
393 Position: prevout.Source.Position,
395 prog := &bytom.Program{prevout.ControlProgram.VmVersion, prevout.ControlProgram.Code}
396 bytomPrevout := bytom.NewOutput(src, prog, prevout.Source.Position)
398 if len(peginWitness) != 5 {
399 return errors.New("peginWitness is error")
401 amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
405 if !consensus.MoneyRange(amount) {
406 return errors.New("Amount out of range")
409 if len(peginWitness[1]) != 64 {
410 return errors.New("The length of gennesisBlockHash is not correct")
413 claimScript := peginWitness[2]
415 rawTx := &bytomtypes.Tx{}
416 err = rawTx.UnmarshalText(peginWitness[3])
421 merkleBlock := &MerkleBlock{}
422 err = json.Unmarshal(peginWitness[4], merkleBlock)
428 for flag := range merkleBlock.Flags {
429 flags = append(flags, uint8(flag))
431 blockHeader := &bytomtypes.BlockHeader{}
432 if err = blockHeader.UnmarshalText(merkleBlock.BlockHeader); err != nil {
436 if !bytomtypes.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, blockHeader.BlockCommitment.TransactionsMerkleRoot) {
437 return errors.New("Merkleblock validation failed")
441 if err = checkPeginTx(rawTx, bytomPrevout, amount, claimScript); err != nil {
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")
449 // TODO Finally, validate peg-in via rpc call
451 if util.ValidatePegin {
452 if err := util.IsConfirmedBytomBlock(blockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
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")
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)
474 scriptHash := crypto.Sha256(peginContractPrograms)
475 controlProg, err := vmutil.P2WSHProgram(scriptHash)
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")
485 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
487 return errors.Wrap(ErrMissingField, "empty value source")
490 return errors.Wrap(ErrMissingField, "missing ref on value source")
492 if vs.Value == nil || vs.Value.AssetId == nil {
493 return errors.Wrap(ErrMissingField, "missing value on value source")
496 e, ok := vstate.tx.Entries[*vs.Ref]
498 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
502 vstate2.entryID = *vs.Ref
503 if err := checkValid(&vstate2, e); err != nil {
504 return errors.Wrap(err, "checking value source")
507 var dest *bc.ValueDestination
508 switch ref := e.(type) {
510 if vs.Position != 0 {
511 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
513 dest = ref.WitnessDestination
516 if vs.Position != 0 {
517 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
519 dest = ref.WitnessDestination
522 if vs.Position != 0 {
523 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
525 dest = ref.WitnessDestination
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))
531 dest = ref.WitnessDestinations[vs.Position]
533 if vs.Position != 0 {
534 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
536 dest = ref.WitnessDestination
538 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
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())
545 if dest.Position != vstate.sourcePos {
546 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
549 eq, err := dest.Value.Equal(vs.Value)
551 return errors.Sub(ErrMissingField, err)
554 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
560 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
562 return errors.Wrap(ErrMissingField, "empty value destination")
565 return errors.Wrap(ErrMissingField, "missing ref on value destination")
567 if vd.Value == nil || vd.Value.AssetId == nil {
568 return errors.Wrap(ErrMissingField, "missing value on value source")
571 e, ok := vs.tx.Entries[*vd.Ref]
573 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
576 var src *bc.ValueSource
577 switch ref := e.(type) {
579 if vd.Position != 0 {
580 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
585 if vd.Position != 0 {
586 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
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))
594 src = ref.Sources[vd.Position]
597 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
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())
604 if src.Position != vs.destPos {
605 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
608 eq, err := src.Value.Equal(vd.Value)
610 return errors.Sub(ErrMissingField, err)
613 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
619 func checkStandardTx(tx *bc.Tx) error {
620 for _, id := range tx.GasInputIDs {
621 spend, err := tx.Spend(id)
625 spentOutput, err := tx.Output(*spend.SpentOutputId)
630 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
631 return ErrNotStandardTx
635 for _, id := range tx.ResultIds {
636 e, ok := tx.Entries[*id]
638 return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
641 output, ok := e.(*bc.Output)
642 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
646 if !segwit.IsP2WScript(output.ControlProgram.Code) {
647 return ErrNotStandardTx
653 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
654 if tx.TimeRange == 0 {
658 if tx.TimeRange < block.Height {
659 return ErrBadTimeRange
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)
670 if tx.SerializedSize == 0 {
671 return gasStatus, ErrWrongTransactionSize
673 if err := checkTimeRange(tx, block); err != nil {
674 return gasStatus, err
676 if err := checkStandardTx(tx); err != nil {
677 return gasStatus, err
679 vs := &validationState{
683 gasStatus: gasStatus,
684 cache: make(map[bc.Hash]error),
686 return vs.gasStatus, checkValid(vs, tx.TxHeader)