1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_SCRIPT_SCRIPT_H
7 #define BITCOIN_SCRIPT_SCRIPT_H
9 #include <crypto/common.h>
10 #include <prevector.h>
11 #include <serialize.h>
22 // Maximum number of bytes pushable to the stack
23 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
= 520;
25 // Maximum number of non-push operations per script
26 static const int MAX_OPS_PER_SCRIPT
= 201;
28 // Maximum number of public keys per multisig
29 static const int MAX_PUBKEYS_PER_MULTISIG
= 20;
31 // Maximum script length in bytes
32 static const int MAX_SCRIPT_SIZE
= 10000;
34 // Maximum number of values on script interpreter stack
35 static const int MAX_STACK_SIZE
= 1000;
37 // Threshold for nLockTime: below this value it is interpreted as block number,
38 // otherwise as UNIX timestamp.
39 static const unsigned int LOCKTIME_THRESHOLD
= 500000000; // Tue Nov 5 00:53:20 1985 UTC
42 std::vector
<unsigned char> ToByteVector(const T
& in
)
44 return std::vector
<unsigned char>(in
.begin(), in
.end());
90 OP_FROMALTSTACK
= 0x6c,
122 OP_EQUALVERIFY
= 0x88,
147 OP_NUMEQUALVERIFY
= 0x9d,
148 OP_NUMNOTEQUAL
= 0x9e,
150 OP_GREATERTHAN
= 0xa0,
151 OP_LESSTHANOREQUAL
= 0xa1,
152 OP_GREATERTHANOREQUAL
= 0xa2,
164 OP_CODESEPARATOR
= 0xab,
166 OP_CHECKSIGVERIFY
= 0xad,
167 OP_CHECKMULTISIG
= 0xae,
168 OP_CHECKMULTISIGVERIFY
= 0xaf,
172 OP_CHECKLOCKTIMEVERIFY
= 0xb1,
173 OP_NOP2
= OP_CHECKLOCKTIMEVERIFY
,
174 OP_CHECKSEQUENCEVERIFY
= 0xb2,
175 OP_NOP3
= OP_CHECKSEQUENCEVERIFY
,
185 // template matching params
186 OP_SMALLINTEGER
= 0xfa,
188 OP_PUBKEYHASH
= 0xfd,
191 OP_INVALIDOPCODE
= 0xff,
194 // Maximum value that an opcode can be
195 static const unsigned int MAX_OPCODE
= OP_NOP10
;
197 const char* GetOpName(opcodetype opcode
);
199 class scriptnum_error
: public std::runtime_error
202 explicit scriptnum_error(const std::string
& str
) : std::runtime_error(str
) {}
208 * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
209 * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
210 * but results may overflow (and are valid as long as they are not used in a subsequent
211 * numeric operation). CScriptNum enforces those semantics by storing results as
212 * an int64 and allowing out-of-range values to be returned as a vector of bytes but
213 * throwing an exception if arithmetic is done or the result is interpreted as an integer.
217 explicit CScriptNum(const int64_t& n
)
222 static const size_t nDefaultMaxNumSize
= 4;
224 explicit CScriptNum(const std::vector
<unsigned char>& vch
, bool fRequireMinimal
,
225 const size_t nMaxNumSize
= nDefaultMaxNumSize
)
227 if (vch
.size() > nMaxNumSize
) {
228 throw scriptnum_error("script number overflow");
230 if (fRequireMinimal
&& vch
.size() > 0) {
231 // Check that the number is encoded with the minimum possible
234 // If the most-significant-byte - excluding the sign bit - is zero
235 // then we're not minimal. Note how this test also rejects the
236 // negative-zero encoding, 0x80.
237 if ((vch
.back() & 0x7f) == 0) {
238 // One exception: if there's more than one byte and the most
239 // significant bit of the second-most-significant-byte is set
240 // it would conflict with the sign bit. An example of this case
241 // is +-255, which encode to 0xff00 and 0xff80 respectively.
243 if (vch
.size() <= 1 || (vch
[vch
.size() - 2] & 0x80) == 0) {
244 throw scriptnum_error("non-minimally encoded script number");
248 m_value
= set_vch(vch
);
251 inline bool operator==(const int64_t& rhs
) const { return m_value
== rhs
; }
252 inline bool operator!=(const int64_t& rhs
) const { return m_value
!= rhs
; }
253 inline bool operator<=(const int64_t& rhs
) const { return m_value
<= rhs
; }
254 inline bool operator< (const int64_t& rhs
) const { return m_value
< rhs
; }
255 inline bool operator>=(const int64_t& rhs
) const { return m_value
>= rhs
; }
256 inline bool operator> (const int64_t& rhs
) const { return m_value
> rhs
; }
258 inline bool operator==(const CScriptNum
& rhs
) const { return operator==(rhs
.m_value
); }
259 inline bool operator!=(const CScriptNum
& rhs
) const { return operator!=(rhs
.m_value
); }
260 inline bool operator<=(const CScriptNum
& rhs
) const { return operator<=(rhs
.m_value
); }
261 inline bool operator< (const CScriptNum
& rhs
) const { return operator< (rhs
.m_value
); }
262 inline bool operator>=(const CScriptNum
& rhs
) const { return operator>=(rhs
.m_value
); }
263 inline bool operator> (const CScriptNum
& rhs
) const { return operator> (rhs
.m_value
); }
265 inline CScriptNum
operator+( const int64_t& rhs
) const { return CScriptNum(m_value
+ rhs
);}
266 inline CScriptNum
operator-( const int64_t& rhs
) const { return CScriptNum(m_value
- rhs
);}
267 inline CScriptNum
operator+( const CScriptNum
& rhs
) const { return operator+(rhs
.m_value
); }
268 inline CScriptNum
operator-( const CScriptNum
& rhs
) const { return operator-(rhs
.m_value
); }
270 inline CScriptNum
& operator+=( const CScriptNum
& rhs
) { return operator+=(rhs
.m_value
); }
271 inline CScriptNum
& operator-=( const CScriptNum
& rhs
) { return operator-=(rhs
.m_value
); }
273 inline CScriptNum
operator&( const int64_t& rhs
) const { return CScriptNum(m_value
& rhs
);}
274 inline CScriptNum
operator&( const CScriptNum
& rhs
) const { return operator&(rhs
.m_value
); }
276 inline CScriptNum
& operator&=( const CScriptNum
& rhs
) { return operator&=(rhs
.m_value
); }
278 inline CScriptNum
operator-() const
280 assert(m_value
!= std::numeric_limits
<int64_t>::min());
281 return CScriptNum(-m_value
);
284 inline CScriptNum
& operator=( const int64_t& rhs
)
290 inline CScriptNum
& operator+=( const int64_t& rhs
)
292 assert(rhs
== 0 || (rhs
> 0 && m_value
<= std::numeric_limits
<int64_t>::max() - rhs
) ||
293 (rhs
< 0 && m_value
>= std::numeric_limits
<int64_t>::min() - rhs
));
298 inline CScriptNum
& operator-=( const int64_t& rhs
)
300 assert(rhs
== 0 || (rhs
> 0 && m_value
>= std::numeric_limits
<int64_t>::min() + rhs
) ||
301 (rhs
< 0 && m_value
<= std::numeric_limits
<int64_t>::max() + rhs
));
306 inline CScriptNum
& operator&=( const int64_t& rhs
)
314 if (m_value
> std::numeric_limits
<int>::max())
315 return std::numeric_limits
<int>::max();
316 else if (m_value
< std::numeric_limits
<int>::min())
317 return std::numeric_limits
<int>::min();
321 std::vector
<unsigned char> getvch() const
323 return serialize(m_value
);
326 static std::vector
<unsigned char> serialize(const int64_t& value
)
329 return std::vector
<unsigned char>();
331 std::vector
<unsigned char> result
;
332 const bool neg
= value
< 0;
333 uint64_t absvalue
= neg
? -value
: value
;
337 result
.push_back(absvalue
& 0xff);
341 // - If the most significant byte is >= 0x80 and the value is positive, push a
342 // new zero-byte to make the significant byte < 0x80 again.
344 // - If the most significant byte is >= 0x80 and the value is negative, push a
345 // new 0x80 byte that will be popped off when converting to an integral.
347 // - If the most significant byte is < 0x80 and the value is negative, add
348 // 0x80 to it, since it will be subtracted and interpreted as a negative when
349 // converting to an integral.
351 if (result
.back() & 0x80)
352 result
.push_back(neg
? 0x80 : 0);
354 result
.back() |= 0x80;
360 static int64_t set_vch(const std::vector
<unsigned char>& vch
)
366 for (size_t i
= 0; i
!= vch
.size(); ++i
)
367 result
|= static_cast<int64_t>(vch
[i
]) << 8*i
;
369 // If the input vector's most significant byte is 0x80, remove it from
370 // the result's msb and return a negative.
371 if (vch
.back() & 0x80)
372 return -((int64_t)(result
& ~(0x80ULL
<< (8 * (vch
.size() - 1)))));
381 * We use a prevector for the script to reduce the considerable memory overhead
382 * of vectors in cases where they normally contain a small number of small elements.
383 * Tests in October 2015 showed use of this reduced dbcache memory usage by 23%
384 * and made an initial sync 13% faster.
386 typedef prevector
<28, unsigned char> CScriptBase
;
388 /** Serialized script, used inside transaction inputs and outputs */
389 class CScript
: public CScriptBase
392 CScript
& push_int64(int64_t n
)
394 if (n
== -1 || (n
>= 1 && n
<= 16))
396 push_back(n
+ (OP_1
- 1));
404 *this << CScriptNum::serialize(n
);
410 CScript(const_iterator pbegin
, const_iterator pend
) : CScriptBase(pbegin
, pend
) { }
411 CScript(std::vector
<unsigned char>::const_iterator pbegin
, std::vector
<unsigned char>::const_iterator pend
) : CScriptBase(pbegin
, pend
) { }
412 CScript(const unsigned char* pbegin
, const unsigned char* pend
) : CScriptBase(pbegin
, pend
) { }
414 ADD_SERIALIZE_METHODS
;
416 template <typename Stream
, typename Operation
>
417 inline void SerializationOp(Stream
& s
, Operation ser_action
) {
418 READWRITE(static_cast<CScriptBase
&>(*this));
421 CScript
& operator+=(const CScript
& b
)
423 reserve(size() + b
.size());
424 insert(end(), b
.begin(), b
.end());
428 friend CScript
operator+(const CScript
& a
, const CScript
& b
)
435 CScript(int64_t b
) { operator<<(b
); }
437 explicit CScript(opcodetype b
) { operator<<(b
); }
438 explicit CScript(const CScriptNum
& b
) { operator<<(b
); }
439 explicit CScript(const std::vector
<unsigned char>& b
) { operator<<(b
); }
442 CScript
& operator<<(int64_t b
) { return push_int64(b
); }
444 CScript
& operator<<(opcodetype opcode
)
446 if (opcode
< 0 || opcode
> 0xff)
447 throw std::runtime_error("CScript::operator<<(): invalid opcode");
448 insert(end(), (unsigned char)opcode
);
452 CScript
& operator<<(const CScriptNum
& b
)
458 CScript
& operator<<(const std::vector
<unsigned char>& b
)
460 if (b
.size() < OP_PUSHDATA1
)
462 insert(end(), (unsigned char)b
.size());
464 else if (b
.size() <= 0xff)
466 insert(end(), OP_PUSHDATA1
);
467 insert(end(), (unsigned char)b
.size());
469 else if (b
.size() <= 0xffff)
471 insert(end(), OP_PUSHDATA2
);
473 WriteLE16(_data
, b
.size());
474 insert(end(), _data
, _data
+ sizeof(_data
));
478 insert(end(), OP_PUSHDATA4
);
480 WriteLE32(_data
, b
.size());
481 insert(end(), _data
, _data
+ sizeof(_data
));
483 insert(end(), b
.begin(), b
.end());
487 CScript
& operator<<(const CScript
& b
)
489 // I'm not sure if this should push the script or concatenate scripts.
490 // If there's ever a use for pushing a script onto a script, delete this member fn
491 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
496 bool GetOp(iterator
& pc
, opcodetype
& opcodeRet
, std::vector
<unsigned char>& vchRet
)
498 // Wrapper so it can be called with either iterator or const_iterator
499 const_iterator pc2
= pc
;
500 bool fRet
= GetOp2(pc2
, opcodeRet
, &vchRet
);
501 pc
= begin() + (pc2
- begin());
505 bool GetOp(iterator
& pc
, opcodetype
& opcodeRet
)
507 const_iterator pc2
= pc
;
508 bool fRet
= GetOp2(pc2
, opcodeRet
, nullptr);
509 pc
= begin() + (pc2
- begin());
513 bool GetOp(const_iterator
& pc
, opcodetype
& opcodeRet
, std::vector
<unsigned char>& vchRet
) const
515 return GetOp2(pc
, opcodeRet
, &vchRet
);
518 bool GetOp(const_iterator
& pc
, opcodetype
& opcodeRet
) const
520 return GetOp2(pc
, opcodeRet
, nullptr);
523 bool GetOp2(const_iterator
& pc
, opcodetype
& opcodeRet
, std::vector
<unsigned char>* pvchRet
) const
525 opcodeRet
= OP_INVALIDOPCODE
;
534 unsigned int opcode
= *pc
++;
537 if (opcode
<= OP_PUSHDATA4
)
539 unsigned int nSize
= 0;
540 if (opcode
< OP_PUSHDATA1
)
544 else if (opcode
== OP_PUSHDATA1
)
550 else if (opcode
== OP_PUSHDATA2
)
554 nSize
= ReadLE16(&pc
[0]);
557 else if (opcode
== OP_PUSHDATA4
)
561 nSize
= ReadLE32(&pc
[0]);
564 if (end() - pc
< 0 || (unsigned int)(end() - pc
) < nSize
)
567 pvchRet
->assign(pc
, pc
+ nSize
);
571 opcodeRet
= (opcodetype
)opcode
;
575 /** Encode/decode small integers: */
576 static int DecodeOP_N(opcodetype opcode
)
580 assert(opcode
>= OP_1
&& opcode
<= OP_16
);
581 return (int)opcode
- (int)(OP_1
- 1);
583 static opcodetype
EncodeOP_N(int n
)
585 assert(n
>= 0 && n
<= 16);
588 return (opcodetype
)(OP_1
+n
-1);
591 int FindAndDelete(const CScript
& b
)
597 iterator pc
= begin(), pc2
= begin();
601 result
.insert(result
.end(), pc2
, pc
);
602 while (static_cast<size_t>(end() - pc
) >= b
.size() && std::equal(b
.begin(), b
.end(), pc
))
609 while (GetOp(pc
, opcode
));
612 result
.insert(result
.end(), pc2
, end());
618 int Find(opcodetype op
) const
622 for (const_iterator pc
= begin(); pc
!= end() && GetOp(pc
, opcode
);)
629 * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
630 * as 20 sigops. With pay-to-script-hash, that changed:
631 * CHECKMULTISIGs serialized in scriptSigs are
632 * counted more accurately, assuming they are of the form
633 * ... OP_N CHECKMULTISIG ...
635 unsigned int GetSigOpCount(bool fAccurate
) const;
638 * Accurately count sigOps, including sigOps in
639 * pay-to-script-hash transactions:
641 unsigned int GetSigOpCount(const CScript
& scriptSig
) const;
643 bool IsPayToScriptHash() const;
644 bool IsPayToWitnessScriptHash() const;
645 bool IsWitnessProgram(int& version
, std::vector
<unsigned char>& program
) const;
647 /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
648 bool IsPushOnly(const_iterator pc
) const;
649 bool IsPushOnly() const;
651 /** Check if the script contains valid OP_CODES */
652 bool HasValidOps() const;
655 * Returns whether the script is guaranteed to fail at execution,
656 * regardless of the initial stack. This allows outputs to be pruned
657 * instantly when entering the UTXO set.
659 bool IsUnspendable() const
661 return (size() > 0 && *begin() == OP_RETURN
) || (size() > MAX_SCRIPT_SIZE
);
666 // The default prevector::clear() does not release memory
667 CScriptBase::clear();
672 struct CScriptWitness
674 // Note that this encodes the data elements being pushed, rather than
675 // encoding them as a CScript that pushes them.
676 std::vector
<std::vector
<unsigned char> > stack
;
678 // Some compilers complain without a default constructor
681 bool IsNull() const { return stack
.empty(); }
683 void SetNull() { stack
.clear(); stack
.shrink_to_fit(); }
685 std::string
ToString() const;
691 CScript reserveScript
;
692 virtual void KeepScript() {}
694 virtual ~CReserveScript() {}
697 #endif // BITCOIN_SCRIPT_SCRIPT_H