policy.go 16 KB

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