1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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"
21 // Maximum number of bytes pushable to the stack
22 static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
= 520;
24 // Maximum number of non-push operations per script
25 static const int MAX_OPS_PER_SCRIPT
= 201;
27 // Maximum number of public keys per multisig
28 static const int MAX_PUBKEYS_PER_MULTISIG
= 20;
30 // Maximum script length in bytes
31 static const int MAX_SCRIPT_SIZE
= 10000;
33 // Maximum number of values on script interpreter stack
34 static const int MAX_STACK_SIZE
= 1000;
36 // Threshold for nLockTime: below this value it is interpreted as block number,
37 // otherwise as UNIX timestamp.
38 static const unsigned int LOCKTIME_THRESHOLD
= 500000000; // Tue Nov 5 00:53:20 1985 UTC
41 std::vector
<unsigned char> ToByteVector(const T
& in
)
43 return std::vector
<unsigned char>(in
.begin(), in
.end());
89 OP_FROMALTSTACK
= 0x6c,
121 OP_EQUALVERIFY
= 0x88,
146 OP_NUMEQUALVERIFY
= 0x9d,
147 OP_NUMNOTEQUAL
= 0x9e,
149 OP_GREATERTHAN
= 0xa0,
150 OP_LESSTHANOREQUAL
= 0xa1,
151 OP_GREATERTHANOREQUAL
= 0xa2,
163 OP_CODESEPARATOR
= 0xab,
165 OP_CHECKSIGVERIFY
= 0xad,
166 OP_CHECKMULTISIG
= 0xae,
167 OP_CHECKMULTISIGVERIFY
= 0xaf,
171 OP_CHECKLOCKTIMEVERIFY
= 0xb1,
172 OP_NOP2
= OP_CHECKLOCKTIMEVERIFY
,
173 OP_CHECKSEQUENCEVERIFY
= 0xb2,
174 OP_NOP3
= OP_CHECKSEQUENCEVERIFY
,
184 // template matching params
185 OP_SMALLINTEGER
= 0xfa,
187 OP_PUBKEYHASH
= 0xfd,
190 OP_INVALIDOPCODE
= 0xff,
193 const char* GetOpName(opcodetype opcode
);
195 class scriptnum_error
: public std::runtime_error
198 explicit scriptnum_error(const std::string
& str
) : std::runtime_error(str
) {}
204 * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers.
205 * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1],
206 * but results may overflow (and are valid as long as they are not used in a subsequent
207 * numeric operation). CScriptNum enforces those semantics by storing results as
208 * an int64 and allowing out-of-range values to be returned as a vector of bytes but
209 * throwing an exception if arithmetic is done or the result is interpreted as an integer.
213 explicit CScriptNum(const int64_t& n
)
218 static const size_t nDefaultMaxNumSize
= 4;
220 explicit CScriptNum(const std::vector
<unsigned char>& vch
, bool fRequireMinimal
,
221 const size_t nMaxNumSize
= nDefaultMaxNumSize
)
223 if (vch
.size() > nMaxNumSize
) {
224 throw scriptnum_error("script number overflow");
226 if (fRequireMinimal
&& vch
.size() > 0) {
227 // Check that the number is encoded with the minimum possible
230 // If the most-significant-byte - excluding the sign bit - is zero
231 // then we're not minimal. Note how this test also rejects the
232 // negative-zero encoding, 0x80.
233 if ((vch
.back() & 0x7f) == 0) {
234 // One exception: if there's more than one byte and the most
235 // significant bit of the second-most-significant-byte is set
236 // it would conflict with the sign bit. An example of this case
237 // is +-255, which encode to 0xff00 and 0xff80 respectively.
239 if (vch
.size() <= 1 || (vch
[vch
.size() - 2] & 0x80) == 0) {
240 throw scriptnum_error("non-minimally encoded script number");
244 m_value
= set_vch(vch
);
247 inline bool operator==(const int64_t& rhs
) const { return m_value
== rhs
; }
248 inline bool operator!=(const int64_t& rhs
) const { return m_value
!= rhs
; }
249 inline bool operator<=(const int64_t& rhs
) const { return m_value
<= rhs
; }
250 inline bool operator< (const int64_t& rhs
) const { return m_value
< rhs
; }
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
; }
254 inline bool operator==(const CScriptNum
& rhs
) const { return operator==(rhs
.m_value
); }
255 inline bool operator!=(const CScriptNum
& rhs
) const { return operator!=(rhs
.m_value
); }
256 inline bool operator<=(const CScriptNum
& rhs
) const { return operator<=(rhs
.m_value
); }
257 inline bool operator< (const CScriptNum
& rhs
) const { return operator< (rhs
.m_value
); }
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
); }
261 inline CScriptNum
operator+( const int64_t& rhs
) const { return CScriptNum(m_value
+ rhs
);}
262 inline CScriptNum
operator-( const int64_t& rhs
) const { return CScriptNum(m_value
- rhs
);}
263 inline CScriptNum
operator+( const CScriptNum
& rhs
) const { return operator+(rhs
.m_value
); }
264 inline CScriptNum
operator-( const CScriptNum
& rhs
) const { return operator-(rhs
.m_value
); }
266 inline CScriptNum
& operator+=( const CScriptNum
& rhs
) { return operator+=(rhs
.m_value
); }
267 inline CScriptNum
& operator-=( const CScriptNum
& rhs
) { return operator-=(rhs
.m_value
); }
269 inline CScriptNum
operator&( const int64_t& rhs
) const { return CScriptNum(m_value
& rhs
);}
270 inline CScriptNum
operator&( const CScriptNum
& rhs
) const { return operator&(rhs
.m_value
); }
272 inline CScriptNum
& operator&=( const CScriptNum
& rhs
) { return operator&=(rhs
.m_value
); }
274 inline CScriptNum
operator-() const
276 assert(m_value
!= std::numeric_limits
<int64_t>::min());
277 return CScriptNum(-m_value
);
280 inline CScriptNum
& operator=( const int64_t& rhs
)
286 inline CScriptNum
& operator+=( const int64_t& rhs
)
288 assert(rhs
== 0 || (rhs
> 0 && m_value
<= std::numeric_limits
<int64_t>::max() - rhs
) ||
289 (rhs
< 0 && m_value
>= std::numeric_limits
<int64_t>::min() - rhs
));
294 inline CScriptNum
& operator-=( const int64_t& rhs
)
296 assert(rhs
== 0 || (rhs
> 0 && m_value
>= std::numeric_limits
<int64_t>::min() + rhs
) ||
297 (rhs
< 0 && m_value
<= std::numeric_limits
<int64_t>::max() + rhs
));
302 inline CScriptNum
& operator&=( const int64_t& rhs
)
310 if (m_value
> std::numeric_limits
<int>::max())
311 return std::numeric_limits
<int>::max();
312 else if (m_value
< std::numeric_limits
<int>::min())
313 return std::numeric_limits
<int>::min();
317 std::vector
<unsigned char> getvch() const
319 return serialize(m_value
);
322 static std::vector
<unsigned char> serialize(const int64_t& value
)
325 return std::vector
<unsigned char>();
327 std::vector
<unsigned char> result
;
328 const bool neg
= value
< 0;
329 uint64_t absvalue
= neg
? -value
: value
;
333 result
.push_back(absvalue
& 0xff);
337 // - If the most significant byte is >= 0x80 and the value is positive, push a
338 // new zero-byte to make the significant byte < 0x80 again.
340 // - If the most significant byte is >= 0x80 and the value is negative, push a
341 // new 0x80 byte that will be popped off when converting to an integral.
343 // - If the most significant byte is < 0x80 and the value is negative, add
344 // 0x80 to it, since it will be subtracted and interpreted as a negative when
345 // converting to an integral.
347 if (result
.back() & 0x80)
348 result
.push_back(neg
? 0x80 : 0);
350 result
.back() |= 0x80;
356 static int64_t set_vch(const std::vector
<unsigned char>& vch
)
362 for (size_t i
= 0; i
!= vch
.size(); ++i
)
363 result
|= static_cast<int64_t>(vch
[i
]) << 8*i
;
365 // If the input vector's most significant byte is 0x80, remove it from
366 // the result's msb and return a negative.
367 if (vch
.back() & 0x80)
368 return -((int64_t)(result
& ~(0x80ULL
<< (8 * (vch
.size() - 1)))));
376 typedef prevector
<28, unsigned char> CScriptBase
;
378 /** Serialized script, used inside transaction inputs and outputs */
379 class CScript
: public CScriptBase
382 CScript
& push_int64(int64_t n
)
384 if (n
== -1 || (n
>= 1 && n
<= 16))
386 push_back(n
+ (OP_1
- 1));
394 *this << CScriptNum::serialize(n
);
400 CScript(const_iterator pbegin
, const_iterator pend
) : CScriptBase(pbegin
, pend
) { }
401 CScript(std::vector
<unsigned char>::const_iterator pbegin
, std::vector
<unsigned char>::const_iterator pend
) : CScriptBase(pbegin
, pend
) { }
402 CScript(const unsigned char* pbegin
, const unsigned char* pend
) : CScriptBase(pbegin
, pend
) { }
404 CScript
& operator+=(const CScript
& b
)
406 insert(end(), b
.begin(), b
.end());
410 friend CScript
operator+(const CScript
& a
, const CScript
& b
)
417 CScript(int64_t b
) { operator<<(b
); }
419 explicit CScript(opcodetype b
) { operator<<(b
); }
420 explicit CScript(const CScriptNum
& b
) { operator<<(b
); }
421 explicit CScript(const std::vector
<unsigned char>& b
) { operator<<(b
); }
424 CScript
& operator<<(int64_t b
) { return push_int64(b
); }
426 CScript
& operator<<(opcodetype opcode
)
428 if (opcode
< 0 || opcode
> 0xff)
429 throw std::runtime_error("CScript::operator<<(): invalid opcode");
430 insert(end(), (unsigned char)opcode
);
434 CScript
& operator<<(const CScriptNum
& b
)
440 CScript
& operator<<(const std::vector
<unsigned char>& b
)
442 if (b
.size() < OP_PUSHDATA1
)
444 insert(end(), (unsigned char)b
.size());
446 else if (b
.size() <= 0xff)
448 insert(end(), OP_PUSHDATA1
);
449 insert(end(), (unsigned char)b
.size());
451 else if (b
.size() <= 0xffff)
453 insert(end(), OP_PUSHDATA2
);
455 WriteLE16(_data
, b
.size());
456 insert(end(), _data
, _data
+ sizeof(_data
));
460 insert(end(), OP_PUSHDATA4
);
462 WriteLE32(_data
, b
.size());
463 insert(end(), _data
, _data
+ sizeof(_data
));
465 insert(end(), b
.begin(), b
.end());
469 CScript
& operator<<(const CScript
& b
)
471 // I'm not sure if this should push the script or concatenate scripts.
472 // If there's ever a use for pushing a script onto a script, delete this member fn
473 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
478 bool GetOp(iterator
& pc
, opcodetype
& opcodeRet
, std::vector
<unsigned char>& vchRet
)
480 // Wrapper so it can be called with either iterator or const_iterator
481 const_iterator pc2
= pc
;
482 bool fRet
= GetOp2(pc2
, opcodeRet
, &vchRet
);
483 pc
= begin() + (pc2
- begin());
487 bool GetOp(iterator
& pc
, opcodetype
& opcodeRet
)
489 const_iterator pc2
= pc
;
490 bool fRet
= GetOp2(pc2
, opcodeRet
, NULL
);
491 pc
= begin() + (pc2
- begin());
495 bool GetOp(const_iterator
& pc
, opcodetype
& opcodeRet
, std::vector
<unsigned char>& vchRet
) const
497 return GetOp2(pc
, opcodeRet
, &vchRet
);
500 bool GetOp(const_iterator
& pc
, opcodetype
& opcodeRet
) const
502 return GetOp2(pc
, opcodeRet
, NULL
);
505 bool GetOp2(const_iterator
& pc
, opcodetype
& opcodeRet
, std::vector
<unsigned char>* pvchRet
) const
507 opcodeRet
= OP_INVALIDOPCODE
;
516 unsigned int opcode
= *pc
++;
519 if (opcode
<= OP_PUSHDATA4
)
521 unsigned int nSize
= 0;
522 if (opcode
< OP_PUSHDATA1
)
526 else if (opcode
== OP_PUSHDATA1
)
532 else if (opcode
== OP_PUSHDATA2
)
536 nSize
= ReadLE16(&pc
[0]);
539 else if (opcode
== OP_PUSHDATA4
)
543 nSize
= ReadLE32(&pc
[0]);
546 if (end() - pc
< 0 || (unsigned int)(end() - pc
) < nSize
)
549 pvchRet
->assign(pc
, pc
+ nSize
);
553 opcodeRet
= (opcodetype
)opcode
;
557 /** Encode/decode small integers: */
558 static int DecodeOP_N(opcodetype opcode
)
562 assert(opcode
>= OP_1
&& opcode
<= OP_16
);
563 return (int)opcode
- (int)(OP_1
- 1);
565 static opcodetype
EncodeOP_N(int n
)
567 assert(n
>= 0 && n
<= 16);
570 return (opcodetype
)(OP_1
+n
-1);
573 int FindAndDelete(const CScript
& b
)
579 iterator pc
= begin(), pc2
= begin();
583 result
.insert(result
.end(), pc2
, pc
);
584 while (static_cast<size_t>(end() - pc
) >= b
.size() && std::equal(b
.begin(), b
.end(), pc
))
591 while (GetOp(pc
, opcode
));
594 result
.insert(result
.end(), pc2
, end());
600 int Find(opcodetype op
) const
604 for (const_iterator pc
= begin(); pc
!= end() && GetOp(pc
, opcode
);)
611 * Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
612 * as 20 sigops. With pay-to-script-hash, that changed:
613 * CHECKMULTISIGs serialized in scriptSigs are
614 * counted more accurately, assuming they are of the form
615 * ... OP_N CHECKMULTISIG ...
617 unsigned int GetSigOpCount(bool fAccurate
) const;
620 * Accurately count sigOps, including sigOps in
621 * pay-to-script-hash transactions:
623 unsigned int GetSigOpCount(const CScript
& scriptSig
) const;
625 bool IsPayToScriptHash() const;
626 bool IsPayToWitnessScriptHash() const;
627 bool IsWitnessProgram(int& version
, std::vector
<unsigned char>& program
) const;
629 /** Called by IsStandardTx and P2SH/BIP62 VerifyScript (which makes it consensus-critical). */
630 bool IsPushOnly(const_iterator pc
) const;
631 bool IsPushOnly() const;
634 * Returns whether the script is guaranteed to fail at execution,
635 * regardless of the initial stack. This allows outputs to be pruned
636 * instantly when entering the UTXO set.
638 bool IsUnspendable() const
640 return (size() > 0 && *begin() == OP_RETURN
) || (size() > MAX_SCRIPT_SIZE
);
645 // The default std::vector::clear() does not release memory.
646 CScriptBase().swap(*this);
650 struct CScriptWitness
652 // Note that this encodes the data elements being pushed, rather than
653 // encoding them as a CScript that pushes them.
654 std::vector
<std::vector
<unsigned char> > stack
;
656 // Some compilers complain without a default constructor
659 bool IsNull() const { return stack
.empty(); }
661 void SetNull() { stack
.clear(); stack
.shrink_to_fit(); }
663 std::string
ToString() const;
669 CScript reserveScript
;
670 virtual void KeepScript() {}
672 virtual ~CReserveScript() {}
675 #endif // BITCOIN_SCRIPT_SCRIPT_H