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"
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 []*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"`
371 func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
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
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()
387 assetAmount := &bc.AssetAmount{
388 AssetId: prevout.Source.Value.AssetId,
389 Amount: prevout.Source.Value.Amount,
392 src := &bc.ValueSource{
393 Ref: prevout.Source.Ref,
395 Position: prevout.Source.Position,
397 prog := &bc.Program{prevout.ControlProgram.VmVersion, prevout.ControlProgram.Code}
398 bytomPrevout := bc.NewOutput(src, prog, prevout.Source.Position)
400 if len(peginWitness) != 5 {
401 return errors.New("peginWitness is error")
403 amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
407 if !consensus.MoneyRange(amount) {
408 return errors.New("Amount out of range")
411 if len(peginWitness[1]) != 64 {
412 return errors.New("The length of gennesisBlockHash is not correct")
415 claimScript := peginWitness[2]
417 rawTx := &bytomtypes.Tx{}
418 err = rawTx.UnmarshalText(peginWitness[3])
423 merkleBlock := &MerkleBlock{}
424 err = json.Unmarshal(peginWitness[4], merkleBlock)
430 for flag := range merkleBlock.Flags {
431 flags = append(flags, uint8(flag))
433 blockHeader := &bytomtypes.BlockHeader{}
434 if err = blockHeader.UnmarshalText(merkleBlock.BlockHeader); err != nil {
438 if !types.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, blockHeader.BlockCommitment.TransactionsMerkleRoot) {
439 return errors.New("Merkleblock validation failed")
443 if err = checkPeginTx(rawTx, bytomPrevout, amount, claimScript); err != nil {
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")
451 // TODO Finally, validate peg-in via rpc call
453 if util.ValidatePegin {
454 if err := util.IsConfirmedBytomBlock(blockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
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")
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)
476 scriptHash := crypto.Sha256(peginContractPrograms)
477 controlProg, err := vmutil.P2WSHProgram(scriptHash)
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")
487 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
489 return errors.Wrap(ErrMissingField, "empty value source")
492 return errors.Wrap(ErrMissingField, "missing ref on value source")
494 if vs.Value == nil || vs.Value.AssetId == nil {
495 return errors.Wrap(ErrMissingField, "missing value on value source")
498 e, ok := vstate.tx.Entries[*vs.Ref]
500 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
504 vstate2.entryID = *vs.Ref
505 if err := checkValid(&vstate2, e); err != nil {
506 return errors.Wrap(err, "checking value source")
509 var dest *bc.ValueDestination
510 switch ref := e.(type) {
512 if vs.Position != 0 {
513 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
515 dest = ref.WitnessDestination
518 if vs.Position != 0 {
519 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
521 dest = ref.WitnessDestination
524 if vs.Position != 0 {
525 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
527 dest = ref.WitnessDestination
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))
533 dest = ref.WitnessDestinations[vs.Position]
535 if vs.Position != 0 {
536 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
538 dest = ref.WitnessDestination
540 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
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())
547 if dest.Position != vstate.sourcePos {
548 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
551 eq, err := dest.Value.Equal(vs.Value)
553 return errors.Sub(ErrMissingField, err)
556 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
562 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
564 return errors.Wrap(ErrMissingField, "empty value destination")
567 return errors.Wrap(ErrMissingField, "missing ref on value destination")
569 if vd.Value == nil || vd.Value.AssetId == nil {
570 return errors.Wrap(ErrMissingField, "missing value on value source")
573 e, ok := vs.tx.Entries[*vd.Ref]
575 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
578 var src *bc.ValueSource
579 switch ref := e.(type) {
581 if vd.Position != 0 {
582 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
587 if vd.Position != 0 {
588 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
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))
596 src = ref.Sources[vd.Position]
599 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
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())
606 if src.Position != vs.destPos {
607 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
610 eq, err := src.Value.Equal(vd.Value)
612 return errors.Sub(ErrMissingField, err)
615 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
621 func checkStandardTx(tx *bc.Tx) error {
622 for _, id := range tx.GasInputIDs {
623 spend, err := tx.Spend(id)
627 spentOutput, err := tx.Output(*spend.SpentOutputId)
632 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
633 return ErrNotStandardTx
637 for _, id := range tx.ResultIds {
638 e, ok := tx.Entries[*id]
640 return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
643 output, ok := e.(*bc.Output)
644 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
648 if !segwit.IsP2WScript(output.ControlProgram.Code) {
649 return ErrNotStandardTx
655 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
656 if tx.TimeRange == 0 {
660 if tx.TimeRange < block.Height {
661 return ErrBadTimeRange
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)
672 if tx.SerializedSize == 0 {
673 return gasStatus, ErrWrongTransactionSize
675 if err := checkTimeRange(tx, block); err != nil {
676 return gasStatus, err
678 if err := checkStandardTx(tx); err != nil {
679 return gasStatus, err
681 vs := &validationState{
685 gasStatus: gasStatus,
686 cache: make(map[bc.Hash]error),
688 return vs.gasStatus, checkValid(vs, tx.TxHeader)