github.com/lbryio/lbcd@v0.22.119/mempool/policy.go (about)

     1  // Copyright (c) 2013-2016 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package mempool
     6  
     7  import (
     8  	"fmt"
     9  	"math"
    10  	"time"
    11  
    12  	"github.com/lbryio/lbcd/blockchain"
    13  	"github.com/lbryio/lbcd/txscript"
    14  	"github.com/lbryio/lbcd/wire"
    15  	btcutil "github.com/lbryio/lbcutil"
    16  )
    17  
    18  const (
    19  	// maxStandardP2SHSigOps is the maximum number of signature operations
    20  	// that are considered standard in a pay-to-script-hash script.
    21  	maxStandardP2SHSigOps = 15
    22  
    23  	// maxStandardTxCost is the max weight permitted by any transaction
    24  	// according to the current default policy.
    25  	maxStandardTxWeight = 400000
    26  
    27  	// maxStandardSigScriptSize is the maximum size allowed for a
    28  	// transaction input signature script to be considered standard.  This
    29  	// value allows for a 15-of-15 CHECKMULTISIG pay-to-script-hash with
    30  	// compressed keys.
    31  	//
    32  	// The form of the overall script is: OP_0 <15 signatures> OP_PUSHDATA2
    33  	// <2 bytes len> [OP_15 <15 pubkeys> OP_15 OP_CHECKMULTISIG]
    34  	//
    35  	// For the p2sh script portion, each of the 15 compressed pubkeys are
    36  	// 33 bytes (plus one for the OP_DATA_33 opcode), and the thus it totals
    37  	// to (15*34)+3 = 513 bytes.  Next, each of the 15 signatures is a max
    38  	// of 73 bytes (plus one for the OP_DATA_73 opcode).  Also, there is one
    39  	// extra byte for the initial extra OP_0 push and 3 bytes for the
    40  	// OP_PUSHDATA2 needed to specify the 513 bytes for the script push.
    41  	// That brings the total to 1+(15*74)+3+513 = 1627.  This value also
    42  	// adds a few extra bytes to provide a little buffer.
    43  	// (1 + 15*74 + 3) + (15*34 + 3) + 23 = 1650
    44  	maxStandardSigScriptSize = 1650
    45  
    46  	// DefaultMinRelayTxFee is the minimum fee in satoshi that is required
    47  	// for a transaction to be treated as free for relay and mining
    48  	// purposes.  It is also used to help determine if a transaction is
    49  	// considered dust and as a base for calculating minimum required fees
    50  	// for larger transactions.  This value is in Satoshi/1000 bytes.
    51  	DefaultMinRelayTxFee = btcutil.Amount(1000)
    52  
    53  	// maxStandardMultiSigKeys is the maximum number of public keys allowed
    54  	// in a multi-signature transaction output script for it to be
    55  	// considered standard.
    56  	maxStandardMultiSigKeys = 3
    57  )
    58  
    59  // calcMinRequiredTxRelayFee returns the minimum transaction fee required for a
    60  // transaction with the passed serialized size to be accepted into the memory
    61  // pool and relayed.
    62  func calcMinRequiredTxRelayFee(serializedSize int64, minRelayTxFee btcutil.Amount) int64 {
    63  	// Calculate the minimum fee for a transaction to be allowed into the
    64  	// mempool and relayed by scaling the base fee (which is the minimum
    65  	// free transaction relay fee).  minRelayTxFee is in Satoshi/kB so
    66  	// multiply by serializedSize (which is in bytes) and divide by 1000 to
    67  	// get minimum Satoshis.
    68  	minFee := (serializedSize * int64(minRelayTxFee)) / 1000
    69  
    70  	if minFee == 0 && minRelayTxFee > 0 {
    71  		minFee = int64(minRelayTxFee)
    72  	}
    73  
    74  	// Set the minimum fee to the maximum possible value if the calculated
    75  	// fee is not in the valid range for monetary amounts.
    76  	if minFee < 0 || minFee > btcutil.MaxSatoshi {
    77  		minFee = btcutil.MaxSatoshi
    78  	}
    79  
    80  	return minFee
    81  }
    82  
    83  // checkInputsStandard performs a series of checks on a transaction's inputs
    84  // to ensure they are "standard".  A standard transaction input within the
    85  // context of this function is one whose referenced public key script is of a
    86  // standard form and, for pay-to-script-hash, does not have more than
    87  // maxStandardP2SHSigOps signature operations.  However, it should also be noted
    88  // that standard inputs also are those which have a clean stack after execution
    89  // and only contain pushed data in their signature scripts.  This function does
    90  // not perform those checks because the script engine already does this more
    91  // accurately and concisely via the txscript.ScriptVerifyCleanStack and
    92  // txscript.ScriptVerifySigPushOnly flags.
    93  func checkInputsStandard(tx *btcutil.Tx, utxoView *blockchain.UtxoViewpoint) error {
    94  	// NOTE: The reference implementation also does a coinbase check here,
    95  	// but coinbases have already been rejected prior to calling this
    96  	// function so no need to recheck.
    97  
    98  	for i, txIn := range tx.MsgTx().TxIn {
    99  		// It is safe to elide existence and index checks here since
   100  		// they have already been checked prior to calling this
   101  		// function.
   102  		entry := utxoView.LookupEntry(txIn.PreviousOutPoint)
   103  		originPkScript := txscript.StripClaimScriptPrefix(entry.PkScript())
   104  		switch txscript.GetScriptClass(originPkScript) {
   105  		case txscript.ScriptHashTy:
   106  			numSigOps := txscript.GetPreciseSigOpCount(
   107  				txIn.SignatureScript, originPkScript, true)
   108  			if numSigOps > maxStandardP2SHSigOps {
   109  				str := fmt.Sprintf("transaction input #%d has "+
   110  					"%d signature operations which is more "+
   111  					"than the allowed max amount of %d",
   112  					i, numSigOps, maxStandardP2SHSigOps)
   113  				return txRuleError(wire.RejectNonstandard, str)
   114  			}
   115  
   116  		case txscript.NonStandardTy:
   117  			str := fmt.Sprintf("transaction input #%d has a "+
   118  				"non-standard script form", i)
   119  			return txRuleError(wire.RejectNonstandard, str)
   120  		}
   121  	}
   122  
   123  	return nil
   124  }
   125  
   126  // checkPkScriptStandard performs a series of checks on a transaction output
   127  // script (public key script) to ensure it is a "standard" public key script.
   128  // A standard public key script is one that is a recognized form, and for
   129  // multi-signature scripts, only contains from 1 to maxStandardMultiSigKeys
   130  // public keys.
   131  func checkPkScriptStandard(pkScript []byte, scriptClass txscript.ScriptClass) error {
   132  	switch scriptClass {
   133  	case txscript.MultiSigTy:
   134  		numPubKeys, numSigs, err := txscript.CalcMultiSigStats(pkScript)
   135  		if err != nil {
   136  			str := fmt.Sprintf("multi-signature script parse "+
   137  				"failure: %v", err)
   138  			return txRuleError(wire.RejectNonstandard, str)
   139  		}
   140  
   141  		// A standard multi-signature public key script must contain
   142  		// from 1 to maxStandardMultiSigKeys public keys.
   143  		if numPubKeys < 1 {
   144  			str := "multi-signature script with no pubkeys"
   145  			return txRuleError(wire.RejectNonstandard, str)
   146  		}
   147  		if numPubKeys > maxStandardMultiSigKeys {
   148  			str := fmt.Sprintf("multi-signature script with %d "+
   149  				"public keys which is more than the allowed "+
   150  				"max of %d", numPubKeys, maxStandardMultiSigKeys)
   151  			return txRuleError(wire.RejectNonstandard, str)
   152  		}
   153  
   154  		// A standard multi-signature public key script must have at
   155  		// least 1 signature and no more signatures than available
   156  		// public keys.
   157  		if numSigs < 1 {
   158  			return txRuleError(wire.RejectNonstandard,
   159  				"multi-signature script with no signatures")
   160  		}
   161  		if numSigs > numPubKeys {
   162  			str := fmt.Sprintf("multi-signature script with %d "+
   163  				"signatures which is more than the available "+
   164  				"%d public keys", numSigs, numPubKeys)
   165  			return txRuleError(wire.RejectNonstandard, str)
   166  		}
   167  
   168  	case txscript.NonStandardTy:
   169  		return txRuleError(wire.RejectNonstandard,
   170  			"non-standard script form")
   171  	}
   172  
   173  	return nil
   174  }
   175  
   176  // GetDustThreshold calculates the dust limit for a *wire.TxOut by taking the
   177  // size of a typical spending transaction and multiplying it by 3 to account
   178  // for the minimum dust relay fee of 3000sat/kvb.
   179  const dustCap = math.MaxInt64 / 1001
   180  
   181  func GetDustThreshold(txOut *wire.TxOut) int64 {
   182  	// The total serialized size consists of the output and the associated
   183  	// input script to redeem it.  Since there is no input script
   184  	// to redeem it yet, use the minimum size of a typical input script.
   185  	//
   186  	// Pay-to-pubkey-hash bytes breakdown:
   187  	//
   188  	//  Output to hash (34 bytes):
   189  	//   8 value, 1 script len, 25 script [1 OP_DUP, 1 OP_HASH_160,
   190  	//   1 OP_DATA_20, 20 hash, 1 OP_EQUALVERIFY, 1 OP_CHECKSIG]
   191  	//
   192  	//  Input with compressed pubkey (148 bytes):
   193  	//   36 prev outpoint, 1 script len, 107 script [1 OP_DATA_72, 72 sig,
   194  	//   1 OP_DATA_33, 33 compressed pubkey], 4 sequence
   195  	//
   196  	//  Input with uncompressed pubkey (180 bytes):
   197  	//   36 prev outpoint, 1 script len, 139 script [1 OP_DATA_72, 72 sig,
   198  	//   1 OP_DATA_65, 65 compressed pubkey], 4 sequence
   199  	//
   200  	// Pay-to-pubkey bytes breakdown:
   201  	//
   202  	//  Output to compressed pubkey (44 bytes):
   203  	//   8 value, 1 script len, 35 script [1 OP_DATA_33,
   204  	//   33 compressed pubkey, 1 OP_CHECKSIG]
   205  	//
   206  	//  Output to uncompressed pubkey (76 bytes):
   207  	//   8 value, 1 script len, 67 script [1 OP_DATA_65, 65 pubkey,
   208  	//   1 OP_CHECKSIG]
   209  	//
   210  	//  Input (114 bytes):
   211  	//   36 prev outpoint, 1 script len, 73 script [1 OP_DATA_72,
   212  	//   72 sig], 4 sequence
   213  	//
   214  	// Pay-to-witness-pubkey-hash bytes breakdown:
   215  	//
   216  	//  Output to witness key hash (31 bytes);
   217  	//   8 value, 1 script len, 22 script [1 OP_0, 1 OP_DATA_20,
   218  	//   20 bytes hash160]
   219  	//
   220  	//  Input (67 bytes as the 107 witness stack is discounted):
   221  	//   36 prev outpoint, 1 script len, 0 script (not sigScript), 107
   222  	//   witness stack bytes [1 element length, 33 compressed pubkey,
   223  	//   element length 72 sig], 4 sequence
   224  	//
   225  	//
   226  	// Theoretically this could examine the script type of the output script
   227  	// and use a different size for the typical input script size for
   228  	// pay-to-pubkey vs pay-to-pubkey-hash inputs per the above breakdowns,
   229  	// but the only combination which is less than the value chosen is
   230  	// a pay-to-pubkey script with a compressed pubkey, which is not very
   231  	// common.
   232  	//
   233  	// The most common scripts are pay-to-pubkey-hash, and as per the above
   234  	// breakdown, the minimum size of a p2pkh input script is 148 bytes.  So
   235  	// that figure is used. If the output being spent is a witness program,
   236  	// then we apply the witness discount to the size of the signature.
   237  	//
   238  	// The segwit analogue to p2pkh is a p2wkh output. This is the smallest
   239  	// output possible using the new segwit features. The 107 bytes of
   240  	// witness data is discounted by a factor of 4, leading to a computed
   241  	// value of 67 bytes of witness data.
   242  	//
   243  	// Both cases share a 41 byte preamble required to reference the input
   244  	// being spent and the sequence number of the input.
   245  	totalSize := txOut.SerializeSize() + 41
   246  	if txscript.IsWitnessProgram(txOut.PkScript) {
   247  		totalSize += (107 / blockchain.WitnessScaleFactor)
   248  	} else {
   249  		totalSize += 107
   250  	}
   251  
   252  	return int64(totalSize)
   253  }
   254  
   255  // IsDust returns whether or not the passed transaction output amount is
   256  // considered dust or not based on the passed minimum transaction relay fee.
   257  // Dust is defined in terms of the minimum transaction relay fee.  In
   258  // particular, if the cost to the network to spend coins is more than 1/3 of the
   259  // minimum transaction relay fee, it is considered dust.
   260  func IsDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool {
   261  	// Unspendable outputs are considered dust.
   262  	if txscript.IsUnspendable(txOut.PkScript) {
   263  		return true
   264  	}
   265  
   266  	// The output is considered dust if the cost to the network to spend the
   267  	// coins is more than the minimum free transaction relay fee.
   268  	// minFreeTxRelayFee is in Satoshi/KB, so multiply by 1000 to
   269  	// convert to bytes.
   270  	//
   271  	// Using the typical values for a pay-to-pubkey-hash transaction from
   272  	// the breakdown above and the default minimum free transaction relay
   273  	// fee of 1000, this equates to values less than 546 satoshi being
   274  	// considered dust.
   275  	//
   276  	// The following is equivalent to (value/totalSize) * 1000
   277  	// without needing to do floating point math.
   278  	if txOut.Value > dustCap {
   279  		return false
   280  	}
   281  	return txOut.Value*1000/GetDustThreshold(txOut) < int64(minRelayTxFee)
   282  }
   283  
   284  // checkTransactionStandard performs a series of checks on a transaction to
   285  // ensure it is a "standard" transaction.  A standard transaction is one that
   286  // conforms to several additional limiting cases over what is considered a
   287  // "sane" transaction such as having a version in the supported range, being
   288  // finalized, conforming to more stringent size constraints, having scripts
   289  // of recognized forms, and not containing "dust" outputs (those that are
   290  // so small it costs more to process them than they are worth).
   291  func checkTransactionStandard(tx *btcutil.Tx, height int32,
   292  	medianTimePast time.Time, minRelayTxFee btcutil.Amount,
   293  	maxTxVersion int32) error {
   294  
   295  	// The transaction must be a currently supported version.
   296  	msgTx := tx.MsgTx()
   297  	if msgTx.Version > maxTxVersion || msgTx.Version < 1 {
   298  		str := fmt.Sprintf("transaction version %d is not in the "+
   299  			"valid range of %d-%d", msgTx.Version, 1,
   300  			maxTxVersion)
   301  		return txRuleError(wire.RejectNonstandard, str)
   302  	}
   303  
   304  	// The transaction must be finalized to be standard and therefore
   305  	// considered for inclusion in a block.
   306  	if !blockchain.IsFinalizedTransaction(tx, height, medianTimePast) {
   307  		return txRuleError(wire.RejectNonstandard,
   308  			"transaction is not finalized")
   309  	}
   310  
   311  	// Since extremely large transactions with a lot of inputs can cost
   312  	// almost as much to process as the sender fees, limit the maximum
   313  	// size of a transaction.  This also helps mitigate CPU exhaustion
   314  	// attacks.
   315  	txWeight := blockchain.GetTransactionWeight(tx)
   316  	if txWeight > maxStandardTxWeight {
   317  		str := fmt.Sprintf("weight of transaction %v is larger than max "+
   318  			"allowed weight of %v", txWeight, maxStandardTxWeight)
   319  		return txRuleError(wire.RejectNonstandard, str)
   320  	}
   321  
   322  	for i, txIn := range msgTx.TxIn {
   323  		// Each transaction input signature script must not exceed the
   324  		// maximum size allowed for a standard transaction.  See
   325  		// the comment on maxStandardSigScriptSize for more details.
   326  		sigScriptLen := len(txIn.SignatureScript)
   327  		if sigScriptLen > maxStandardSigScriptSize {
   328  			str := fmt.Sprintf("transaction input %d: signature "+
   329  				"script size of %d bytes is large than max "+
   330  				"allowed size of %d bytes", i, sigScriptLen,
   331  				maxStandardSigScriptSize)
   332  			return txRuleError(wire.RejectNonstandard, str)
   333  		}
   334  
   335  		// Each transaction input signature script must only contain
   336  		// opcodes which push data onto the stack.
   337  		if !txscript.IsPushOnlyScript(txIn.SignatureScript) {
   338  			str := fmt.Sprintf("transaction input %d: signature "+
   339  				"script is not push only", i)
   340  			return txRuleError(wire.RejectNonstandard, str)
   341  		}
   342  	}
   343  
   344  	// None of the output public key scripts can be a non-standard script or
   345  	// be "dust" (except when the script is a null data script).
   346  	numNullDataOutputs := 0
   347  	for i, txOut := range msgTx.TxOut {
   348  		pkScript := txscript.StripClaimScriptPrefix(txOut.PkScript)
   349  		scriptClass := txscript.GetScriptClass(pkScript)
   350  		err := checkPkScriptStandard(pkScript, scriptClass)
   351  		if err != nil {
   352  			// Attempt to extract a reject code from the error so
   353  			// it can be retained.  When not possible, fall back to
   354  			// a non standard error.
   355  			rejectCode := wire.RejectNonstandard
   356  			if rejCode, found := extractRejectCode(err); found {
   357  				rejectCode = rejCode
   358  			}
   359  			str := fmt.Sprintf("transaction output %d: %v", i, err)
   360  			return txRuleError(rejectCode, str)
   361  		}
   362  
   363  		// Accumulate the number of outputs which only carry data.  For
   364  		// all other script types, ensure the output value is not
   365  		// "dust".
   366  		if scriptClass == txscript.NullDataTy {
   367  			numNullDataOutputs++
   368  		} else if IsDust(txOut, minRelayTxFee) {
   369  			str := fmt.Sprintf("transaction output %d: payment "+
   370  				"of %d is dust", i, txOut.Value)
   371  			return txRuleError(wire.RejectDust, str)
   372  		}
   373  	}
   374  
   375  	// A standard transaction must not have more than one output script that
   376  	// only carries data.
   377  	if numNullDataOutputs > 1 {
   378  		str := "more than one transaction output in a nulldata script"
   379  		return txRuleError(wire.RejectNonstandard, str)
   380  	}
   381  
   382  	return nil
   383  }
   384  
   385  // GetTxVirtualSize computes the virtual size of a given transaction. A
   386  // transaction's virtual size is based off its weight, creating a discount for
   387  // any witness data it contains, proportional to the current
   388  // blockchain.WitnessScaleFactor value.
   389  func GetTxVirtualSize(tx *btcutil.Tx) int64 {
   390  	// vSize := (weight(tx) + 3) / 4
   391  	//       := (((baseSize * 3) + totalSize) + 3) / 4
   392  	// We add 3 here as a way to compute the ceiling of the prior arithmetic
   393  	// to 4. The division by 4 creates a discount for wit witness data.
   394  	return (blockchain.GetTransactionWeight(tx) + (blockchain.WitnessScaleFactor - 1)) /
   395  		blockchain.WitnessScaleFactor
   396  }