10 "github.com/vapor/consensus"
11 "github.com/vapor/consensus/segwit"
12 "github.com/vapor/crypto"
13 "github.com/vapor/errors"
14 "github.com/vapor/math/checked"
15 "github.com/vapor/protocol/bc"
16 "github.com/vapor/protocol/bc/types"
17 "github.com/vapor/protocol/vm"
18 "github.com/vapor/protocol/vm/vmutil"
19 "github.com/vapor/util"
22 // validate transaction error
24 ErrTxVersion = errors.New("invalid transaction version")
25 ErrWrongTransactionSize = errors.New("invalid transaction size")
26 ErrBadTimeRange = errors.New("invalid transaction time range")
27 ErrNotStandardTx = errors.New("not standard transaction")
28 ErrWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
29 ErrWrongCoinbaseAsset = errors.New("wrong coinbase assetID")
30 ErrCoinbaseArbitraryOversize = errors.New("coinbase arbitrary size is larger than limit")
31 ErrEmptyResults = errors.New("transaction has no results")
32 ErrMismatchedAssetID = errors.New("mismatched assetID")
33 ErrMismatchedPosition = errors.New("mismatched value source/dest position")
34 ErrMismatchedReference = errors.New("mismatched reference")
35 ErrMismatchedValue = errors.New("mismatched value")
36 ErrMissingField = errors.New("missing required field")
37 ErrNoSource = errors.New("no source for value")
38 ErrOverflow = errors.New("arithmetic overflow/underflow")
39 ErrPosition = errors.New("invalid source or destination position")
40 ErrUnbalanced = errors.New("unbalanced asset amount between input and output")
41 ErrOverGasCredit = errors.New("all gas credit has been spend")
42 ErrGasCalculate = errors.New("gas usage calculate got a math error")
45 // GasState record the gas usage status
46 type GasState struct {
54 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
56 return errors.Wrap(ErrGasCalculate, "input BTM is negative")
59 g.BTMValue = uint64(BTMValue)
62 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
63 return errors.Wrap(ErrGasCalculate, "setGas calc gas amount")
66 if g.GasLeft > consensus.MaxGasAmount {
67 g.GasLeft = consensus.MaxGasAmount
70 if g.StorageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
71 return errors.Wrap(ErrGasCalculate, "setGas calc tx storage gas")
76 func (g *GasState) setGasValid() error {
78 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.StorageGas); !ok || g.GasLeft < 0 {
79 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasLeft")
82 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.StorageGas); !ok {
83 return errors.Wrap(ErrGasCalculate, "setGasValid calc gasUsed")
90 func (g *GasState) updateUsage(gasLeft int64) error {
92 return errors.Wrap(ErrGasCalculate, "updateUsage input negative gas")
95 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
99 return errors.Wrap(ErrGasCalculate, "updateUsage calc gas diff")
102 if !g.GasValid && (g.GasUsed > consensus.DefaultGasCredit || g.StorageGas > g.GasLeft) {
103 return ErrOverGasCredit
108 // validationState contains the context that must propagate through
109 // the transaction graph when validating entries.
110 type validationState struct {
114 entryID bc.Hash // The ID of the nearest enclosing entry
115 sourcePos uint64 // The source position, for validate ValueSources
116 destPos uint64 // The destination position, for validate ValueDestinations
117 cache map[bc.Hash]error // Memoized per-entry validation results
120 func checkValid(vs *validationState, e bc.Entry) (err error) {
122 entryID := bc.EntryID(e)
123 if err, ok = vs.cache[entryID]; ok {
128 vs.cache[entryID] = err
131 switch e := e.(type) {
133 for i, resID := range e.ResultIds {
134 resultEntry := vs.tx.Entries[*resID]
137 if err = checkValid(&vs2, resultEntry); err != nil {
138 return errors.Wrapf(err, "checking result %d", i)
142 if e.Version == 1 && len(e.ResultIds) == 0 {
143 return ErrEmptyResults
147 parity := make(map[bc.AssetID]int64)
148 for i, src := range e.Sources {
149 if src.Value.Amount > math.MaxInt64 {
150 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
152 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
154 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])
156 parity[*src.Value.AssetId] = sum
159 for i, dest := range e.WitnessDestinations {
160 sum, ok := parity[*dest.Value.AssetId]
162 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
164 if dest.Value.Amount > math.MaxInt64 {
165 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
167 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
169 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)
171 parity[*dest.Value.AssetId] = diff
174 for assetID, amount := range parity {
175 if assetID == *consensus.BTMAssetID {
176 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
179 } else if amount != 0 {
180 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
184 for _, BTMInputID := range vs.tx.GasInputIDs {
185 e, ok := vs.tx.Entries[BTMInputID]
187 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
191 vs2.entryID = BTMInputID
192 if err := checkValid(&vs2, e); err != nil {
193 return errors.Wrap(err, "checking gas input")
197 for i, dest := range e.WitnessDestinations {
199 vs2.destPos = uint64(i)
200 if err = checkValidDest(&vs2, dest); err != nil {
201 return errors.Wrapf(err, "checking mux destination %d", i)
205 if len(vs.tx.GasInputIDs) > 0 {
206 if err := vs.gasStatus.setGasValid(); err != nil {
211 for i, src := range e.Sources {
213 vs2.sourcePos = uint64(i)
214 if err = checkValidSrc(&vs2, src); err != nil {
215 return errors.Wrapf(err, "checking mux source %d", i)
222 if err = checkValidSrc(&vs2, e.Source); err != nil {
223 return errors.Wrap(err, "checking output source")
229 if err = checkValidSrc(&vs2, e.Source); err != nil {
230 return errors.Wrap(err, "checking retirement source")
234 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
235 if computedAssetID != *e.Value.AssetId {
236 return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
239 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
241 return errors.Wrap(err, "checking issuance program")
243 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
249 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
250 return errors.Wrap(err, "checking issuance destination")
254 if e.SpentOutputId == nil {
255 return errors.Wrap(ErrMissingField, "spend without spent output ID")
257 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
259 return errors.Wrap(err, "getting spend prevout")
262 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
264 return errors.Wrap(err, "checking control program")
266 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
270 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
275 return errors.WithDetailf(
277 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
278 spentOutput.Source.Value.Amount,
279 spentOutput.Source.Value.AssetId.Bytes(),
280 e.WitnessDestination.Value.Amount,
281 e.WitnessDestination.Value.AssetId.Bytes(),
287 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
288 return errors.Wrap(err, "checking spend destination")
292 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
293 return ErrWrongCoinbaseTransaction
296 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
297 return ErrWrongCoinbaseAsset
300 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
301 return ErrCoinbaseArbitraryOversize
306 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
307 return errors.Wrap(err, "checking coinbase destination")
310 // special case for coinbase transaction, it's valid unit all the verify has been passed
311 vs.gasStatus.GasValid = true
314 if e.SpentOutputId == nil {
315 return errors.Wrap(ErrMissingField, "spend without spent output ID")
317 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
319 return errors.Wrap(err, "getting spend prevout")
321 stack := e.GetPeginwitness()
322 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
324 return errors.New("pegin-no-witness")
327 if IsValidPeginWitness(stack, *spentOutput) == nil {
328 return errors.New("PeginWitness invalid")
333 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
338 return errors.WithDetailf(
340 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
341 spentOutput.Source.Value.Amount,
342 spentOutput.Source.Value.AssetId.Bytes(),
343 e.WitnessDestination.Value.Amount,
344 e.WitnessDestination.Value.AssetId.Bytes(),
350 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
351 return errors.Wrap(err, "checking spend destination")
353 vs.gasStatus.GasValid = true
355 return fmt.Errorf("entry has unexpected type %T", e)
361 type MerkleBlock struct {
362 BlockHeader types.BlockHeader `json:"block_header"`
363 TxHashes []*bc.Hash `json:"tx_hashes"`
364 StatusHashes []*bc.Hash `json:"status_hashes"`
365 Flags []uint32 `json:"flags"`
366 MatchedTxIDs []*bc.Hash `json:"matched_tx_ids"`
369 func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
370 if len(peginWitness) != 5 {
371 return errors.New("peginWitness is error")
373 amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
377 if consensus.MoneyRange(amount) {
378 return errors.New("Amount out of range")
381 if len(peginWitness[1]) != 32 {
382 return errors.New("The length of gennesisBlockHash is not correct")
385 claimScript := peginWitness[2]
388 err = json.Unmarshal(peginWitness[3], &rawTx)
392 var merkleBlock MerkleBlock
393 err = json.Unmarshal(peginWitness[4], &merkleBlock)
399 for flag := range merkleBlock.Flags {
400 flags = append(flags, uint8(flag))
402 if !types.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, merkleBlock.BlockHeader.BlockCommitment.TransactionsMerkleRoot) {
403 return errors.New("Merkleblock validation failed")
405 var txHash bc.Hash = rawTx.ID
407 if !checkPeginTx(&rawTx, &prevout, amount, claimScript) {
408 return errors.New("check PeginTx fail")
411 // Check that the merkle proof corresponds to the txid
412 if txHash != *prevout.Source.Ref {
413 return errors.New("prevout hash don't match")
415 // Check the genesis block corresponds to a valid peg (only one for now)
416 if !bytes.Equal(peginWitness[1], []byte(consensus.ActiveNetParams.ParentGenesisBlockHash)) {
417 return errors.New("ParentGenesisBlockHash don't match")
419 // TODO Finally, validate peg-in via rpc call
421 if util.ValidatePegin {
422 if err := util.IsConfirmedBytomBlock(merkleBlock.BlockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
430 func checkPeginTx(rawTx *types.Tx, prevout *bc.Output, claimAmount uint64, claimScript []byte) bool {
431 // Check that transaction matches txid
432 if rawTx.ID != *prevout.Source.Ref {
435 // Check the transaction nout/value matches
436 amount := rawTx.Outputs[prevout.Source.Position].Amount
437 if claimAmount != amount {
440 // Check that the witness program matches the p2ch on the p2sh-p2wsh transaction output
441 federationRedeemScript := vmutil.CalculateContract(consensus.ActiveNetParams.FedpegXPubs, claimScript)
442 scriptHash := crypto.Sha256(federationRedeemScript)
443 controlProg, err := vmutil.P2WSHProgram(scriptHash)
447 if bytes.Equal(rawTx.Outputs[prevout.Source.Position].ControlProgram, controlProg) {
453 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
455 return errors.Wrap(ErrMissingField, "empty value source")
458 return errors.Wrap(ErrMissingField, "missing ref on value source")
460 if vs.Value == nil || vs.Value.AssetId == nil {
461 return errors.Wrap(ErrMissingField, "missing value on value source")
464 e, ok := vstate.tx.Entries[*vs.Ref]
466 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
470 vstate2.entryID = *vs.Ref
471 if err := checkValid(&vstate2, e); err != nil {
472 return errors.Wrap(err, "checking value source")
475 var dest *bc.ValueDestination
476 switch ref := e.(type) {
478 if vs.Position != 0 {
479 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
481 dest = ref.WitnessDestination
484 if vs.Position != 0 {
485 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
487 dest = ref.WitnessDestination
490 if vs.Position != 0 {
491 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
493 dest = ref.WitnessDestination
496 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
497 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
499 dest = ref.WitnessDestinations[vs.Position]
501 if vs.Position != 0 {
502 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
504 dest = ref.WitnessDestination
506 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
509 if dest.Ref == nil || *dest.Ref != vstate.entryID {
510 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
513 if dest.Position != vstate.sourcePos {
514 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
517 eq, err := dest.Value.Equal(vs.Value)
519 return errors.Sub(ErrMissingField, err)
522 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
528 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
530 return errors.Wrap(ErrMissingField, "empty value destination")
533 return errors.Wrap(ErrMissingField, "missing ref on value destination")
535 if vd.Value == nil || vd.Value.AssetId == nil {
536 return errors.Wrap(ErrMissingField, "missing value on value source")
539 e, ok := vs.tx.Entries[*vd.Ref]
541 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
544 var src *bc.ValueSource
545 switch ref := e.(type) {
547 if vd.Position != 0 {
548 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
553 if vd.Position != 0 {
554 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
559 if vd.Position >= uint64(len(ref.Sources)) {
560 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
562 src = ref.Sources[vd.Position]
565 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
568 if src.Ref == nil || *src.Ref != vs.entryID {
569 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
572 if src.Position != vs.destPos {
573 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
576 eq, err := src.Value.Equal(vd.Value)
578 return errors.Sub(ErrMissingField, err)
581 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
587 func checkStandardTx(tx *bc.Tx) error {
588 for _, id := range tx.GasInputIDs {
589 spend, err := tx.Spend(id)
593 spentOutput, err := tx.Output(*spend.SpentOutputId)
598 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
599 return ErrNotStandardTx
603 for _, id := range tx.ResultIds {
604 e, ok := tx.Entries[*id]
606 return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
609 output, ok := e.(*bc.Output)
610 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
614 if !segwit.IsP2WScript(output.ControlProgram.Code) {
615 return ErrNotStandardTx
621 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
622 if tx.TimeRange == 0 {
626 if tx.TimeRange < block.Height {
627 return ErrBadTimeRange
632 // ValidateTx validates a transaction.
633 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
634 gasStatus := &GasState{GasValid: false}
635 if block.Version == 1 && tx.Version != 1 {
636 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
638 if tx.SerializedSize == 0 {
639 return gasStatus, ErrWrongTransactionSize
641 if err := checkTimeRange(tx, block); err != nil {
642 return gasStatus, err
644 if err := checkStandardTx(tx); err != nil {
645 return gasStatus, err
647 vs := &validationState{
651 gasStatus: gasStatus,
652 cache: make(map[bc.Hash]error),
654 return vs.gasStatus, checkValid(vs, tx.TxHeader)