1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or https://www.opensource.org/licenses/mit-license.php .
6 #ifndef BITCOIN_SCRIPT_INTERPRETER_H
7 #define BITCOIN_SCRIPT_INTERPRETER_H
10 #include "script_error.h"
11 #include "pbaas/crosschainrpc.h"
12 #include "primitives/transaction.h"
13 #include "script/cc.h"
26 /** Special case nIn for signing JoinSplits. */
27 const unsigned int NOT_AN_INPUT = UINT_MAX;
29 /** Signature hash types/flags */
35 SIGHASH_ANYONECANPAY = 0x80,
38 /** Script verification flags */
41 SCRIPT_VERIFY_NONE = 0,
43 // Evaluate P2SH subscripts (softfork safe, BIP16).
44 SCRIPT_VERIFY_P2SH = (1U << 0),
46 // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
47 // Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure.
48 // (softfork safe, but not used or intended as a consensus rule).
49 SCRIPT_VERIFY_STRICTENC = (1U << 1),
51 // Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1)
52 // In Zcash this is required, and validation of non-strict-DER signatures is not implemented.
53 //SCRIPT_VERIFY_DERSIG = (1U << 2),
55 // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
56 // (softfork safe, BIP62 rule 5).
57 SCRIPT_VERIFY_LOW_S = (1U << 3),
59 // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7).
60 SCRIPT_VERIFY_NULLDUMMY = (1U << 4),
62 // Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2).
63 SCRIPT_VERIFY_SIGPUSHONLY = (1U << 5),
65 // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
66 // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
67 // any other push causes the script to fail (BIP62 rule 3).
68 // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
70 SCRIPT_VERIFY_MINIMALDATA = (1U << 6),
72 // Discourage use of NOPs reserved for upgrades (NOP1-10)
74 // Provided so that nodes can avoid accepting or mining transactions
75 // containing executed NOP's whose meaning may change after a soft-fork,
76 // thus rendering the script invalid; with this flag set executing
77 // discouraged NOPs fails the script. This verification flag will never be
78 // a mandatory flag applied to scripts in a block. NOPs that are not
79 // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
80 SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1U << 7),
82 // Require that only a single stack element remains after evaluation. This changes the success criterion from
83 // "At least one stack element must remain, and when interpreted as a boolean, it must be true" to
84 // "Exactly one stack element must remain, and when interpreted as a boolean, it must be true".
85 // (softfork safe, BIP62 rule 6)
86 // Note: CLEANSTACK should never be used without P2SH.
87 SCRIPT_VERIFY_CLEANSTACK = (1U << 8),
89 // Verify CHECKLOCKTIMEVERIFY
91 // See BIP65 for details.
92 SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1U << 9),
95 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror);
97 struct PrecomputedTransactionData
99 uint256 hashPrevouts, hashSequence, hashOutputs, hashJoinSplits, hashShieldedSpends, hashShieldedOutputs;
101 PrecomputedTransactionData(const CTransaction& tx);
106 SIGVERSION_SPROUT = 0,
107 SIGVERSION_OVERWINTER = 1,
108 SIGVERSION_SAPLING = 2,
111 // smart transactions are derived from crypto-conditions, but they are not the same thing. A smart transaction is described
112 // along with any eval-specific parameters, as an object encoded in the COptCCParams following the OP_CHECK_CRYPTOCONDITION opcode
113 // of a script. smart transactions are not encoded with ASN.1, but with standard Bitcoin serialization and an object model
114 // defined in PBaaS. while as of this comment, the cryptocondition code is used to validate crypto-conditions, that is only
115 // internally to determine thresholds and remain compatible with evals. The protocol contains only PBaaS serialized descriptions,
116 // and the signatures contain a vector of this object, serialized in one fulfillment that gets updated for multisig.
117 class CSmartTransactionSignature
122 SIGTYPE_SECP256K1 = 1,
123 SIGTYPE_SECP256K1_LEN = 64,
128 std::vector<unsigned char> pubKeyData;
129 std::vector<unsigned char> signature;
131 CSmartTransactionSignature() : sigType(SIGTYPE_NONE) {}
132 CSmartTransactionSignature(uint8_t sType, const std::vector<unsigned char> &pkData, const std::vector<unsigned char> &sig) : sigType(sType), pubKeyData(pubKeyData), signature(sig) {}
133 CSmartTransactionSignature(uint8_t sType, const CPubKey &pk, const std::vector<unsigned char> &sig) : sigType(sType), pubKeyData(pk.begin(), pk.end()), signature(sig) {}
134 CSmartTransactionSignature(const std::vector<unsigned char> &asVector)
136 ::FromVector(asVector, *this);
139 ADD_SERIALIZE_METHODS;
141 template <typename Stream, typename Operation>
142 inline void SerializationOp(Stream& s, Operation ser_action) {
144 READWRITE(pubKeyData);
145 READWRITE(signature);
148 UniValue ToUniValue() const
150 UniValue obj(UniValue::VOBJ);
152 obj.push_back(Pair("signaturetype", (int)sigType));
153 obj.push_back(Pair("publickeydata", HexBytes(&pubKeyData[0], pubKeyData.size())));
154 obj.push_back(Pair("signature", HexBytes(&signature[0], signature.size())));
160 return (sigType == SIGTYPE_SECP256K1 || sigType == SIGTYPE_FALCON) &&
161 CPubKey(pubKeyData).IsFullyValid();
165 class CSmartTransactionSignatures
175 std::map<uint160, CSmartTransactionSignature> signatures;
177 CSmartTransactionSignatures() : version(VERSION) {}
178 CSmartTransactionSignatures(uint8_t hashType, const std::map<uint160, CSmartTransactionSignature> &signatureMap, uint8_t ver=VERSION) : version(ver), sigHashType(hashType), signatures(signatureMap) {}
179 CSmartTransactionSignatures(const std::vector<unsigned char> &asVector)
181 ::FromVector(asVector, *this);
184 ADD_SERIALIZE_METHODS;
186 template <typename Stream, typename Operation>
187 inline void SerializationOp(Stream& s, Operation ser_action) {
189 READWRITE(sigHashType);
190 std::vector<CSmartTransactionSignature> sigVec;
191 if (ser_action.ForRead())
194 for (auto oneSig : sigVec)
196 if (oneSig.sigType == oneSig.SIGTYPE_SECP256K1)
198 CPubKey pk(oneSig.pubKeyData);
199 if (pk.IsFullyValid())
201 signatures[pk.GetID()] = oneSig;
208 for (auto oneSigPair : signatures)
210 sigVec.push_back(oneSigPair.second);
216 bool AddSignature(const CSmartTransactionSignature &oneSig)
218 if (oneSig.sigType == oneSig.SIGTYPE_SECP256K1)
220 CPubKey pk(oneSig.pubKeyData);
221 if (pk.IsFullyValid())
223 signatures[pk.GetID()] = oneSig;
230 UniValue ToUniValue() const
232 UniValue obj(UniValue::VOBJ);
234 obj.push_back(Pair("version", (int)version));
235 obj.push_back(Pair("signaturehashtype", (int)sigHashType));
236 UniValue uniSigs(UniValue::VARR);
237 for (auto sig : signatures)
239 uniSigs.push_back(sig.second.ToUniValue());
241 obj.push_back(Pair("signatures", uniSigs));
247 if (!(version >= FIRST_VERSION && version <= LAST_VERSION))
251 for (auto oneSig : signatures)
253 if (oneSig.second.sigType == oneSig.second.SIGTYPE_SECP256K1)
255 CPubKey pk(oneSig.second.pubKeyData);
256 uint160 pubKeyHash = pk.GetID();
257 //printf("pk.IsFullyValid(): %s, pk.GetID(): %s, oneSig.first: %s\n", pk.IsFullyValid() ? "true" : "false", pk.GetID().GetHex().c_str(), oneSig.first.GetHex().c_str());
258 if (!pk.IsFullyValid() || pk.GetID() != oneSig.first)
263 else if (oneSig.second.sigType == oneSig.second.SIGTYPE_FALCON)
275 std::vector<unsigned char> AsVector()
277 return ::AsVector(*this);
281 uint256 SignatureHash(
282 const CScript &scriptCode,
283 const CTransaction& txTo,
286 const CAmount& amount,
287 uint32_t consensusBranchId,
288 const PrecomputedTransactionData* cache = NULL);
290 class BaseSignatureChecker
293 virtual bool CheckSig(
294 const std::vector<unsigned char>& scriptSig,
295 const std::vector<unsigned char>& vchPubKey,
296 const CScript& scriptCode,
297 uint32_t consensusBranchId) const
302 virtual bool CheckLockTime(const CScriptNum& nLockTime) const
307 virtual int CheckCryptoCondition(
308 const std::vector<unsigned char>& condBin,
309 const std::vector<unsigned char>& ffillBin,
310 const CScript& scriptCode,
311 uint32_t consensusBranchId) const
316 static std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> ExtractIDMap(const CScript &scriptPubKeyIn, const CKeyStore &keystore, uint32_t spendHeight=INT32_MAX); // use wallet
318 virtual void SetIDMap(const std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> &map) {}
319 virtual std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> IDMap()
321 return std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>>();
323 virtual bool IsIDMapSet() const { return false; }
324 virtual bool CanValidateIDs() const { return false; }
326 virtual ~BaseSignatureChecker() {}
329 class TransactionSignatureChecker : public BaseSignatureChecker
332 const CTransaction* txTo;
334 const CAmount amount;
335 const PrecomputedTransactionData* txdata;
336 std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> idMap;
339 virtual bool VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const;
342 TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> *pIdMap);
343 TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData& txdataIn, const std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> *pIdMap);
344 TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const CScript *pScriptPubKeyIn=nullptr, const CKeyStore *pKeyStore=nullptr, uint32_t spendHeight=INT32_MAX);
345 TransactionSignatureChecker(const CTransaction* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData& txdataIn, const CScript *pScriptPubKeyIn=nullptr, const CKeyStore *pKeyStore=nullptr, uint32_t spendHeight=INT32_MAX);
346 bool CheckSig(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, uint32_t consensusBranchId) const;
347 bool CheckLockTime(const CScriptNum& nLockTime) const;
348 void SetIDMap(const std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> &map)
353 std::map<uint160, std::pair<int, std::vector<std::vector<unsigned char>>>> IDMap()
357 bool IsIDMapSet() const { return idMapSet; }
358 int CheckCryptoCondition(
359 const std::vector<unsigned char>& condBin,
360 const std::vector<unsigned char>& ffillBin,
361 const CScript& scriptCode,
362 uint32_t consensusBranchId) const;
363 virtual int CheckEvalCondition(const CC *cond, int fulfilled) const;
366 class MutableTransactionSignatureChecker : public TransactionSignatureChecker
369 const CTransaction txTo;
372 MutableTransactionSignatureChecker(const CMutableTransaction* txToIn, unsigned int nInIn, const CAmount& amount) : TransactionSignatureChecker(&txTo, nInIn, amount), txTo(*txToIn) {}
376 std::vector<std::vector<unsigned char> >& stack,
377 const CScript& script,
379 const BaseSignatureChecker& checker,
380 uint32_t consensusBranchId,
381 ScriptError* error = NULL);
383 const CScript& scriptSig,
384 const CScript& scriptPubKey,
386 const BaseSignatureChecker& checker,
387 uint32_t consensusBranchId,
388 ScriptError* serror = NULL);
389 #endif // BITCOIN_SCRIPT_INTERPRETER_H