8 "github.com/bytom/common"
9 "github.com/bytom/consensus"
10 "github.com/bytom/consensus/difficulty"
11 "github.com/bytom/consensus/segwit"
12 "github.com/bytom/database"
13 "github.com/bytom/errors"
14 "github.com/bytom/math/checked"
15 "github.com/bytom/protocol/bc"
16 "github.com/bytom/protocol/vm"
20 muxGasCost = int64(10)
21 // timeRangeGash is the block height we will reach after 100 years
22 timeRangeGash = uint64(21024000)
25 // GasState record the gas usage status
26 type GasState struct {
34 func (g *GasState) setGas(BTMValue int64, txSize int64) error {
36 return errors.Wrap(errGasCalculate, "input BTM is negative")
39 g.BTMValue = uint64(BTMValue)
42 g.GasLeft = muxGasCost
47 if g.GasLeft, ok = checked.DivInt64(BTMValue, consensus.VMGasRate); !ok {
48 return errors.Wrap(errGasCalculate, "setGas calc gas amount")
51 if g.GasLeft > consensus.MaxGasAmount {
52 g.GasLeft = consensus.MaxGasAmount
55 if g.storageGas, ok = checked.MulInt64(txSize, consensus.StorageGasRate); !ok {
56 return errors.Wrap(errGasCalculate, "setGas calc tx storage gas")
61 func (g *GasState) setGasVaild() error {
63 if g.GasLeft, ok = checked.SubInt64(g.GasLeft, g.storageGas); !ok || g.GasLeft < 0 {
64 return errors.Wrap(errGasCalculate, "setGasVaild calc gasLeft")
67 if g.GasUsed, ok = checked.AddInt64(g.GasUsed, g.storageGas); !ok {
68 return errors.Wrap(errGasCalculate, "setGasVaild calc gasUsed")
75 func (g *GasState) updateUsage(gasLeft int64) error {
77 return errors.Wrap(errGasCalculate, "updateUsage input negative gas")
80 if gasUsed, ok := checked.SubInt64(g.GasLeft, gasLeft); ok {
84 return errors.Wrap(errGasCalculate, "updateUsage calc gas diff")
87 if !g.GasVaild && (g.GasUsed > consensus.DefaultGasCredit || g.storageGas > g.GasLeft) {
88 return errOverGasCredit
93 // validationState contains the context that must propagate through
94 // the transaction graph when validating entries.
95 type validationState struct {
96 // The ID of the blockchain
99 // The enclosing transaction object
102 // The ID of the nearest enclosing entry
105 // The source position, for validating ValueSources
108 // The destination position, for validating ValueDestinations
111 // Memoized per-entry validation results
112 cache map[bc.Hash]error
118 errBadTimestamp = errors.New("block timestamp is not in the vaild range")
119 errBadBits = errors.New("block bits is invaild")
120 errGasCalculate = errors.New("gas usage calculate got a math error")
121 errEmptyResults = errors.New("transaction has no results")
122 errMismatchedAssetID = errors.New("mismatched asset id")
123 errMismatchedBlock = errors.New("mismatched block")
124 errMismatchedMerkleRoot = errors.New("mismatched merkle root")
125 errMismatchedPosition = errors.New("mismatched value source/dest positions")
126 errMismatchedReference = errors.New("mismatched reference")
127 errMismatchedTxStatus = errors.New("mismatched transaction status")
128 errMismatchedValue = errors.New("mismatched value")
129 errMisorderedBlockHeight = errors.New("misordered block height")
130 errMisorderedBlockTime = errors.New("misordered block time")
131 errMissingField = errors.New("missing required field")
132 errNoGas = errors.New("no gas input")
133 errNoPrevBlock = errors.New("no previous block")
134 errNoSource = errors.New("no source for value")
135 errNonemptyExtHash = errors.New("non-empty extension hash")
136 errOverflow = errors.New("arithmetic overflow/underflow")
137 errOverGasCredit = errors.New("all gas credit has been spend")
138 errOverBlockLimit = errors.New("block's gas is over the limit")
139 errPosition = errors.New("invalid source or destination position")
140 errWorkProof = errors.New("invalid difficulty proof of work")
141 errTxVersion = errors.New("invalid transaction version")
142 errUnbalanced = errors.New("unbalanced")
143 errUntimelyTransaction = errors.New("block timestamp outside transaction time range")
144 errVersionRegression = errors.New("version regression")
145 errWrongBlockSize = errors.New("block size is too big")
146 errWrongTransactionSize = errors.New("transaction size is not in vaild range")
147 errWrongTransactionStatus = errors.New("transaction status is wrong")
148 errWrongCoinbaseTransaction = errors.New("wrong coinbase transaction")
149 errWrongCoinbaseAsset = errors.New("wrong coinbase asset id")
150 errNotStandardTx = errors.New("gas transaction is not standard transaction")
153 func checkValid(vs *validationState, e bc.Entry) (err error) {
154 entryID := bc.EntryID(e)
156 if err, ok = vs.cache[entryID]; ok {
161 vs.cache[entryID] = err
164 switch e := e.(type) {
167 for i, resID := range e.ResultIds {
168 resultEntry := vs.tx.Entries[*resID]
171 err = checkValid(&vs2, resultEntry)
173 return errors.Wrapf(err, "checking result %d", i)
178 if len(e.ResultIds) == 0 {
179 return errEmptyResults
182 if e.ExtHash != nil && !e.ExtHash.IsZero() {
183 return errNonemptyExtHash
188 if vs.block == nil || len(vs.block.Transactions) == 0 || vs.block.Transactions[0] != vs.tx {
189 return errWrongCoinbaseTransaction
192 if *e.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
193 return errWrongCoinbaseAsset
198 err = checkValidDest(&vs2, e.WitnessDestination)
200 return errors.Wrap(err, "checking coinbase destination")
204 parity := make(map[bc.AssetID]int64)
205 for i, src := range e.Sources {
206 sum, ok := checked.AddInt64(parity[*src.Value.AssetId], int64(src.Value.Amount))
208 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])
210 parity[*src.Value.AssetId] = sum
213 for i, dest := range e.WitnessDestinations {
214 sum, ok := parity[*dest.Value.AssetId]
216 return errors.WithDetailf(errNoSource, "mux destination %d, asset %x, has no corresponding source", i, dest.Value.AssetId.Bytes())
219 diff, ok := checked.SubInt64(sum, int64(dest.Value.Amount))
221 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)
223 parity[*dest.Value.AssetId] = diff
226 for assetID, amount := range parity {
227 if assetID == *consensus.BTMAssetID {
228 if err = vs.gasStatus.setGas(amount, int64(vs.tx.SerializedSize)); err != nil {
231 } else if amount != 0 {
232 return errors.WithDetailf(errUnbalanced, "asset %x sources - destinations = %d (should be 0)", assetID.Bytes(), amount)
236 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.Program, e.WitnessArguments), vs.gasStatus.GasLeft)
238 return errors.Wrap(err, "checking mux program")
240 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
244 for _, BTMInputID := range vs.tx.GasInputIDs {
245 e, ok := vs.tx.Entries[BTMInputID]
247 return errors.Wrapf(bc.ErrMissingEntry, "entry for bytom input %x not found", BTMInputID)
251 vs2.entryID = BTMInputID
252 if err := checkValid(&vs2, e); err != nil {
253 return errors.Wrap(err, "checking value source")
257 for i, dest := range e.WitnessDestinations {
259 vs2.destPos = uint64(i)
260 err = checkValidDest(&vs2, dest)
262 return errors.Wrapf(err, "checking mux destination %d", i)
266 if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
267 return errNonemptyExtHash
270 if err := vs.gasStatus.setGasVaild(); err != nil {
274 for i, src := range e.Sources {
276 vs2.sourcePos = uint64(i)
277 err = checkValidSrc(&vs2, src)
279 return errors.Wrapf(err, "checking mux source %d", i)
284 //TODO: add block heigh range check on the control program
285 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.Program, e.WitnessArguments), vs.gasStatus.GasLeft)
287 return errors.Wrap(err, "checking nonce program")
289 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
293 if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
294 return errNonemptyExtHash
300 err = checkValidSrc(&vs2, e.Source)
302 return errors.Wrap(err, "checking output source")
305 if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
306 return errNonemptyExtHash
312 err = checkValidSrc(&vs2, e.Source)
314 return errors.Wrap(err, "checking retirement source")
317 if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
318 return errNonemptyExtHash
322 computedAssetID := e.WitnessAssetDefinition.ComputeAssetID()
323 if computedAssetID != *e.Value.AssetId {
324 return errors.WithDetailf(errMismatchedAssetID, "asset ID is %x, issuance wants %x", computedAssetID.Bytes(), e.Value.AssetId.Bytes())
327 anchor, ok := vs.tx.Entries[*e.AnchorId]
329 return errors.Wrapf(bc.ErrMissingEntry, "entry for issuance anchor %x not found", e.AnchorId.Bytes())
332 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, e.WitnessAssetDefinition.IssuanceProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
334 return errors.Wrap(err, "checking issuance program")
336 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
340 var anchored *bc.Hash
341 switch a := anchor.(type) {
343 anchored = a.WitnessAnchoredId
346 anchored = a.WitnessAnchoredId
349 anchored = a.WitnessAnchoredId
352 return errors.WithDetailf(bc.ErrEntryType, "issuance anchor has type %T, should be nonce, spend, or issuance", anchor)
355 if *anchored != vs.entryID {
356 return errors.WithDetailf(errMismatchedReference, "issuance %x anchor is for %x", vs.entryID.Bytes(), anchored.Bytes())
360 anchorVS.entryID = *e.AnchorId
361 err = checkValid(&anchorVS, anchor)
363 return errors.Wrap(err, "checking issuance anchor")
368 err = checkValidDest(&destVS, e.WitnessDestination)
370 return errors.Wrap(err, "checking issuance destination")
373 if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
374 return errNonemptyExtHash
378 if e.SpentOutputId == nil {
379 return errors.Wrap(errMissingField, "spend without spent output ID")
381 spentOutput, err := vs.tx.Output(*e.SpentOutputId)
383 return errors.Wrap(err, "getting spend prevout")
385 gasLeft, err := vm.Verify(NewTxVMContext(vs, e, spentOutput.ControlProgram, e.WitnessArguments), vs.gasStatus.GasLeft)
387 return errors.Wrap(err, "checking control program")
389 if err = vs.gasStatus.updateUsage(gasLeft); err != nil {
393 eq, err := spentOutput.Source.Value.Equal(e.WitnessDestination.Value)
398 return errors.WithDetailf(
400 "previous output is for %d unit(s) of %x, spend wants %d unit(s) of %x",
401 spentOutput.Source.Value.Amount,
402 spentOutput.Source.Value.AssetId.Bytes(),
403 e.WitnessDestination.Value.Amount,
404 e.WitnessDestination.Value.AssetId.Bytes(),
410 err = checkValidDest(&vs2, e.WitnessDestination)
412 return errors.Wrap(err, "checking spend destination")
415 if vs.tx.Version == 1 && e.ExtHash != nil && !e.ExtHash.IsZero() {
416 return errNonemptyExtHash
420 return fmt.Errorf("entry has unexpected type %T", e)
426 func checkValidSrc(vstate *validationState, vs *bc.ValueSource) error {
428 return errors.Wrap(errMissingField, "empty value source")
431 return errors.Wrap(errMissingField, "missing ref on value source")
433 if vs.Value == nil || vs.Value.AssetId == nil {
434 return errors.Wrap(errMissingField, "missing value on value source")
437 e, ok := vstate.tx.Entries[*vs.Ref]
439 return errors.Wrapf(bc.ErrMissingEntry, "entry for value source %x not found", vs.Ref.Bytes())
442 vstate2.entryID = *vs.Ref
443 err := checkValid(&vstate2, e)
445 return errors.Wrap(err, "checking value source")
448 var dest *bc.ValueDestination
449 switch ref := e.(type) {
451 if vs.Position != 0 {
452 return errors.Wrapf(errPosition, "invalid position %d for coinbase source", vs.Position)
454 dest = ref.WitnessDestination
456 if vs.Position != 0 {
457 return errors.Wrapf(errPosition, "invalid position %d for issuance source", vs.Position)
459 dest = ref.WitnessDestination
462 if vs.Position != 0 {
463 return errors.Wrapf(errPosition, "invalid position %d for spend source", vs.Position)
465 dest = ref.WitnessDestination
468 if vs.Position >= uint64(len(ref.WitnessDestinations)) {
469 return errors.Wrapf(errPosition, "invalid position %d for %d-destination mux source", vs.Position, len(ref.WitnessDestinations))
471 dest = ref.WitnessDestinations[vs.Position]
474 return errors.Wrapf(bc.ErrEntryType, "value source is %T, should be coinbase, issuance, spend, or mux", e)
477 if dest.Ref == nil || *dest.Ref != vstate.entryID {
478 return errors.Wrapf(errMismatchedReference, "value source for %x has disagreeing destination %x", vstate.entryID.Bytes(), dest.Ref.Bytes())
481 if dest.Position != vstate.sourcePos {
482 return errors.Wrapf(errMismatchedPosition, "value source position %d disagrees with %d", dest.Position, vstate.sourcePos)
485 eq, err := dest.Value.Equal(vs.Value)
487 return errors.Sub(errMissingField, err)
490 return errors.Wrapf(errMismatchedValue, "source value %v disagrees with %v", dest.Value, vs.Value)
496 func checkValidDest(vs *validationState, vd *bc.ValueDestination) error {
498 return errors.Wrap(errMissingField, "empty value destination")
501 return errors.Wrap(errMissingField, "missing ref on value destination")
503 if vd.Value == nil || vd.Value.AssetId == nil {
504 return errors.Wrap(errMissingField, "missing value on value source")
507 e, ok := vs.tx.Entries[*vd.Ref]
509 return errors.Wrapf(bc.ErrMissingEntry, "entry for value destination %x not found", vd.Ref.Bytes())
511 var src *bc.ValueSource
512 switch ref := e.(type) {
514 if vd.Position != 0 {
515 return errors.Wrapf(errPosition, "invalid position %d for output destination", vd.Position)
520 if vd.Position != 0 {
521 return errors.Wrapf(errPosition, "invalid position %d for retirement destination", vd.Position)
526 if vd.Position >= uint64(len(ref.Sources)) {
527 return errors.Wrapf(errPosition, "invalid position %d for %d-source mux destination", vd.Position, len(ref.Sources))
529 src = ref.Sources[vd.Position]
532 return errors.Wrapf(bc.ErrEntryType, "value destination is %T, should be output, retirement, or mux", e)
535 if src.Ref == nil || *src.Ref != vs.entryID {
536 return errors.Wrapf(errMismatchedReference, "value destination for %x has disagreeing source %x", vs.entryID.Bytes(), src.Ref.Bytes())
539 if src.Position != vs.destPos {
540 return errors.Wrapf(errMismatchedPosition, "value destination position %d disagrees with %d", src.Position, vs.destPos)
543 eq, err := src.Value.Equal(vd.Value)
545 return errors.Sub(errMissingField, err)
548 return errors.Wrapf(errMismatchedValue, "destination value %v disagrees with %v", src.Value, vd.Value)
554 // ValidateBlock validates a block and the transactions within.
555 // It does not run the consensus program; for that, see ValidateBlockSig.
556 func ValidateBlock(b, prev *bc.Block, seed *bc.Hash, store database.Store) error {
559 return errors.WithDetailf(errNoPrevBlock, "height %d", b.Height)
561 if err := validateBlockAgainstPrev(b, prev); err != nil {
564 if err := validateBlockTime(b, store); err != nil {
567 if err := validateBlockBits(b, prev, store); err != nil {
572 if !difficulty.CheckProofOfWork(&b.ID, seed, b.BlockHeader.Bits) {
576 b.TransactionStatus = bc.NewTransactionStatus()
577 coinbaseValue := consensus.BlockSubsidy(b.BlockHeader.Height)
579 for i, tx := range b.Transactions {
580 gasStatus, err := ValidateTx(tx, b)
583 if gasStatus == nil || !gasStatus.GasVaild {
584 return errors.Wrapf(err, "validity of transaction %d of %d", i, len(b.Transactions))
588 b.TransactionStatus.SetStatus(i, gasOnlyTx)
589 coinbaseValue += gasStatus.BTMValue
590 gasUsed += uint64(gasStatus.GasUsed)
593 if gasUsed > consensus.MaxBlockGas {
594 return errOverBlockLimit
597 // check the coinbase output entry value
598 if err := validateCoinbase(b.Transactions[0], coinbaseValue); err != nil {
602 txRoot, err := bc.TxMerkleRoot(b.Transactions)
604 return errors.Wrap(err, "computing transaction merkle root")
607 if txRoot != *b.TransactionsRoot {
608 return errors.WithDetailf(errMismatchedMerkleRoot, "computed %x, current block wants %x", txRoot.Bytes(), b.TransactionsRoot.Bytes())
611 txStatusHash, err := bc.TxStatusMerkleRoot(b.TransactionStatus.VerifyStatus)
616 if txStatusHash != *b.TransactionStatusHash {
617 return errMismatchedTxStatus
622 func validateBlockBits(b, prev *bc.Block, store database.Store) error {
623 if prev.Height%consensus.BlocksPerRetarget != 0 || prev.Height == 0 {
624 if b.Bits != prev.Bits {
630 lastBH, err := store.GetBlockHeader(b.PreviousBlockId)
635 compareBH, err := store.GetBlockHeader(&lastBH.PreviousBlockHash)
640 for compareBH.Height%consensus.BlocksPerRetarget != 0 {
641 if compareBH, err = store.GetBlockHeader(&compareBH.PreviousBlockHash); err != nil {
646 if b.Bits != difficulty.CalcNextRequiredDifficulty(lastBH, compareBH) {
652 func validateBlockTime(b *bc.Block, store database.Store) error {
653 if b.Timestamp > uint64(time.Now().Unix())+consensus.MaxTimeOffsetSeconds {
654 return errBadTimestamp
657 iterBH, err := store.GetBlockHeader(b.PreviousBlockId)
662 timestamps := []uint64{}
663 for len(timestamps) < consensus.MedianTimeBlocks {
664 timestamps = append(timestamps, iterBH.Timestamp)
665 if iterBH.Height == 0 {
668 iterBH, err = store.GetBlockHeader(&iterBH.PreviousBlockHash)
674 sort.Sort(common.TimeSorter(timestamps))
675 medianTime := timestamps[len(timestamps)/2]
676 if b.Timestamp <= medianTime {
677 return errBadTimestamp
682 func validateCoinbase(tx *bc.Tx, value uint64) error {
683 resultEntry := tx.Entries[*tx.TxHeader.ResultIds[0]]
684 output, ok := resultEntry.(*bc.Output)
686 return errors.Wrap(errWrongCoinbaseTransaction, "decode output")
689 if output.Source.Value.Amount != value {
690 return errors.Wrap(errWrongCoinbaseTransaction, "dismatch output value")
693 inputEntry := tx.Entries[tx.InputIDs[0]]
694 input, ok := inputEntry.(*bc.Coinbase)
696 return errors.Wrap(errWrongCoinbaseTransaction, "decode input")
698 if input.Arbitrary != nil && len(input.Arbitrary) > consensus.CoinbaseArbitrarySizeLimit {
699 return errors.Wrap(errWrongCoinbaseTransaction, "coinbase arbitrary is over size")
704 func validateBlockAgainstPrev(b, prev *bc.Block) error {
705 if b.Version < prev.Version {
706 return errors.WithDetailf(errVersionRegression, "previous block verson %d, current block version %d", prev.Version, b.Version)
708 if b.Height != prev.Height+1 {
709 return errors.WithDetailf(errMisorderedBlockHeight, "previous block height %d, current block height %d", prev.Height, b.Height)
712 if prev.ID != *b.PreviousBlockId {
713 return errors.WithDetailf(errMismatchedBlock, "previous block ID %x, current block wants %x", prev.ID.Bytes(), b.PreviousBlockId.Bytes())
718 func validateStandardTx(tx *bc.Tx) error {
719 for _, id := range tx.InputIDs {
720 e, ok := tx.Entries[id]
722 return errors.New("miss tx input entry")
724 if spend, ok := e.(*bc.Spend); ok {
725 if *spend.WitnessDestination.Value.AssetId != *consensus.BTMAssetID {
728 spentOutput, err := tx.Output(*spend.SpentOutputId)
730 return errors.Wrap(err, "getting spend prevout")
733 if !segwit.IsP2WScript(spentOutput.ControlProgram.Code) {
734 return errNotStandardTx
739 for _, id := range tx.ResultIds {
740 e, ok := tx.Entries[*id]
742 return errors.New("miss tx output entry")
744 if output, ok := e.(*bc.Output); ok {
745 if *output.Source.Value.AssetId != *consensus.BTMAssetID {
748 if !segwit.IsP2WScript(output.ControlProgram.Code) {
749 return errNotStandardTx
756 // ValidateTx validates a transaction.
757 func ValidateTx(tx *bc.Tx, block *bc.Block) (*GasState, error) {
758 if block.Version == 1 && tx.Version != 1 {
759 return nil, errors.WithDetailf(errTxVersion, "block version %d, transaction version %d", block.Version, tx.Version)
762 if tx.TimeRange > timeRangeGash && tx.TimeRange < block.Timestamp {
763 return nil, errors.New("transaction max timestamp is lower than block's")
764 } else if tx.TimeRange != 0 && tx.TimeRange < block.Height {
765 return nil, errors.New("transaction max block height is lower than block's")
768 if tx.TxHeader.SerializedSize > consensus.MaxTxSize || tx.TxHeader.SerializedSize == 0 {
769 return nil, errWrongTransactionSize
772 if len(tx.ResultIds) == 0 {
773 return nil, errors.New("tx didn't have any output")
776 if len(tx.GasInputIDs) == 0 && tx != block.Transactions[0] {
777 return nil, errors.New("tx didn't have gas input")
780 if err := validateStandardTx(tx); err != nil {
784 vs := &validationState{
788 gasStatus: &GasState{
791 cache: make(map[bc.Hash]error),
794 err := checkValid(vs, tx.TxHeader)
795 return vs.gasStatus, err