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 e, ok := vs.tx.Entries[*src.Ref]
153 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", *src.Ref)
161 if src.Value.Amount > math.MaxInt64 {
162 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", src.Value.Amount)
164 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
166 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])
168 parity[*src.Value.AssetId] = sum
171 for i, dest := range e.WitnessDestinations {
172 sum, ok := parity[*dest.Value.AssetId]
174 return errors.WithDetailf(ErrNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
176 if dest.Value.Amount > math.MaxInt64 {
177 return errors.WithDetailf(ErrOverflow, "amount %d exceeds maximum value 2^63", dest.Value.Amount)
179 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
181 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)
183 parity[*dest.Value.AssetId] = diff
186 for assetID, amount := range parity {
187 if assetID == *consensus.BTMAssetID {
188 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
191 } else if amount != 0 {
192 return errors.WithDetailf(ErrUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
196 for _, BTMInputID := range vs.tx.GasInputIDs {
197 e, ok := vs.tx.Entries[BTMInputID]
199 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
202 vs2.entryID = BTMInputID
203 if err := checkValid(&vs2, e); err != nil {
204 return errors.Wrap(err, "checking gas input")
208 for i, dest := range e.WitnessDestinations {
210 vs2.destPos = uint64(i)
211 if err = checkValidDest(&vs2, dest); err != nil {
212 return errors.Wrapf(err, "checking mux destination %d", i)
216 if len(vs.tx.GasInputIDs) > 0 {
217 if err := vs.gasStatus.setGasValid(); err != nil {
222 for i, src := range e.Sources {
224 vs2.sourcePos = uint64(i)
225 if err = checkValidSrc(&vs2, src); err != nil {
226 return errors.Wrapf(err, "checking mux source %d", i)
233 if err = checkValidSrc(&vs2, e.Source); err != nil {
234 return errors.Wrap(err, "checking output source")
240 if err = checkValidSrc(&vs2, e.Source); err != nil {
241 return errors.Wrap(err, "checking retirement source")
245 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
246 if computedAssetID != *e.Value.AssetId {
247 return errors.WithDetailf(ErrMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
250 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
252 return errors.Wrap(err, "checking issuance program")
254 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
260 if err = checkValidDest(&destVS, e.WitnessDestination); err != nil {
261 return errors.Wrap(err, "checking issuance destination")
265 if e.SpentOutputId == nil {
266 return errors.Wrap(ErrMissingField, "spend without spent output ID")
268 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
270 return errors.Wrap(err, "getting spend prevout")
272 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
274 return errors.Wrap(err, "checking control program")
276 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
280 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
285 return errors.WithDetailf(
287 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
288 spentOutput.Source.Value.Amount,
289 spentOutput.Source.Value.AssetId.Bytes(),
290 e.WitnessDestination.Value.Amount,
291 e.WitnessDestination.Value.AssetId.Bytes(),
297 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
298 return errors.Wrap(err, "checking spend destination")
302 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
303 return ErrWrongCoinbaseTransaction
306 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
307 return ErrWrongCoinbaseAsset
310 if e.Arbitrary != nil && len(e.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
311 return ErrCoinbaseArbitraryOversize
316 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
317 return errors.Wrap(err, "checking coinbase destination")
320 // special case for coinbase transaction, it's valid unit all the verify has been passed
321 vs.gasStatus.GasValid = true
324 if e.SpentOutputId == nil {
325 return errors.Wrap(ErrMissingField, "spend without spent output ID")
327 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
329 return errors.Wrap(err, "getting spend prevout")
331 stack := e.GetPeginwitness()
332 if len(stack) < 5 || stack[1] == nil || spentOutput.Source == nil {
334 return errors.New("pegin-no-witness")
337 if err := IsValidPeginWitness(stack, *spentOutput); err != nil {
341 // 判断cliam tx的输入是否已经被用
343 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
348 return errors.WithDetailf(
350 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
351 spentOutput.Source.Value.Amount,
352 spentOutput.Source.Value.AssetId.Bytes(),
353 e.WitnessDestination.Value.Amount,
354 e.WitnessDestination.Value.AssetId.Bytes(),
360 if err = checkValidDest(&vs2, e.WitnessDestination); err != nil {
361 return errors.Wrap(err, "checking spend destination")
363 vs.gasStatus.GasValid = true
365 //fmt.Printf("kkkkkkkkkkkkkkkkkkkkkkkkkkk %T\n", e)
367 return fmt.Errorf("entry has unexpected type %T", e)
373 type MerkleBlock struct {
374 BlockHeader []byte `json:"block_header"`
375 TxHashes []*bc.Hash `json:"tx_hashes"`
376 StatusHashes []*bc.Hash `json:"status_hashes"`
377 Flags []uint32 `json:"flags"`
378 MatchedTxIDs []*bc.Hash `json:"matched_tx_ids"`
381 func IsValidPeginWitness(peginWitness [][]byte, prevout bc.Output) (err error) {
383 assetAmount := &bc.AssetAmount{
384 AssetId: prevout.Source.Value.AssetId,
385 Amount: prevout.Source.Value.Amount,
388 src := &bc.ValueSource{
389 Ref: prevout.Source.Ref,
391 Position: prevout.Source.Position,
393 prog := &bc.Program{prevout.ControlProgram.VmVersion, prevout.ControlProgram.Code}
394 bytomPrevout := bc.NewOutput(src, prog, prevout.Source.Position)
396 if len(peginWitness) != 5 {
397 return errors.New("peginWitness is error")
399 amount, err := strconv.ParseUint(string(peginWitness[0]), 10, 64)
403 if !consensus.MoneyRange(amount) {
404 return errors.New("Amount out of range")
407 if len(peginWitness[1]) != 32 {
408 return errors.New("The length of gennesisBlockHash is not correct")
411 claimScript := peginWitness[2]
413 rawTx := &bytomtypes.Tx{}
414 err = rawTx.UnmarshalText(peginWitness[3])
419 merkleBlock := &MerkleBlock{}
420 err = json.Unmarshal(peginWitness[4], merkleBlock)
426 for flag := range merkleBlock.Flags {
427 flags = append(flags, uint8(flag))
429 blockHeader := &bytomtypes.BlockHeader{}
430 if err = blockHeader.UnmarshalText(merkleBlock.BlockHeader); err != nil {
434 if !types.ValidateTxMerkleTreeProof(merkleBlock.TxHashes, flags, merkleBlock.MatchedTxIDs, blockHeader.BlockCommitment.TransactionsMerkleRoot) {
435 return errors.New("Merkleblock validation failed")
439 if err = checkPeginTx(rawTx, bytomPrevout, amount, claimScript); err != nil {
443 b.UnmarshalText(peginWitness[1])
444 // Check the genesis block corresponds to a valid peg (only one for now)
445 if b.String() != consensus.ActiveNetParams.ParentGenesisBlockHash {
446 return errors.New("ParentGenesisBlockHash don't match")
448 // TODO Finally, validate peg-in via rpc call
450 if util.ValidatePegin {
451 if err := util.IsConfirmedBytomBlock(blockHeader.Height, consensus.ActiveNetParams.PeginMinDepth); err != nil {
459 func checkPeginTx(rawTx *bytomtypes.Tx, prevout *bc.Output, claimAmount uint64, claimScript []byte) error {
460 // Check the transaction nout/value matches
461 amount := rawTx.Outputs[prevout.Source.Position].Amount
462 if claimAmount != amount {
463 return errors.New("transaction nout/value do not matches")
465 // Check that the witness program matches the p2ch on the p2sh-p2wsh transaction output
466 //federationRedeemScript := vmutil.CalculateContract(consensus.ActiveNetParams.FedpegXPubs, claimScript)
467 //scriptHash := crypto.Sha256(federationRedeemScript)
468 peginContractPrograms, err := pegin_contract.GetPeginContractPrograms(claimScript)
473 scriptHash := crypto.Sha256(peginContractPrograms)
474 controlProg, err := vmutil.P2WSHProgram(scriptHash)
478 if !bytes.Equal(rawTx.Outputs[prevout.Source.Position].ControlProgram, controlProg) {
479 return errors.New("The output control program of transaction does not match the control program of the system's alliance contract")
484 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
486 return errors.Wrap(ErrMissingField, "empty value source")
489 return errors.Wrap(ErrMissingField, "missing ref on value source")
491 if vs.Value == nil || vs.Value.AssetId == nil {
492 return errors.Wrap(ErrMissingField, "missing value on value source")
495 e, ok := vstate.tx.Entries[*vs.Ref]
497 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
501 vstate2.entryID = *vs.Ref
502 if err := checkValid(&vstate2, e); err != nil {
503 return errors.Wrap(err, "checking value source")
506 var dest *bc.ValueDestination
507 switch ref := e.(type) {
509 if vs.Position != 0 {
510 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
512 dest = ref.WitnessDestination
515 if vs.Position != 0 {
516 return errors.Wrapf(ErrPosition, "invalid position %d for issuance source", vs.Position)
518 dest = ref.WitnessDestination
521 if vs.Position != 0 {
522 return errors.Wrapf(ErrPosition, "invalid position %d for spend source", vs.Position)
524 dest = ref.WitnessDestination
527 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
528 return errors.Wrapf(ErrPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
530 dest = ref.WitnessDestinations[vs.Position]
532 if vs.Position != 0 {
533 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
535 dest = ref.WitnessDestination
537 if vs.Position != 0 {
538 return errors.Wrapf(ErrPosition, "invalid position %d for coinbase source", vs.Position)
540 dest = ref.WitnessDestination
542 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
545 if dest.Ref == nil || *dest.Ref != vstate.entryID {
546 return errors.Wrapf(ErrMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
549 if dest.Position != vstate.sourcePos {
550 return errors.Wrapf(ErrMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
553 eq, err := dest.Value.Equal(vs.Value)
555 return errors.Sub(ErrMissingField, err)
558 return errors.Wrapf(ErrMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
564 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
566 return errors.Wrap(ErrMissingField, "empty value destination")
569 return errors.Wrap(ErrMissingField, "missing ref on value destination")
571 if vd.Value == nil || vd.Value.AssetId == nil {
572 return errors.Wrap(ErrMissingField, "missing value on value source")
575 e, ok := vs.tx.Entries[*vd.Ref]
577 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
580 var src *bc.ValueSource
581 switch ref := e.(type) {
583 if vd.Position != 0 {
584 return errors.Wrapf(ErrPosition, "invalid position %d for output destination", vd.Position)
589 if vd.Position != 0 {
590 return errors.Wrapf(ErrPosition, "invalid position %d for retirement destination", vd.Position)
595 if vd.Position >= uint64(len(ref.Sources)) {
596 return errors.Wrapf(ErrPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
598 src = ref.Sources[vd.Position]
601 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
604 if src.Ref == nil || *src.Ref != vs.entryID {
605 return errors.Wrapf(ErrMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
608 if src.Position != vs.destPos {
609 return errors.Wrapf(ErrMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
612 eq, err := src.Value.Equal(vd.Value)
614 return errors.Sub(ErrMissingField, err)
617 return errors.Wrapf(ErrMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
623 func checkStandardTx(tx *bc.Tx) error {
624 for _, id := range tx.GasInputIDs {
625 spend, err := tx.Spend(id)
629 spentOutput, err := tx.Output(*spend.SpentOutputId)
634 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
635 return ErrNotStandardTx
639 for _, id := range tx.ResultIds {
640 e, ok := tx.Entries[*id]
642 return errors.Wrapf(bc.ErrMissingEntry, "id %x", id.Bytes())
645 output, ok := e.(*bc.Output)
646 if !ok || *output.Source.Value.AssetId != *consensus.BTMAssetID {
650 if !segwit.IsP2WScript(output.ControlProgram.Code) {
651 return ErrNotStandardTx
657 func checkTimeRange(tx *bc.Tx, block *bc.Block) error {
658 if tx.TimeRange == 0 {
662 if tx.TimeRange < block.Height {
663 return ErrBadTimeRange
668 // ValidateTx validates a transaction.
669 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
670 gasStatus := &GasState{GasValid: false}
671 if block.Version == 1 && tx.Version != 1 {
672 return gasStatus, errors.WithDetailf(ErrTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
674 if tx.SerializedSize == 0 {
675 return gasStatus, ErrWrongTransactionSize
677 if err := checkTimeRange(tx, block); err != nil {
678 return gasStatus, err
680 if err := checkStandardTx(tx); err != nil {
681 return gasStatus, err
683 vs := &validationState{
687 gasStatus: gasStatus,
688 cache: make(map[bc.Hash]error),
690 return vs.gasStatus, checkValid(vs, tx.TxHeader)