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.
11 "github.com/btcsuite/btcd/blockchain"
12 "github.com/btcsuite/btcd/txscript"
13 "github.com/btcsuite/btcd/wire"
14 "github.com/btcsuite/btcutil"
18 // maxStandardP2SHSigOps is the maximum number of signature operations
19 // that are considered standard in a pay-to-script-hash script.
20 maxStandardP2SHSigOps = 15
22 // maxStandardTxCost is the max weight permitted by any transaction
23 // according to the current default policy.
24 maxStandardTxWeight = 400000
26 // maxStandardSigScriptSize is the maximum size allowed for a
27 // transaction input signature script to be considered standard. This
28 // value allows for a 15-of-15 CHECKMULTISIG pay-to-script-hash with
31 // The form of the overall script is: OP_0 <15 signatures> OP_PUSHDATA2
32 // <2 bytes len> [OP_15 <15 pubkeys> OP_15 OP_CHECKMULTISIG]
34 // For the p2sh script portion, each of the 15 compressed pubkeys are
35 // 33 bytes (plus one for the OP_DATA_33 opcode), and the thus it totals
36 // to (15*34)+3 = 513 bytes. Next, each of the 15 signatures is a max
37 // of 73 bytes (plus one for the OP_DATA_73 opcode). Also, there is one
38 // extra byte for the initial extra OP_0 push and 3 bytes for the
39 // OP_PUSHDATA2 needed to specify the 513 bytes for the script push.
40 // That brings the total to 1+(15*74)+3+513 = 1627. This value also
41 // adds a few extra bytes to provide a little buffer.
42 // (1 + 15*74 + 3) + (15*34 + 3) + 23 = 1650
43 maxStandardSigScriptSize = 1650
45 // DefaultMinRelayTxFee is the minimum fee in satoshi that is required
46 // for a transaction to be treated as free for relay and mining
47 // purposes. It is also used to help determine if a transaction is
48 // considered dust and as a base for calculating minimum required fees
49 // for larger transactions. This value is in Satoshi/1000 bytes.
50 DefaultMinRelayTxFee = btcutil.Amount(1000)
52 // maxStandardMultiSigKeys is the maximum number of public keys allowed
53 // in a multi-signature transaction output script for it to be
54 // considered standard.
55 maxStandardMultiSigKeys = 3
58 // calcMinRequiredTxRelayFee returns the minimum transaction fee required for a
59 // transaction with the passed serialized size to be accepted into the memory
61 func calcMinRequiredTxRelayFee(serializedSize int64, minRelayTxFee btcutil.Amount) int64 {
62 // Calculate the minimum fee for a transaction to be allowed into the
63 // mempool and relayed by scaling the base fee (which is the minimum
64 // free transaction relay fee). minTxRelayFee is in Satoshi/kB so
65 // multiply by serializedSize (which is in bytes) and divide by 1000 to
66 // get minimum Satoshis.
67 minFee := (serializedSize * int64(minRelayTxFee)) / 1000
69 if minFee == 0 && minRelayTxFee > 0 {
70 minFee = int64(minRelayTxFee)
73 // Set the minimum fee to the maximum possible value if the calculated
74 // fee is not in the valid range for monetary amounts.
75 if minFee < 0 || minFee > btcutil.MaxSatoshi {
76 minFee = btcutil.MaxSatoshi
82 // checkInputsStandard performs a series of checks on a transaction's inputs
83 // to ensure they are "standard". A standard transaction input within the
84 // context of this function is one whose referenced public key script is of a
85 // standard form and, for pay-to-script-hash, does not have more than
86 // maxStandardP2SHSigOps signature operations. However, it should also be noted
87 // that standard inputs also are those which have a clean stack after execution
88 // and only contain pushed data in their signature scripts. This function does
89 // not perform those checks because the script engine already does this more
90 // accurately and concisely via the txscript.ScriptVerifyCleanStack and
91 // txscript.ScriptVerifySigPushOnly flags.
92 func checkInputsStandard(tx *btcutil.Tx, utxoView *blockchain.UtxoViewpoint) error {
93 // NOTE: The reference implementation also does a coinbase check here,
94 // but coinbases have already been rejected prior to calling this
95 // function so no need to recheck.
97 for i, txIn := range tx.MsgTx().TxIn {
98 // It is safe to elide existence and index checks here since
99 // they have already been checked prior to calling this
101 prevOut := txIn.PreviousOutPoint
102 entry := utxoView.LookupEntry(&prevOut.Hash)
103 originPkScript := entry.PkScriptByIndex(prevOut.Index)
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)
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)
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
131 func checkPkScriptStandard(pkScript []byte, scriptClass txscript.ScriptClass) error {
133 case txscript.MultiSigTy:
134 numPubKeys, numSigs, err := txscript.CalcMultiSigStats(pkScript)
136 str := fmt.Sprintf("multi-signature script parse "+
138 return txRuleError(wire.RejectNonstandard, str)
141 // A standard multi-signature public key script must contain
142 // from 1 to maxStandardMultiSigKeys public keys.
144 str := "multi-signature script with no pubkeys"
145 return txRuleError(wire.RejectNonstandard, str)
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)
154 // A standard multi-signature public key script must have at
155 // least 1 signature and no more signatures than available
158 return txRuleError(wire.RejectNonstandard,
159 "multi-signature script with no signatures")
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)
168 case txscript.NonStandardTy:
169 return txRuleError(wire.RejectNonstandard,
170 "non-standard script form")
176 // isDust returns whether or not the passed transaction output amount is
177 // considered dust or not based on the passed minimum transaction relay fee.
178 // Dust is defined in terms of the minimum transaction relay fee. In
179 // particular, if the cost to the network to spend coins is more than 1/3 of the
180 // minimum transaction relay fee, it is considered dust.
181 func isDust(txOut *wire.TxOut, minRelayTxFee btcutil.Amount) bool {
182 // Unspendable outputs are considered dust.
183 if txscript.IsUnspendable(txOut.PkScript) {
187 // The total serialized size consists of the output and the associated
188 // input script to redeem it. Since there is no input script
189 // to redeem it yet, use the minimum size of a typical input script.
191 // Pay-to-pubkey-hash bytes breakdown:
193 // Output to hash (34 bytes):
194 // 8 value, 1 script len, 25 script [1 OP_DUP, 1 OP_HASH_160,
195 // 1 OP_DATA_20, 20 hash, 1 OP_EQUALVERIFY, 1 OP_CHECKSIG]
197 // Input with compressed pubkey (148 bytes):
198 // 36 prev outpoint, 1 script len, 107 script [1 OP_DATA_72, 72 sig,
199 // 1 OP_DATA_33, 33 compressed pubkey], 4 sequence
201 // Input with uncompressed pubkey (180 bytes):
202 // 36 prev outpoint, 1 script len, 139 script [1 OP_DATA_72, 72 sig,
203 // 1 OP_DATA_65, 65 compressed pubkey], 4 sequence
205 // Pay-to-pubkey bytes breakdown:
207 // Output to compressed pubkey (44 bytes):
208 // 8 value, 1 script len, 35 script [1 OP_DATA_33,
209 // 33 compressed pubkey, 1 OP_CHECKSIG]
211 // Output to uncompressed pubkey (76 bytes):
212 // 8 value, 1 script len, 67 script [1 OP_DATA_65, 65 pubkey,
215 // Input (114 bytes):
216 // 36 prev outpoint, 1 script len, 73 script [1 OP_DATA_72,
217 // 72 sig], 4 sequence
219 // Pay-to-witness-pubkey-hash bytes breakdown:
221 // Output to witness key hash (31 bytes);
222 // 8 value, 1 script len, 22 script [1 OP_0, 1 OP_DATA_20,
225 // Input (67 bytes as the 107 witness stack is discounted):
226 // 36 prev outpoint, 1 script len, 0 script (not sigScript), 107
227 // witness stack bytes [1 element length, 33 compressed pubkey,
228 // element length 72 sig], 4 sequence
231 // Theoretically this could examine the script type of the output script
232 // and use a different size for the typical input script size for
233 // pay-to-pubkey vs pay-to-pubkey-hash inputs per the above breakdowns,
234 // but the only combination which is less than the value chosen is
235 // a pay-to-pubkey script with a compressed pubkey, which is not very
238 // The most common scripts are pay-to-pubkey-hash, and as per the above
239 // breakdown, the minimum size of a p2pkh input script is 148 bytes. So
240 // that figure is used. If the output being spent is a witness program,
241 // then we apply the witness discount to the size of the signature.
243 // The segwit analogue to p2pkh is a p2wkh output. This is the smallest
244 // output possible using the new segwit features. The 107 bytes of
245 // witness data is discounted by a factor of 4, leading to a computed
246 // value of 67 bytes of witness data.
248 // Both cases share a 41 byte preamble required to reference the input
249 // being spent and the sequence number of the input.
250 totalSize := txOut.SerializeSize() + 41
251 if txscript.IsWitnessProgram(txOut.PkScript) {
252 totalSize += (107 / blockchain.WitnessScaleFactor)
257 // The output is considered dust if the cost to the network to spend the
258 // coins is more than 1/3 of the minimum free transaction relay fee.
259 // minFreeTxRelayFee is in Satoshi/KB, so multiply by 1000 to
262 // Using the typical values for a pay-to-pubkey-hash transaction from
263 // the breakdown above and the default minimum free transaction relay
264 // fee of 1000, this equates to values less than 546 satoshi being
267 // The following is equivalent to (value/totalSize) * (1/3) * 1000
268 // without needing to do floating point math.
269 return txOut.Value*1000/(3*int64(totalSize)) < int64(minRelayTxFee)
272 // checkTransactionStandard performs a series of checks on a transaction to
273 // ensure it is a "standard" transaction. A standard transaction is one that
274 // conforms to several additional limiting cases over what is considered a
275 // "sane" transaction such as having a version in the supported range, being
276 // finalized, conforming to more stringent size constraints, having scripts
277 // of recognized forms, and not containing "dust" outputs (those that are
278 // so small it costs more to process them than they are worth).
279 func checkTransactionStandard(tx *btcutil.Tx, height int32,
280 medianTimePast time.Time, minRelayTxFee btcutil.Amount,
281 maxTxVersion int32) error {
283 // The transaction must be a currently supported version.
285 if msgTx.Version > maxTxVersion || msgTx.Version < 1 {
286 str := fmt.Sprintf("transaction version %d is not in the "+
287 "valid range of %d-%d", msgTx.Version, 1,
289 return txRuleError(wire.RejectNonstandard, str)
292 // The transaction must be finalized to be standard and therefore
293 // considered for inclusion in a block.
294 if !blockchain.IsFinalizedTransaction(tx, height, medianTimePast) {
295 return txRuleError(wire.RejectNonstandard,
296 "transaction is not finalized")
299 // Since extremely large transactions with a lot of inputs can cost
300 // almost as much to process as the sender fees, limit the maximum
301 // size of a transaction. This also helps mitigate CPU exhaustion
303 txWeight := blockchain.GetTransactionWeight(tx)
304 if txWeight > maxStandardTxWeight {
305 str := fmt.Sprintf("weight of transaction %v is larger than max "+
306 "allowed weight of %v", txWeight, maxStandardTxWeight)
307 return txRuleError(wire.RejectNonstandard, str)
310 for i, txIn := range msgTx.TxIn {
311 // Each transaction input signature script must not exceed the
312 // maximum size allowed for a standard transaction. See
313 // the comment on maxStandardSigScriptSize for more details.
314 sigScriptLen := len(txIn.SignatureScript)
315 if sigScriptLen > maxStandardSigScriptSize {
316 str := fmt.Sprintf("transaction input %d: signature "+
317 "script size of %d bytes is large than max "+
318 "allowed size of %d bytes", i, sigScriptLen,
319 maxStandardSigScriptSize)
320 return txRuleError(wire.RejectNonstandard, str)
323 // Each transaction input signature script must only contain
324 // opcodes which push data onto the stack.
325 if !txscript.IsPushOnlyScript(txIn.SignatureScript) {
326 str := fmt.Sprintf("transaction input %d: signature "+
327 "script is not push only", i)
328 return txRuleError(wire.RejectNonstandard, str)
332 // None of the output public key scripts can be a non-standard script or
333 // be "dust" (except when the script is a null data script).
334 numNullDataOutputs := 0
335 for i, txOut := range msgTx.TxOut {
336 scriptClass := txscript.GetScriptClass(txOut.PkScript)
337 err := checkPkScriptStandard(txOut.PkScript, scriptClass)
339 // Attempt to extract a reject code from the error so
340 // it can be retained. When not possible, fall back to
341 // a non standard error.
342 rejectCode := wire.RejectNonstandard
343 if rejCode, found := extractRejectCode(err); found {
346 str := fmt.Sprintf("transaction output %d: %v", i, err)
347 return txRuleError(rejectCode, str)
350 // Accumulate the number of outputs which only carry data. For
351 // all other script types, ensure the output value is not
353 if scriptClass == txscript.NullDataTy {
355 } else if isDust(txOut, minRelayTxFee) {
356 str := fmt.Sprintf("transaction output %d: payment "+
357 "of %d is dust", i, txOut.Value)
358 return txRuleError(wire.RejectDust, str)
362 // A standard transaction must not have more than one output script that
363 // only carries data.
364 if numNullDataOutputs > 1 {
365 str := "more than one transaction output in a nulldata script"
366 return txRuleError(wire.RejectNonstandard, str)
372 // GetTxVirtualSize computes the virtual size of a given transaction. A
373 // transaction's virtual size is based off its weight, creating a discount for
374 // any witness data it contains, proportional to the current
375 // blockchain.WitnessScaleFactor value.
376 func GetTxVirtualSize(tx *btcutil.Tx) int64 {
377 // vSize := (weight(tx) + 3) / 4
378 // := (((baseSize * 3) + totalSize) + 3) / 4
379 // We add 3 here as a way to compute the ceiling of the prior arithmetic
380 // to 4. The division by 4 creates a discount for wit witness data.
381 return (blockchain.GetTransactionWeight(tx) + (blockchain.WitnessScaleFactor - 1)) /
382 blockchain.WitnessScaleFactor