LCOV - code coverage report
Current view: top level - src/test - script_tests.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 1118 1137 98.3 %
Date: 2020-09-26 01:30:44 Functions: 166 167 99.4 %

          Line data    Source code
       1             : // Copyright (c) 2011-2020 The Bitcoin Core developers
       2             : // Distributed under the MIT software license, see the accompanying
       3             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4             : 
       5             : #include <test/data/script_tests.json.h>
       6             : 
       7             : #include <core_io.h>
       8             : #include <key.h>
       9             : #include <rpc/util.h>
      10             : #include <script/script.h>
      11             : #include <script/script_error.h>
      12             : #include <script/sign.h>
      13             : #include <script/signingprovider.h>
      14             : #include <streams.h>
      15             : #include <test/util/setup_common.h>
      16             : #include <test/util/transaction_utils.h>
      17             : #include <util/strencodings.h>
      18             : #include <util/system.h>
      19             : 
      20             : #if defined(HAVE_CONSENSUS_LIB)
      21             : #include <script/bitcoinconsensus.h>
      22             : #endif
      23             : 
      24             : #include <stdint.h>
      25             : #include <string>
      26             : #include <vector>
      27             : 
      28             : #include <boost/test/unit_test.hpp>
      29             : 
      30             : #include <univalue.h>
      31             : 
      32             : // Uncomment if you want to output updated JSON tests.
      33             : // #define UPDATE_JSON_TESTS
      34             : 
      35             : static const unsigned int gFlags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
      36             : 
      37             : unsigned int ParseScriptFlags(std::string strFlags);
      38             : std::string FormatScriptFlags(unsigned int flags);
      39             : 
      40             : UniValue
      41          10 : read_json(const std::string& jsondata)
      42             : {
      43          10 :     UniValue v;
      44             : 
      45          10 :     if (!v.read(jsondata) || !v.isArray())
      46             :     {
      47           0 :         BOOST_ERROR("Parse error.");
      48           0 :         return UniValue(UniValue::VARR);
      49             :     }
      50          10 :     return v.get_array();
      51          10 : }
      52             : 
      53             : struct ScriptErrorDesc
      54             : {
      55             :     ScriptError_t err;
      56             :     const char *name;
      57             : };
      58             : 
      59             : static ScriptErrorDesc script_errors[]={
      60             :     {SCRIPT_ERR_OK, "OK"},
      61             :     {SCRIPT_ERR_UNKNOWN_ERROR, "UNKNOWN_ERROR"},
      62             :     {SCRIPT_ERR_EVAL_FALSE, "EVAL_FALSE"},
      63             :     {SCRIPT_ERR_OP_RETURN, "OP_RETURN"},
      64             :     {SCRIPT_ERR_SCRIPT_SIZE, "SCRIPT_SIZE"},
      65             :     {SCRIPT_ERR_PUSH_SIZE, "PUSH_SIZE"},
      66             :     {SCRIPT_ERR_OP_COUNT, "OP_COUNT"},
      67             :     {SCRIPT_ERR_STACK_SIZE, "STACK_SIZE"},
      68             :     {SCRIPT_ERR_SIG_COUNT, "SIG_COUNT"},
      69             :     {SCRIPT_ERR_PUBKEY_COUNT, "PUBKEY_COUNT"},
      70             :     {SCRIPT_ERR_VERIFY, "VERIFY"},
      71             :     {SCRIPT_ERR_EQUALVERIFY, "EQUALVERIFY"},
      72             :     {SCRIPT_ERR_CHECKMULTISIGVERIFY, "CHECKMULTISIGVERIFY"},
      73             :     {SCRIPT_ERR_CHECKSIGVERIFY, "CHECKSIGVERIFY"},
      74             :     {SCRIPT_ERR_NUMEQUALVERIFY, "NUMEQUALVERIFY"},
      75             :     {SCRIPT_ERR_BAD_OPCODE, "BAD_OPCODE"},
      76             :     {SCRIPT_ERR_DISABLED_OPCODE, "DISABLED_OPCODE"},
      77             :     {SCRIPT_ERR_INVALID_STACK_OPERATION, "INVALID_STACK_OPERATION"},
      78             :     {SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, "INVALID_ALTSTACK_OPERATION"},
      79             :     {SCRIPT_ERR_UNBALANCED_CONDITIONAL, "UNBALANCED_CONDITIONAL"},
      80             :     {SCRIPT_ERR_NEGATIVE_LOCKTIME, "NEGATIVE_LOCKTIME"},
      81             :     {SCRIPT_ERR_UNSATISFIED_LOCKTIME, "UNSATISFIED_LOCKTIME"},
      82             :     {SCRIPT_ERR_SIG_HASHTYPE, "SIG_HASHTYPE"},
      83             :     {SCRIPT_ERR_SIG_DER, "SIG_DER"},
      84             :     {SCRIPT_ERR_MINIMALDATA, "MINIMALDATA"},
      85             :     {SCRIPT_ERR_SIG_PUSHONLY, "SIG_PUSHONLY"},
      86             :     {SCRIPT_ERR_SIG_HIGH_S, "SIG_HIGH_S"},
      87             :     {SCRIPT_ERR_SIG_NULLDUMMY, "SIG_NULLDUMMY"},
      88             :     {SCRIPT_ERR_PUBKEYTYPE, "PUBKEYTYPE"},
      89             :     {SCRIPT_ERR_CLEANSTACK, "CLEANSTACK"},
      90             :     {SCRIPT_ERR_MINIMALIF, "MINIMALIF"},
      91             :     {SCRIPT_ERR_SIG_NULLFAIL, "NULLFAIL"},
      92             :     {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, "DISCOURAGE_UPGRADABLE_NOPS"},
      93             :     {SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM"},
      94             :     {SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH, "WITNESS_PROGRAM_WRONG_LENGTH"},
      95             :     {SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY, "WITNESS_PROGRAM_WITNESS_EMPTY"},
      96             :     {SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH, "WITNESS_PROGRAM_MISMATCH"},
      97             :     {SCRIPT_ERR_WITNESS_MALLEATED, "WITNESS_MALLEATED"},
      98             :     {SCRIPT_ERR_WITNESS_MALLEATED_P2SH, "WITNESS_MALLEATED_P2SH"},
      99             :     {SCRIPT_ERR_WITNESS_UNEXPECTED, "WITNESS_UNEXPECTED"},
     100             :     {SCRIPT_ERR_WITNESS_PUBKEYTYPE, "WITNESS_PUBKEYTYPE"},
     101             :     {SCRIPT_ERR_OP_CODESEPARATOR, "OP_CODESEPARATOR"},
     102             :     {SCRIPT_ERR_SIG_FINDANDDELETE, "SIG_FINDANDDELETE"},
     103             : };
     104             : 
     105        2808 : static std::string FormatScriptError(ScriptError_t err)
     106             : {
     107       22733 :     for (unsigned int i=0; i<ARRAYLEN(script_errors); ++i)
     108       22733 :         if (script_errors[i].err == err)
     109        2808 :             return script_errors[i].name;
     110           0 :     BOOST_ERROR("Unknown scripterror enumeration value, update script_errors in script_tests.cpp.");
     111           0 :     return "";
     112        2808 : }
     113             : 
     114        1203 : static ScriptError_t ParseScriptError(const std::string &name)
     115             : {
     116        8995 :     for (unsigned int i=0; i<ARRAYLEN(script_errors); ++i)
     117        8995 :         if (script_errors[i].name == name)
     118        1203 :             return script_errors[i].err;
     119           0 :     BOOST_ERROR("Unknown scripterror \"" << name << "\" in test description");
     120           0 :     return SCRIPT_ERR_UNKNOWN_ERROR;
     121        1203 : }
     122             : 
     123          89 : BOOST_FIXTURE_TEST_SUITE(script_tests, BasicTestingSetup)
     124             : 
     125        1337 : void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, const CScriptWitness& scriptWitness, int flags, const std::string& message, int scriptError, CAmount nValue = 0)
     126             : {
     127        1337 :     bool expect = (scriptError == SCRIPT_ERR_OK);
     128        1337 :     if (flags & SCRIPT_VERIFY_CLEANSTACK) {
     129           6 :         flags |= SCRIPT_VERIFY_P2SH;
     130           6 :         flags |= SCRIPT_VERIFY_WITNESS;
     131           6 :     }
     132        1337 :     ScriptError err;
     133        1337 :     const CTransaction txCredit{BuildCreditingTransaction(scriptPubKey, nValue)};
     134        1337 :     CMutableTransaction tx = BuildSpendingTransaction(scriptSig, scriptWitness, txCredit);
     135        1337 :     CMutableTransaction tx2 = tx;
     136        1337 :     BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue), &err) == expect, message);
     137        1337 :     BOOST_CHECK_MESSAGE(err == scriptError, FormatScriptError(err) + " where " + FormatScriptError((ScriptError_t)scriptError) + " expected: " + message);
     138             : 
     139             :     // Verify that removing flags from a passing test or adding flags to a failing test does not change the result.
     140       22729 :     for (int i = 0; i < 16; ++i) {
     141       21392 :         int extra_flags = InsecureRandBits(16);
     142       21392 :         int combined_flags = expect ? (flags & ~extra_flags) : (flags | extra_flags);
     143             :         // Weed out some invalid flag combinations.
     144       21392 :         if (combined_flags & SCRIPT_VERIFY_CLEANSTACK && ~combined_flags & (SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS)) continue;
     145       18991 :         if (combined_flags & SCRIPT_VERIFY_WITNESS && ~combined_flags & SCRIPT_VERIFY_P2SH) continue;
     146       18356 :         BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, &scriptWitness, combined_flags, MutableTransactionSignatureChecker(&tx, 0, txCredit.vout[0].nValue), &err) == expect, message + strprintf(" (with flags %x)", combined_flags));
     147       21392 :     }
     148             : 
     149             : #if defined(HAVE_CONSENSUS_LIB)
     150        1337 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
     151        1337 :     stream << tx2;
     152        1337 :     int libconsensus_flags = flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_ALL;
     153        1337 :     if (libconsensus_flags == flags) {
     154         325 :         int expectedSuccessCode = expect ? 1 : 0;
     155         325 :         if (flags & bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS) {
     156          80 :             BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), txCredit.vout[0].nValue, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
     157             :         } else {
     158         245 :             BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script_with_amount(scriptPubKey.data(), scriptPubKey.size(), 0, (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
     159         245 :             BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, libconsensus_flags, nullptr) == expectedSuccessCode, message);
     160             :         }
     161         325 :     }
     162             : #endif
     163        1337 : }
     164             : 
     165           2 : void static NegateSignatureS(std::vector<unsigned char>& vchSig) {
     166             :     // Parse the signature.
     167           2 :     std::vector<unsigned char> r, s;
     168           2 :     r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
     169           2 :     s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
     170             : 
     171             :     // Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1.
     172             :     static const unsigned char order[33] = {
     173             :         0x00,
     174             :         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
     175             :         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
     176             :         0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
     177             :         0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
     178             :     };
     179           4 :     while (s.size() < 33) {
     180           2 :         s.insert(s.begin(), 0x00);
     181             :     }
     182             :     int carry = 0;
     183          66 :     for (int p = 32; p >= 1; p--) {
     184          64 :         int n = (int)order[p] - s[p] - carry;
     185          64 :         s[p] = (n + 256) & 0xFF;
     186          64 :         carry = (n < 0);
     187             :     }
     188           2 :     assert(carry == 0);
     189           2 :     if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) {
     190           0 :         s.erase(s.begin());
     191           0 :     }
     192             : 
     193             :     // Reconstruct the signature.
     194           2 :     vchSig.clear();
     195           2 :     vchSig.push_back(0x30);
     196           2 :     vchSig.push_back(4 + r.size() + s.size());
     197           2 :     vchSig.push_back(0x02);
     198           2 :     vchSig.push_back(r.size());
     199           2 :     vchSig.insert(vchSig.end(), r.begin(), r.end());
     200           2 :     vchSig.push_back(0x02);
     201           2 :     vchSig.push_back(s.size());
     202           2 :     vchSig.insert(vchSig.end(), s.begin(), s.end());
     203           2 : }
     204             : 
     205             : namespace
     206             : {
     207             : const unsigned char vchKey0[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
     208             : const unsigned char vchKey1[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
     209             : const unsigned char vchKey2[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0};
     210             : 
     211           2 : struct KeyData
     212             : {
     213             :     CKey key0, key0C, key1, key1C, key2, key2C;
     214             :     CPubKey pubkey0, pubkey0C, pubkey0H;
     215             :     CPubKey pubkey1, pubkey1C;
     216             :     CPubKey pubkey2, pubkey2C;
     217             : 
     218           2 :     KeyData()
     219           1 :     {
     220           1 :         key0.Set(vchKey0, vchKey0 + 32, false);
     221           1 :         key0C.Set(vchKey0, vchKey0 + 32, true);
     222           1 :         pubkey0 = key0.GetPubKey();
     223           1 :         pubkey0H = key0.GetPubKey();
     224           1 :         pubkey0C = key0C.GetPubKey();
     225           1 :         *const_cast<unsigned char*>(&pubkey0H[0]) = 0x06 | (pubkey0H[64] & 1);
     226             : 
     227           1 :         key1.Set(vchKey1, vchKey1 + 32, false);
     228           1 :         key1C.Set(vchKey1, vchKey1 + 32, true);
     229           1 :         pubkey1 = key1.GetPubKey();
     230           1 :         pubkey1C = key1C.GetPubKey();
     231             : 
     232           1 :         key2.Set(vchKey2, vchKey2 + 32, false);
     233           1 :         key2C.Set(vchKey2, vchKey2 + 32, true);
     234           1 :         pubkey2 = key2.GetPubKey();
     235           1 :         pubkey2C = key2C.GetPubKey();
     236           2 :     }
     237             : };
     238             : 
     239             : enum class WitnessMode {
     240             :     NONE,
     241             :     PKH,
     242             :     SH
     243             : };
     244             : 
     245        2494 : class TestBuilder
     246             : {
     247             : private:
     248             :     //! Actually executed script
     249             :     CScript script;
     250             :     //! The P2SH redeemscript
     251             :     CScript redeemscript;
     252             :     //! The Witness embedded script
     253             :     CScript witscript;
     254             :     CScriptWitness scriptWitness;
     255             :     CTransactionRef creditTx;
     256             :     CMutableTransaction spendTx;
     257             :     bool havePush;
     258             :     std::vector<unsigned char> push;
     259             :     std::string comment;
     260             :     int flags;
     261             :     int scriptError;
     262             :     CAmount nValue;
     263             : 
     264         577 :     void DoPush()
     265             :     {
     266         577 :         if (havePush) {
     267         220 :             spendTx.vin[0].scriptSig << push;
     268         220 :             havePush = false;
     269         220 :         }
     270         577 :     }
     271             : 
     272         253 :     void DoPush(const std::vector<unsigned char>& data)
     273             :     {
     274         253 :         DoPush();
     275         253 :         push = data;
     276         253 :         havePush = true;
     277         253 :     }
     278             : 
     279             : public:
     280         268 :     TestBuilder(const CScript& script_, const std::string& comment_, int flags_, bool P2SH = false, WitnessMode wm = WitnessMode::NONE, int witnessversion = 0, CAmount nValue_ = 0) : script(script_), havePush(false), comment(comment_), flags(flags_), scriptError(SCRIPT_ERR_OK), nValue(nValue_)
     281         134 :     {
     282         134 :         CScript scriptPubKey = script;
     283         134 :         if (wm == WitnessMode::PKH) {
     284          16 :             uint160 hash;
     285          16 :             CHash160().Write(MakeSpan(script).subspan(1)).Finalize(hash);
     286          16 :             script = CScript() << OP_DUP << OP_HASH160 << ToByteVector(hash) << OP_EQUALVERIFY << OP_CHECKSIG;
     287          16 :             scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
     288         134 :         } else if (wm == WitnessMode::SH) {
     289          34 :             witscript = scriptPubKey;
     290          34 :             uint256 hash;
     291          34 :             CSHA256().Write(&witscript[0], witscript.size()).Finalize(hash.begin());
     292          34 :             scriptPubKey = CScript() << witnessversion << ToByteVector(hash);
     293          34 :         }
     294         134 :         if (P2SH) {
     295          36 :             redeemscript = scriptPubKey;
     296          36 :             scriptPubKey = CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemscript)) << OP_EQUAL;
     297          36 :         }
     298         134 :         creditTx = MakeTransactionRef(BuildCreditingTransaction(scriptPubKey, nValue));
     299         134 :         spendTx = BuildSpendingTransaction(CScript(), CScriptWitness(), *creditTx);
     300         268 :     }
     301             : 
     302          71 :     TestBuilder& ScriptError(ScriptError_t err)
     303             :     {
     304          71 :         scriptError = err;
     305          71 :         return *this;
     306             :     }
     307             : 
     308           6 :     TestBuilder& Opcode(const opcodetype& _op)
     309             :     {
     310           6 :         DoPush();
     311           6 :         spendTx.vin[0].scriptSig << _op;
     312           6 :         return *this;
     313             :     }
     314             : 
     315          50 :     TestBuilder& Num(int num)
     316             :     {
     317          50 :         DoPush();
     318          50 :         spendTx.vin[0].scriptSig << num;
     319          50 :         return *this;
     320             :     }
     321             : 
     322           2 :     TestBuilder& Push(const std::string& hex)
     323             :     {
     324           2 :         DoPush(ParseHex(hex));
     325           2 :         return *this;
     326           0 :     }
     327             : 
     328          21 :     TestBuilder& Push(const CScript& _script)
     329             :     {
     330          21 :         DoPush(std::vector<unsigned char>(_script.begin(), _script.end()));
     331          21 :         return *this;
     332           0 :     }
     333             : 
     334         142 :     TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::BASE, CAmount amount = 0)
     335             :     {
     336         142 :         uint256 hash = SignatureHash(script, spendTx, 0, nHashType, amount, sigversion);
     337         142 :         std::vector<unsigned char> vchSig, r, s;
     338             :         uint32_t iter = 0;
     339         142 :         do {
     340        1340 :             key.Sign(hash, vchSig, false, iter++);
     341        1340 :             if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) {
     342           2 :                 NegateSignatureS(vchSig);
     343             :             }
     344        1340 :             r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
     345        1340 :             s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
     346        1340 :         } while (lenR != r.size() || lenS != s.size());
     347         142 :         vchSig.push_back(static_cast<unsigned char>(nHashType));
     348         142 :         DoPush(vchSig);
     349             :         return *this;
     350         142 :     }
     351             : 
     352          50 :     TestBuilder& PushWitSig(const CKey& key, CAmount amount = -1, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32, SigVersion sigversion = SigVersion::WITNESS_V0)
     353             :     {
     354          50 :         if (amount == -1)
     355          46 :             amount = nValue;
     356          50 :         return PushSig(key, nHashType, lenR, lenS, sigversion, amount).AsWit();
     357             :     }
     358             : 
     359          20 :     TestBuilder& Push(const CPubKey& pubkey)
     360             :     {
     361          20 :         DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));
     362          20 :         return *this;
     363           0 :     }
     364             : 
     365          36 :     TestBuilder& PushRedeem()
     366             :     {
     367          36 :         DoPush(std::vector<unsigned char>(redeemscript.begin(), redeemscript.end()));
     368          36 :         return *this;
     369           0 :     }
     370             : 
     371          32 :     TestBuilder& PushWitRedeem()
     372             :     {
     373          32 :         DoPush(std::vector<unsigned char>(witscript.begin(), witscript.end()));
     374          32 :         return AsWit();
     375           0 :     }
     376             : 
     377          31 :     TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout)
     378             :     {
     379          31 :         assert(havePush);
     380          31 :         std::vector<unsigned char> datain = ParseHex(hexin);
     381          31 :         std::vector<unsigned char> dataout = ParseHex(hexout);
     382          31 :         assert(pos + datain.size() <= push.size());
     383          31 :         BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment);
     384          31 :         push.erase(push.begin() + pos, push.begin() + pos + datain.size());
     385          31 :         push.insert(push.begin() + pos, dataout.begin(), dataout.end());
     386             :         return *this;
     387          31 :     }
     388             : 
     389          14 :     TestBuilder& DamagePush(unsigned int pos)
     390             :     {
     391          14 :         assert(havePush);
     392          14 :         assert(pos < push.size());
     393          14 :         push[pos] ^= 1;
     394          14 :         return *this;
     395             :     }
     396             : 
     397         134 :     TestBuilder& Test()
     398             :     {
     399         134 :         TestBuilder copy = *this; // Make a copy so we can rollback the push.
     400         134 :         DoPush();
     401         134 :         DoTest(creditTx->vout[0].scriptPubKey, spendTx.vin[0].scriptSig, scriptWitness, flags, comment, scriptError, nValue);
     402         134 :         *this = copy;
     403             :         return *this;
     404         134 :     }
     405             : 
     406         122 :     TestBuilder& AsWit()
     407             :     {
     408         122 :         assert(havePush);
     409         122 :         scriptWitness.stack.push_back(push);
     410         122 :         havePush = false;
     411         122 :         return *this;
     412             :     }
     413             : 
     414         134 :     UniValue GetJSON()
     415             :     {
     416         134 :         DoPush();
     417         134 :         UniValue array(UniValue::VARR);
     418         134 :         if (!scriptWitness.stack.empty()) {
     419          51 :             UniValue wit(UniValue::VARR);
     420         173 :             for (unsigned i = 0; i < scriptWitness.stack.size(); i++) {
     421         122 :                 wit.push_back(HexStr(scriptWitness.stack[i]));
     422             :             }
     423          51 :             wit.push_back(ValueFromAmount(nValue));
     424          51 :             array.push_back(wit);
     425          51 :         }
     426         134 :         array.push_back(FormatScript(spendTx.vin[0].scriptSig));
     427         134 :         array.push_back(FormatScript(creditTx->vout[0].scriptPubKey));
     428         134 :         array.push_back(FormatScriptFlags(flags));
     429         134 :         array.push_back(FormatScriptError((ScriptError_t)scriptError));
     430         134 :         array.push_back(comment);
     431             :         return array;
     432         134 :     }
     433             : 
     434           0 :     std::string GetComment() const
     435             :     {
     436           0 :         return comment;
     437             :     }
     438             : };
     439             : 
     440        1388 : std::string JSONPrettyPrint(const UniValue& univalue)
     441             : {
     442        1388 :     std::string ret = univalue.write(4);
     443             :     // Workaround for libunivalue pretty printer, which puts a space between commas and newlines
     444             :     size_t pos = 0;
     445        1388 :     while ((pos = ret.find(" \n", pos)) != std::string::npos) {
     446           0 :         ret.replace(pos, 2, "\n");
     447           0 :         pos++;
     448             :     }
     449             :     return ret;
     450        1388 : }
     451             : } // namespace
     452             : 
     453          95 : BOOST_AUTO_TEST_CASE(script_build)
     454             : {
     455           1 :     const KeyData keys;
     456             : 
     457           1 :     std::vector<TestBuilder> tests;
     458             : 
     459           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     460           1 :                                 "P2PK", 0
     461           1 :                                ).PushSig(keys.key0));
     462           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     463           1 :                                 "P2PK, bad sig", 0
     464           1 :                                ).PushSig(keys.key0).DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     465             : 
     466           3 :     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
     467           1 :                                 "P2PKH", 0
     468           1 :                                ).PushSig(keys.key1).Push(keys.pubkey1C));
     469           3 :     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
     470           1 :                                 "P2PKH, bad pubkey", 0
     471           1 :                                ).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5).ScriptError(SCRIPT_ERR_EQUALVERIFY));
     472             : 
     473           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     474           1 :                                 "P2PK anyonecanpay", 0
     475           1 :                                ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));
     476           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     477           1 :                                 "P2PK anyonecanpay marked with normal hashtype", 0
     478           1 :                                ).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01").ScriptError(SCRIPT_ERR_EVAL_FALSE));
     479             : 
     480           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
     481           1 :                                 "P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true
     482           1 :                                ).PushSig(keys.key0).PushRedeem());
     483           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
     484           1 :                                 "P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true
     485           1 :                                ).PushSig(keys.key0).PushRedeem().DamagePush(10).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     486             : 
     487           3 :     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey0.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
     488           1 :                                 "P2SH(P2PKH)", SCRIPT_VERIFY_P2SH, true
     489           1 :                                ).PushSig(keys.key0).Push(keys.pubkey0).PushRedeem());
     490           3 :     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
     491           1 :                                 "P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true
     492           1 :                                ).PushSig(keys.key0).DamagePush(10).PushRedeem());
     493           3 :     tests.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
     494           1 :                                 "P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true
     495           1 :                                ).PushSig(keys.key0).DamagePush(10).PushRedeem().ScriptError(SCRIPT_ERR_EQUALVERIFY));
     496             : 
     497           3 :     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
     498           1 :                                 "3-of-3", 0
     499           1 :                                ).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
     500           3 :     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
     501           1 :                                 "3-of-3, 2 sigs", 0
     502           1 :                                ).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     503             : 
     504           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
     505           1 :                                 "P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true
     506           1 :                                ).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());
     507           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
     508           1 :                                 "P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true
     509           1 :                                ).Num(0).PushSig(keys.key1).Num(0).PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     510             : 
     511           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     512           1 :                                 "P2PK with too much R padding but no DERSIG", 0
     513           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
     514           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     515           1 :                                 "P2PK with too much R padding", SCRIPT_VERIFY_DERSIG
     516           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
     517           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     518           1 :                                 "P2PK with too much S padding but no DERSIG", 0
     519           1 :                                ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
     520           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     521           1 :                                 "P2PK with too much S padding", SCRIPT_VERIFY_DERSIG
     522           1 :                                ).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100").ScriptError(SCRIPT_ERR_SIG_DER));
     523           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     524           1 :                                 "P2PK with too little R padding but no DERSIG", 0
     525           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
     526           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     527           1 :                                 "P2PK with too little R padding", SCRIPT_VERIFY_DERSIG
     528           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
     529           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
     530           1 :                                 "P2PK NOT with bad sig with too much R padding but no DERSIG", 0
     531           1 :                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
     532           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
     533           1 :                                 "P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG
     534           1 :                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10).ScriptError(SCRIPT_ERR_SIG_DER));
     535           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
     536           1 :                                 "P2PK NOT with too much R padding but no DERSIG", 0
     537           1 :                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_EVAL_FALSE));
     538           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
     539           1 :                                 "P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG
     540           1 :                                ).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").ScriptError(SCRIPT_ERR_SIG_DER));
     541             : 
     542           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     543           1 :                                 "BIP66 example 1, without DERSIG", 0
     544           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
     545           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     546           1 :                                 "BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG
     547           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
     548           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
     549           1 :                                 "BIP66 example 2, without DERSIG", 0
     550           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
     551           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
     552           1 :                                 "BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG
     553           1 :                                ).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
     554           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     555           1 :                                 "BIP66 example 3, without DERSIG", 0
     556           1 :                                ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     557           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     558           1 :                                 "BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG
     559           1 :                                ).Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     560           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
     561           1 :                                 "BIP66 example 4, without DERSIG", 0
     562           1 :                                ).Num(0));
     563           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
     564           1 :                                 "BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG
     565           1 :                                ).Num(0));
     566           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     567           1 :                                 "BIP66 example 5, without DERSIG", 0
     568           1 :                                ).Num(1).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     569           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
     570           1 :                                 "BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG
     571           1 :                                ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
     572           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
     573           1 :                                 "BIP66 example 6, without DERSIG", 0
     574           1 :                                ).Num(1));
     575           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
     576           1 :                                 "BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG
     577           1 :                                ).Num(1).ScriptError(SCRIPT_ERR_SIG_DER));
     578           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
     579           1 :                                 "BIP66 example 7, without DERSIG", 0
     580           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
     581           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
     582           1 :                                 "BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG
     583           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
     584           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
     585           1 :                                 "BIP66 example 8, without DERSIG", 0
     586           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     587           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
     588           1 :                                 "BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG
     589           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_DER));
     590           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
     591           1 :                                 "BIP66 example 9, without DERSIG", 0
     592           1 :                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_EVAL_FALSE));
     593           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
     594           1 :                                 "BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG
     595           1 :                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
     596           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
     597           1 :                                 "BIP66 example 10, without DERSIG", 0
     598           1 :                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
     599           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
     600           1 :                                 "BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG
     601           1 :                                ).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").ScriptError(SCRIPT_ERR_SIG_DER));
     602           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
     603           1 :                                 "BIP66 example 11, without DERSIG", 0
     604           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     605           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
     606           1 :                                 "BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG
     607           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     608           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
     609           1 :                                 "BIP66 example 12, without DERSIG", 0
     610           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
     611           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
     612           1 :                                 "BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG
     613           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
     614           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     615           1 :                                 "P2PK with multi-byte hashtype, without DERSIG", 0
     616           1 :                                ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101"));
     617           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     618           1 :                                 "P2PK with multi-byte hashtype, with DERSIG", SCRIPT_VERIFY_DERSIG
     619           1 :                                ).PushSig(keys.key2, SIGHASH_ALL).EditPush(70, "01", "0101").ScriptError(SCRIPT_ERR_SIG_DER));
     620             : 
     621           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     622           1 :                                 "P2PK with high S but no LOW_S", 0
     623           1 :                                ).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
     624           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     625           1 :                                 "P2PK with high S", SCRIPT_VERIFY_LOW_S
     626           1 :                                ).PushSig(keys.key2, SIGHASH_ALL, 32, 33).ScriptError(SCRIPT_ERR_SIG_HIGH_S));
     627             : 
     628           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
     629           1 :                                 "P2PK with hybrid pubkey but no STRICTENC", 0
     630           1 :                                ).PushSig(keys.key0, SIGHASH_ALL));
     631           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
     632           1 :                                 "P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
     633           1 :                                ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
     634           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
     635           1 :                                 "P2PK NOT with hybrid pubkey but no STRICTENC", 0
     636           1 :                                ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_EVAL_FALSE));
     637           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
     638           1 :                                 "P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
     639           1 :                                ).PushSig(keys.key0, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
     640           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
     641           1 :                                 "P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0
     642           1 :                                ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
     643           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
     644           1 :                                 "P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC
     645           1 :                                ).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
     646           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
     647           1 :                                 "1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0
     648           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
     649           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
     650           1 :                                 "1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
     651           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL));
     652           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,
     653           1 :                                 "1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
     654           1 :                                ).Num(0).PushSig(keys.key1, SIGHASH_ALL).ScriptError(SCRIPT_ERR_PUBKEYTYPE));
     655             : 
     656           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     657           1 :                                 "P2PK with undefined hashtype but no STRICTENC", 0
     658           1 :                                ).PushSig(keys.key1, 5));
     659           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     660           1 :                                 "P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC
     661           1 :                                ).PushSig(keys.key1, 5).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
     662           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
     663           1 :                                 "P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0
     664           1 :                                ).PushSig(keys.key1, 5).DamagePush(10));
     665           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
     666           1 :                                 "P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC
     667           1 :                                ).PushSig(keys.key1, 5).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_HASHTYPE));
     668             : 
     669           3 :     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
     670           1 :                                 "3-of-3 with nonzero dummy but no NULLDUMMY", 0
     671           1 :                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
     672           3 :     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
     673           1 :                                 "3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
     674           1 :                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
     675           3 :     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
     676           1 :                                 "3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0
     677           1 :                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
     678           3 :     tests.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
     679           1 :                                 "3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
     680           1 :                                ).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10).ScriptError(SCRIPT_ERR_SIG_NULLDUMMY));
     681             : 
     682           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
     683           1 :                                 "2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0
     684           1 :                                ).Num(0).PushSig(keys.key1).Opcode(OP_DUP));
     685           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
     686           1 :                                 "2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY
     687           1 :                                ).Num(0).PushSig(keys.key1).Opcode(OP_DUP).ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
     688           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     689           1 :                                 "P2SH(P2PK) with non-push scriptSig but no P2SH or SIGPUSHONLY", 0, true
     690           1 :                                ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem());
     691           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     692           1 :                                 "P2PK with non-push scriptSig but with P2SH validation", 0
     693           1 :                                ).PushSig(keys.key2).Opcode(OP_NOP8));
     694           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     695           1 :                                 "P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", SCRIPT_VERIFY_P2SH, true
     696           1 :                                ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
     697           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
     698           1 :                                 "P2SH(P2PK) with non-push scriptSig but not P2SH", SCRIPT_VERIFY_SIGPUSHONLY, true
     699           1 :                                ).PushSig(keys.key2).Opcode(OP_NOP8).PushRedeem().ScriptError(SCRIPT_ERR_SIG_PUSHONLY));
     700           3 :     tests.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
     701           1 :                                 "2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
     702           1 :                                ).Num(0).PushSig(keys.key1).PushSig(keys.key1));
     703           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     704           1 :                                 "P2PK with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH
     705           1 :                                ).Num(11).PushSig(keys.key0));
     706           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     707           1 :                                 "P2PK with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH
     708           1 :                                ).Num(11).PushSig(keys.key0).ScriptError(SCRIPT_ERR_CLEANSTACK));
     709           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     710           1 :                                 "P2SH with unnecessary input but no CLEANSTACK", SCRIPT_VERIFY_P2SH, true
     711           1 :                                ).Num(11).PushSig(keys.key0).PushRedeem());
     712           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     713           1 :                                 "P2SH with unnecessary input", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
     714           1 :                                ).Num(11).PushSig(keys.key0).PushRedeem().ScriptError(SCRIPT_ERR_CLEANSTACK));
     715           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     716           1 :                                 "P2SH with CLEANSTACK", SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_P2SH, true
     717           1 :                                ).PushSig(keys.key0).PushRedeem());
     718             : 
     719           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     720           1 :                                 "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
     721           1 :                                 0, 1).PushWitSig(keys.key0).PushWitRedeem());
     722           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     723           1 :                                 "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
     724           1 :                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit());
     725           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     726           1 :                                 "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
     727           1 :                                 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
     728           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     729           1 :                                 "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
     730           1 :                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem());
     731           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     732           1 :                                 "Basic P2WSH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
     733           1 :                                ).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     734           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
     735           1 :                                 "Basic P2WPKH with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
     736           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     737           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     738           1 :                                 "Basic P2SH(P2WSH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
     739           1 :                                ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     740           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
     741           1 :                                 "Basic P2SH(P2WPKH) with the wrong key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
     742           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     743           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     744           1 :                                 "Basic P2WSH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
     745           1 :                                ).PushWitSig(keys.key0).PushWitRedeem());
     746           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
     747           1 :                                 "Basic P2WPKH with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
     748           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit());
     749           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
     750           1 :                                 "Basic P2SH(P2WSH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::SH
     751           1 :                                ).PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
     752           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
     753           1 :                                 "Basic P2SH(P2WPKH) with the wrong key but no WITNESS", SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
     754           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().PushRedeem());
     755           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     756           1 :                                 "Basic P2WSH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
     757           1 :                                 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     758           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     759           1 :                                 "Basic P2WPKH with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH,
     760           1 :                                 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     761           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     762           1 :                                 "Basic P2SH(P2WSH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
     763           1 :                                 0, 0).PushWitSig(keys.key0, 1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     764           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     765           1 :                                 "Basic P2SH(P2WPKH) with wrong value", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH,
     766           1 :                                 0, 0).PushWitSig(keys.key0, 1).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_EVAL_FALSE));
     767             : 
     768           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     769           1 :                                 "P2WPKH with future witness version", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH |
     770             :                                 SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM, false, WitnessMode::PKH, 1
     771           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM));
     772             :     {
     773           1 :         CScript witscript = CScript() << ToByteVector(keys.pubkey0);
     774           1 :         uint256 hash;
     775           1 :         CSHA256().Write(&witscript[0], witscript.size()).Finalize(hash.begin());
     776           1 :         std::vector<unsigned char> hashBytes = ToByteVector(hash);
     777           1 :         hashBytes.pop_back();
     778           3 :         tests.push_back(TestBuilder(CScript() << OP_0 << hashBytes,
     779           1 :                                     "P2WPKH with wrong witness program length", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false
     780           1 :                                    ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH));
     781           1 :     }
     782           2 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     783           1 :                                 "P2WSH with empty witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
     784           1 :                                ).ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY));
     785             :     {
     786           1 :         CScript witscript = CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG;
     787           2 :         tests.push_back(TestBuilder(witscript,
     788           1 :                                     "P2WSH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH
     789           1 :                                    ).PushWitSig(keys.key0).Push(witscript).DamagePush(0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
     790           1 :     }
     791           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     792           1 :                                 "P2WPKH with witness program mismatch", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
     793           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH));
     794           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     795           1 :                                 "P2WPKH with non-empty scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::PKH
     796           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().Num(11).ScriptError(SCRIPT_ERR_WITNESS_MALLEATED));
     797           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1),
     798           1 :                                 "P2SH(P2WPKH) with superfluous push in scriptSig", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::PKH
     799           1 :                                ).PushWitSig(keys.key0).Push(keys.pubkey1).AsWit().Num(11).PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_MALLEATED_P2SH));
     800           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     801           1 :                                 "P2PK with witness", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH
     802           1 :                                ).PushSig(keys.key0).Push("0").AsWit().ScriptError(SCRIPT_ERR_WITNESS_UNEXPECTED));
     803             : 
     804             :     // Compressed keys should pass SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
     805           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
     806           1 :                                 "Basic P2WSH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     807           1 :                                 0, 1).PushWitSig(keys.key0C).PushWitRedeem());
     808           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
     809           1 :                                 "Basic P2WPKH with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
     810           1 :                                 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit());
     811           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
     812           1 :                                 "Basic P2SH(P2WSH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     813           1 :                                 0, 1).PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
     814           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C),
     815           1 :                                 "Basic P2SH(P2WPKH) with compressed key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
     816           1 :                                 0, 1).PushWitSig(keys.key0C).Push(keys.pubkey0C).AsWit().PushRedeem());
     817             : 
     818             :     // Testing uncompressed key in witness with SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
     819           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     820           1 :                                 "Basic P2WSH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     821           1 :                                 0, 1).PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     822           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     823           1 :                                 "Basic P2WPKH", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::PKH,
     824           1 :                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     825           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
     826           1 :                                 "Basic P2SH(P2WSH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     827           1 :                                 0, 1).PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     828           3 :     tests.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0),
     829           1 :                                 "Basic P2SH(P2WPKH)", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::PKH,
     830           1 :                                 0, 1).PushWitSig(keys.key0).Push(keys.pubkey0).AsWit().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     831             : 
     832             :     // P2WSH 1-of-2 multisig with compressed keys
     833           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     834           1 :                                 "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     835           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
     836           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     837           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     838           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
     839           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     840           1 :                                 "P2WSH CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     841           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
     842           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     843           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with compressed keys", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     844           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
     845             : 
     846             :     // P2WSH 1-of-2 multisig with first key uncompressed
     847           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     848           1 :                                 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
     849           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem());
     850           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     851           1 :                                 "P2SH(P2WSH) CHECKMULTISIG first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
     852           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem());
     853           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     854           1 :                                 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     855           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     856           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     857           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     858           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     859           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     860           1 :                                 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
     861           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem());
     862           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     863           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
     864           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem());
     865           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     866           1 :                                 "P2WSH CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     867           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     868           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0) << OP_2 << OP_CHECKMULTISIG,
     869           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with first key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     870           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1C).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     871             :     // P2WSH 1-of-2 multisig with second key uncompressed
     872           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     873           1 :                                 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
     874           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
     875           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     876           1 :                                 "P2SH(P2WSH) CHECKMULTISIG second key uncompressed and signing with the first key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
     877           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
     878           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     879           1 :                                 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     880           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem());
     881           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     882           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the first key should pass as the uncompressed key is not used", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     883           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key0C).PushWitRedeem().PushRedeem());
     884           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     885           1 :                                 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, false, WitnessMode::SH,
     886           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem());
     887           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     888           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH, true, WitnessMode::SH,
     889           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem());
     890           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     891           1 :                                 "P2WSH CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, false, WitnessMode::SH,
     892           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     893           3 :     tests.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1) << ToByteVector(keys.pubkey0C) << OP_2 << OP_CHECKMULTISIG,
     894           1 :                                 "P2SH(P2WSH) CHECKMULTISIG with second key uncompressed and signing with the second key", SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS_PUBKEYTYPE, true, WitnessMode::SH,
     895           1 :                                 0, 1).Push(CScript()).AsWit().PushWitSig(keys.key1).PushWitRedeem().PushRedeem().ScriptError(SCRIPT_ERR_WITNESS_PUBKEYTYPE));
     896             : 
     897           1 :     std::set<std::string> tests_set;
     898             : 
     899             :     {
     900           1 :         UniValue json_tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests)));
     901             : 
     902        1255 :         for (unsigned int idx = 0; idx < json_tests.size(); idx++) {
     903        1254 :             const UniValue& tv = json_tests[idx];
     904        1254 :             tests_set.insert(JSONPrettyPrint(tv.get_array()));
     905             :         }
     906           1 :     }
     907             : 
     908             : #ifdef UPDATE_JSON_TESTS
     909             :     std::string strGen;
     910             : #endif
     911         135 :     for (TestBuilder& test : tests) {
     912         134 :         test.Test();
     913         134 :         std::string str = JSONPrettyPrint(test.GetJSON());
     914             : #ifdef UPDATE_JSON_TESTS
     915             :         strGen += str + ",\n";
     916             : #else
     917         134 :         if (tests_set.count(str) == 0) {
     918           0 :             BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment());
     919             :         }
     920             : #endif
     921         134 :     }
     922             : 
     923             : #ifdef UPDATE_JSON_TESTS
     924             :     FILE* file = fopen("script_tests.json.gen", "w");
     925             :     fputs(strGen.c_str(), file);
     926             :     fclose(file);
     927             : #endif
     928           1 : }
     929             : 
     930          95 : BOOST_AUTO_TEST_CASE(script_json_test)
     931             : {
     932             :     // Read tests from test/data/script_tests.json
     933             :     // Format is an array of arrays
     934             :     // Inner arrays are [ ["wit"..., nValue]?, "scriptSig", "scriptPubKey", "flags", "expected_scripterror" ]
     935             :     // ... where scriptSig and scriptPubKey are stringified
     936             :     // scripts.
     937             :     // If a witness is given, then the last value in the array should be the
     938             :     // amount (nValue) to use in the crediting tx
     939           1 :     UniValue tests = read_json(std::string(json_tests::script_tests, json_tests::script_tests + sizeof(json_tests::script_tests)));
     940             : 
     941        1255 :     for (unsigned int idx = 0; idx < tests.size(); idx++) {
     942        1254 :         UniValue test = tests[idx];
     943        1254 :         std::string strTest = test.write();
     944        1254 :         CScriptWitness witness;
     945             :         CAmount nValue = 0;
     946             :         unsigned int pos = 0;
     947        1254 :         if (test.size() > 0 && test[pos].isArray()) {
     948             :             unsigned int i=0;
     949         317 :             for (i = 0; i < test[pos].size()-1; i++) {
     950         214 :                 witness.stack.push_back(ParseHex(test[pos][i].get_str()));
     951             :             }
     952         103 :             nValue = AmountFromValue(test[pos][i]);
     953             :             pos++;
     954         103 :         }
     955        1254 :         if (test.size() < 4 + pos) // Allow size > 3; extra stuff ignored (useful for comments)
     956             :         {
     957          51 :             if (test.size() != 1) {
     958           0 :                 BOOST_ERROR("Bad test: " << strTest);
     959             :             }
     960          51 :             continue;
     961             :         }
     962        1203 :         std::string scriptSigString = test[pos++].get_str();
     963        1203 :         CScript scriptSig = ParseScript(scriptSigString);
     964        1203 :         std::string scriptPubKeyString = test[pos++].get_str();
     965        1203 :         CScript scriptPubKey = ParseScript(scriptPubKeyString);
     966        1203 :         unsigned int scriptflags = ParseScriptFlags(test[pos++].get_str());
     967        1203 :         int scriptError = ParseScriptError(test[pos++].get_str());
     968             : 
     969        1203 :         DoTest(scriptPubKey, scriptSig, witness, scriptflags, strTest, scriptError, nValue);
     970        1254 :     }
     971           1 : }
     972             : 
     973          95 : BOOST_AUTO_TEST_CASE(script_PushData)
     974             : {
     975             :     // Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
     976             :     // the stack as the 1-75 opcodes do.
     977             :     static const unsigned char direct[] = { 1, 0x5a };
     978             :     static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
     979             :     static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
     980             :     static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
     981             : 
     982           1 :     ScriptError err;
     983           1 :     std::vector<std::vector<unsigned char> > directStack;
     984           1 :     BOOST_CHECK(EvalScript(directStack, CScript(direct, direct + sizeof(direct)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
     985           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
     986             : 
     987           1 :     std::vector<std::vector<unsigned char> > pushdata1Stack;
     988           1 :     BOOST_CHECK(EvalScript(pushdata1Stack, CScript(pushdata1, pushdata1 + sizeof(pushdata1)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
     989           1 :     BOOST_CHECK(pushdata1Stack == directStack);
     990           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
     991             : 
     992           1 :     std::vector<std::vector<unsigned char> > pushdata2Stack;
     993           1 :     BOOST_CHECK(EvalScript(pushdata2Stack, CScript(pushdata2, pushdata2 + sizeof(pushdata2)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
     994           1 :     BOOST_CHECK(pushdata2Stack == directStack);
     995           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
     996             : 
     997           1 :     std::vector<std::vector<unsigned char> > pushdata4Stack;
     998           1 :     BOOST_CHECK(EvalScript(pushdata4Stack, CScript(pushdata4, pushdata4 + sizeof(pushdata4)), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
     999           1 :     BOOST_CHECK(pushdata4Stack == directStack);
    1000           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1001             : 
    1002           1 :     const std::vector<unsigned char> pushdata1_trunc{OP_PUSHDATA1, 1};
    1003           1 :     const std::vector<unsigned char> pushdata2_trunc{OP_PUSHDATA2, 1, 0};
    1004           1 :     const std::vector<unsigned char> pushdata4_trunc{OP_PUSHDATA4, 1, 0, 0, 0};
    1005             : 
    1006           1 :     std::vector<std::vector<unsigned char>> stack_ignore;
    1007           1 :     BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata1_trunc.begin(), pushdata1_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
    1008           1 :     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
    1009           1 :     BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata2_trunc.begin(), pushdata2_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
    1010           1 :     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
    1011           1 :     BOOST_CHECK(!EvalScript(stack_ignore, CScript(pushdata4_trunc.begin(), pushdata4_trunc.end()), SCRIPT_VERIFY_P2SH, BaseSignatureChecker(), SigVersion::BASE, &err));
    1012           1 :     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_BAD_OPCODE);
    1013           1 : }
    1014             : 
    1015          95 : BOOST_AUTO_TEST_CASE(script_cltv_truncated)
    1016             : {
    1017           1 :     const auto script_cltv_trunc = CScript() << OP_CHECKLOCKTIMEVERIFY;
    1018             : 
    1019           1 :     std::vector<std::vector<unsigned char>> stack_ignore;
    1020           1 :     ScriptError err;
    1021           1 :     BOOST_CHECK(!EvalScript(stack_ignore, script_cltv_trunc, SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, BaseSignatureChecker(), SigVersion::BASE, &err));
    1022           1 :     BOOST_CHECK_EQUAL(err, SCRIPT_ERR_INVALID_STACK_OPERATION);
    1023           1 : }
    1024             : 
    1025             : static CScript
    1026          12 : sign_multisig(const CScript& scriptPubKey, const std::vector<CKey>& keys, const CTransaction& transaction)
    1027             : {
    1028          12 :     uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL, 0, SigVersion::BASE);
    1029             : 
    1030          12 :     CScript result;
    1031             :     //
    1032             :     // NOTE: CHECKMULTISIG has an unfortunate bug; it requires
    1033             :     // one extra item on the stack, before the signatures.
    1034             :     // Putting OP_0 on the stack is the workaround;
    1035             :     // fixing the bug would mean splitting the block chain (old
    1036             :     // clients would not accept new CHECKMULTISIG transactions,
    1037             :     // and vice-versa)
    1038             :     //
    1039          12 :     result << OP_0;
    1040          31 :     for (const CKey &key : keys)
    1041             :     {
    1042          19 :         std::vector<unsigned char> vchSig;
    1043          19 :         BOOST_CHECK(key.Sign(hash, vchSig));
    1044          19 :         vchSig.push_back((unsigned char)SIGHASH_ALL);
    1045          19 :         result << vchSig;
    1046          19 :     }
    1047             :     return result;
    1048          12 : }
    1049             : static CScript
    1050           3 : sign_multisig(const CScript& scriptPubKey, const CKey& key, const CTransaction& transaction)
    1051             : {
    1052           3 :     std::vector<CKey> keys;
    1053           3 :     keys.push_back(key);
    1054           3 :     return sign_multisig(scriptPubKey, keys, transaction);
    1055           3 : }
    1056             : 
    1057          95 : BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
    1058             : {
    1059           1 :     ScriptError err;
    1060           1 :     CKey key1, key2, key3;
    1061           1 :     key1.MakeNewKey(true);
    1062           1 :     key2.MakeNewKey(false);
    1063           1 :     key3.MakeNewKey(true);
    1064             : 
    1065           1 :     CScript scriptPubKey12;
    1066           1 :     scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
    1067             : 
    1068           1 :     const CTransaction txFrom12{BuildCreditingTransaction(scriptPubKey12)};
    1069           1 :     CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom12);
    1070             : 
    1071           1 :     CScript goodsig1 = sign_multisig(scriptPubKey12, key1, CTransaction(txTo12));
    1072           1 :     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
    1073           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1074           1 :     txTo12.vout[0].nValue = 2;
    1075           1 :     BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
    1076           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1077             : 
    1078           1 :     CScript goodsig2 = sign_multisig(scriptPubKey12, key2, CTransaction(txTo12));
    1079           1 :     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
    1080           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1081             : 
    1082           1 :     CScript badsig1 = sign_multisig(scriptPubKey12, key3, CTransaction(txTo12));
    1083           1 :     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo12, 0, txFrom12.vout[0].nValue), &err));
    1084           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1085           1 : }
    1086             : 
    1087          95 : BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
    1088             : {
    1089           1 :     ScriptError err;
    1090           1 :     CKey key1, key2, key3, key4;
    1091           1 :     key1.MakeNewKey(true);
    1092           1 :     key2.MakeNewKey(false);
    1093           1 :     key3.MakeNewKey(true);
    1094           1 :     key4.MakeNewKey(false);
    1095             : 
    1096           1 :     CScript scriptPubKey23;
    1097           1 :     scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
    1098             : 
    1099           1 :     const CTransaction txFrom23{BuildCreditingTransaction(scriptPubKey23)};
    1100           1 :     CMutableTransaction txTo23 = BuildSpendingTransaction(CScript(), CScriptWitness(), txFrom23);
    1101             : 
    1102           1 :     std::vector<CKey> keys;
    1103           1 :     keys.push_back(key1); keys.push_back(key2);
    1104           1 :     CScript goodsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1105           1 :     BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1106           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1107             : 
    1108           1 :     keys.clear();
    1109           1 :     keys.push_back(key1); keys.push_back(key3);
    1110           1 :     CScript goodsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1111           1 :     BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1112           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1113             : 
    1114           1 :     keys.clear();
    1115           1 :     keys.push_back(key2); keys.push_back(key3);
    1116           1 :     CScript goodsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1117           1 :     BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1118           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1119             : 
    1120           1 :     keys.clear();
    1121           1 :     keys.push_back(key2); keys.push_back(key2); // Can't re-use sig
    1122           1 :     CScript badsig1 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1123           1 :     BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1124           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1125             : 
    1126           1 :     keys.clear();
    1127           1 :     keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
    1128           1 :     CScript badsig2 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1129           1 :     BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1130           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1131             : 
    1132           1 :     keys.clear();
    1133           1 :     keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
    1134           1 :     CScript badsig3 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1135           1 :     BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1136           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1137             : 
    1138           1 :     keys.clear();
    1139           1 :     keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
    1140           1 :     CScript badsig4 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1141           1 :     BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1142           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1143             : 
    1144           1 :     keys.clear();
    1145           1 :     keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
    1146           1 :     CScript badsig5 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1147           1 :     BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1148           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
    1149             : 
    1150           1 :     keys.clear(); // Must have signatures
    1151           1 :     CScript badsig6 = sign_multisig(scriptPubKey23, keys, CTransaction(txTo23));
    1152           1 :     BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, nullptr, gFlags, MutableTransactionSignatureChecker(&txTo23, 0, txFrom23.vout[0].nValue), &err));
    1153           1 :     BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
    1154           1 : }
    1155             : 
    1156             : /* Wrapper around ProduceSignature to combine two scriptsigs */
    1157          17 : SignatureData CombineSignatures(const CTxOut& txout, const CMutableTransaction& tx, const SignatureData& scriptSig1, const SignatureData& scriptSig2)
    1158             : {
    1159          17 :     SignatureData data;
    1160          17 :     data.MergeSignatureData(scriptSig1);
    1161          17 :     data.MergeSignatureData(scriptSig2);
    1162          17 :     ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(&tx, 0, txout.nValue), txout.scriptPubKey, data);
    1163             :     return data;
    1164          17 : }
    1165             : 
    1166          95 : BOOST_AUTO_TEST_CASE(script_combineSigs)
    1167             : {
    1168             :     // Test the ProduceSignature's ability to combine signatures function
    1169           1 :     FillableSigningProvider keystore;
    1170           1 :     std::vector<CKey> keys;
    1171           1 :     std::vector<CPubKey> pubkeys;
    1172           4 :     for (int i = 0; i < 3; i++)
    1173             :     {
    1174           3 :         CKey key;
    1175           3 :         key.MakeNewKey(i%2 == 1);
    1176           3 :         keys.push_back(key);
    1177           3 :         pubkeys.push_back(key.GetPubKey());
    1178           3 :         BOOST_CHECK(keystore.AddKey(key));
    1179           3 :     }
    1180             : 
    1181           1 :     CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(PKHash(keys[0].GetPubKey())));
    1182           1 :     CMutableTransaction txTo = BuildSpendingTransaction(CScript(), CScriptWitness(), CTransaction(txFrom));
    1183           1 :     CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
    1184           1 :     SignatureData scriptSig;
    1185             : 
    1186           1 :     SignatureData empty;
    1187           1 :     SignatureData combined = CombineSignatures(txFrom.vout[0], txTo, empty, empty);
    1188           1 :     BOOST_CHECK(combined.scriptSig.empty());
    1189             : 
    1190             :     // Single signature case:
    1191           1 :     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL)); // changes scriptSig
    1192           1 :     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
    1193           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
    1194           1 :     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
    1195           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
    1196           1 :     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
    1197           1 :     SignatureData scriptSigCopy = scriptSig;
    1198             :     // Signing again will give a different, valid signature:
    1199           1 :     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
    1200           1 :     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
    1201           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
    1202           1 :     BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
    1203             : 
    1204             :     // P2SH, single-signature case:
    1205           1 :     CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;
    1206           1 :     BOOST_CHECK(keystore.AddCScript(pkSingle));
    1207           1 :     scriptPubKey = GetScriptForDestination(ScriptHash(pkSingle));
    1208           1 :     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
    1209           1 :     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
    1210           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
    1211           1 :     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
    1212           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
    1213           1 :     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
    1214           1 :     scriptSigCopy = scriptSig;
    1215           1 :     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
    1216           1 :     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
    1217           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSigCopy, scriptSig);
    1218           1 :     BOOST_CHECK(combined.scriptSig == scriptSigCopy.scriptSig || combined.scriptSig == scriptSig.scriptSig);
    1219             : 
    1220             :     // Hardest case:  Multisig 2-of-3
    1221           1 :     scriptPubKey = GetScriptForMultisig(2, pubkeys);
    1222           1 :     BOOST_CHECK(keystore.AddCScript(scriptPubKey));
    1223           1 :     BOOST_CHECK(SignSignature(keystore, CTransaction(txFrom), txTo, 0, SIGHASH_ALL));
    1224           1 :     scriptSig = DataFromTransaction(txTo, 0, txFrom.vout[0]);
    1225           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, scriptSig, empty);
    1226           1 :     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
    1227           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, empty, scriptSig);
    1228           1 :     BOOST_CHECK(combined.scriptSig == scriptSig.scriptSig);
    1229             : 
    1230             :     // A couple of partially-signed versions:
    1231           1 :     std::vector<unsigned char> sig1;
    1232           1 :     uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL, 0, SigVersion::BASE);
    1233           1 :     BOOST_CHECK(keys[0].Sign(hash1, sig1));
    1234           1 :     sig1.push_back(SIGHASH_ALL);
    1235           1 :     std::vector<unsigned char> sig2;
    1236           1 :     uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE, 0, SigVersion::BASE);
    1237           1 :     BOOST_CHECK(keys[1].Sign(hash2, sig2));
    1238           1 :     sig2.push_back(SIGHASH_NONE);
    1239           1 :     std::vector<unsigned char> sig3;
    1240           1 :     uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE, 0, SigVersion::BASE);
    1241           1 :     BOOST_CHECK(keys[2].Sign(hash3, sig3));
    1242           1 :     sig3.push_back(SIGHASH_SINGLE);
    1243             : 
    1244             :     // Not fussy about order (or even existence) of placeholders or signatures:
    1245           1 :     CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
    1246           1 :     CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
    1247           1 :     CScript partial2a = CScript() << OP_0 << sig2;
    1248           1 :     CScript partial2b = CScript() << sig2 << OP_0;
    1249           1 :     CScript partial3a = CScript() << sig3;
    1250           1 :     CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
    1251           1 :     CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
    1252           1 :     CScript complete12 = CScript() << OP_0 << sig1 << sig2;
    1253           1 :     CScript complete13 = CScript() << OP_0 << sig1 << sig3;
    1254           1 :     CScript complete23 = CScript() << OP_0 << sig2 << sig3;
    1255           1 :     SignatureData partial1_sigs;
    1256           1 :     partial1_sigs.signatures.emplace(keys[0].GetPubKey().GetID(), SigPair(keys[0].GetPubKey(), sig1));
    1257           1 :     SignatureData partial2_sigs;
    1258           1 :     partial2_sigs.signatures.emplace(keys[1].GetPubKey().GetID(), SigPair(keys[1].GetPubKey(), sig2));
    1259           1 :     SignatureData partial3_sigs;
    1260           1 :     partial3_sigs.signatures.emplace(keys[2].GetPubKey().GetID(), SigPair(keys[2].GetPubKey(), sig3));
    1261             : 
    1262           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial1_sigs);
    1263           1 :     BOOST_CHECK(combined.scriptSig == partial1a);
    1264           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
    1265           1 :     BOOST_CHECK(combined.scriptSig == complete12);
    1266           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial1_sigs);
    1267           1 :     BOOST_CHECK(combined.scriptSig == complete12);
    1268           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial1_sigs, partial2_sigs);
    1269           1 :     BOOST_CHECK(combined.scriptSig == complete12);
    1270           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial1_sigs);
    1271           1 :     BOOST_CHECK(combined.scriptSig == complete13);
    1272           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial2_sigs, partial3_sigs);
    1273           1 :     BOOST_CHECK(combined.scriptSig == complete23);
    1274           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial2_sigs);
    1275           1 :     BOOST_CHECK(combined.scriptSig == complete23);
    1276           1 :     combined = CombineSignatures(txFrom.vout[0], txTo, partial3_sigs, partial3_sigs);
    1277           1 :     BOOST_CHECK(combined.scriptSig == partial3c);
    1278           1 : }
    1279             : 
    1280          95 : BOOST_AUTO_TEST_CASE(script_standard_push)
    1281             : {
    1282           1 :     ScriptError err;
    1283       67001 :     for (int i=0; i<67000; i++) {
    1284       67000 :         CScript script;
    1285       67000 :         script << i;
    1286       67000 :         BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
    1287       67000 :         BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
    1288       67000 :         BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1289       67000 :     }
    1290             : 
    1291         522 :     for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {
    1292         521 :         std::vector<unsigned char> data(i, '\111');
    1293         521 :         CScript script;
    1294         521 :         script << data;
    1295         521 :         BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
    1296         521 :         BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, nullptr, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
    1297         521 :         BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
    1298         521 :     }
    1299           1 : }
    1300             : 
    1301          95 : BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)
    1302             : {
    1303             :     // IsPushOnly returns false when given a script containing only pushes that
    1304             :     // are invalid due to truncation. IsPushOnly() is consensus critical
    1305             :     // because P2SH evaluation uses it, although this specific behavior should
    1306             :     // not be consensus critical as the P2SH evaluation would fail first due to
    1307             :     // the invalid push. Still, it doesn't hurt to test it explicitly.
    1308             :     static const unsigned char direct[] = { 1 };
    1309           1 :     BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());
    1310           1 : }
    1311             : 
    1312          95 : BOOST_AUTO_TEST_CASE(script_GetScriptAsm)
    1313             : {
    1314           1 :     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2, true));
    1315           1 :     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY, true));
    1316           1 :     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_NOP2));
    1317           1 :     BOOST_CHECK_EQUAL("OP_CHECKLOCKTIMEVERIFY", ScriptToAsmStr(CScript() << OP_CHECKLOCKTIMEVERIFY));
    1318             : 
    1319           1 :     std::string derSig("304502207fa7a6d1e0ee81132a269ad84e68d695483745cde8b541e3bf630749894e342a022100c1f7ab20e13e22fb95281a870f3dcf38d782e53023ee313d741ad0cfbc0c5090");
    1320           1 :     std::string pubKey("03b0da749730dc9b4b1f4a14d6902877a92541f5368778853d9c4a0cb7802dcfb2");
    1321           1 :     std::vector<unsigned char> vchPubKey = ToByteVector(ParseHex(pubKey));
    1322             : 
    1323           1 :     BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey, true));
    1324           1 :     BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey, true));
    1325           1 :     BOOST_CHECK_EQUAL(derSig + "[ALL] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey, true));
    1326           1 :     BOOST_CHECK_EQUAL(derSig + "[NONE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey, true));
    1327           1 :     BOOST_CHECK_EQUAL(derSig + "[SINGLE] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey, true));
    1328           1 :     BOOST_CHECK_EQUAL(derSig + "[ALL|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey, true));
    1329           1 :     BOOST_CHECK_EQUAL(derSig + "[NONE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey, true));
    1330           1 :     BOOST_CHECK_EQUAL(derSig + "[SINGLE|ANYONECANPAY] " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey, true));
    1331             : 
    1332           1 :     BOOST_CHECK_EQUAL(derSig + "00 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "00")) << vchPubKey));
    1333           1 :     BOOST_CHECK_EQUAL(derSig + "80 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "80")) << vchPubKey));
    1334           1 :     BOOST_CHECK_EQUAL(derSig + "01 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "01")) << vchPubKey));
    1335           1 :     BOOST_CHECK_EQUAL(derSig + "02 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "02")) << vchPubKey));
    1336           1 :     BOOST_CHECK_EQUAL(derSig + "03 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "03")) << vchPubKey));
    1337           1 :     BOOST_CHECK_EQUAL(derSig + "81 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "81")) << vchPubKey));
    1338           1 :     BOOST_CHECK_EQUAL(derSig + "82 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "82")) << vchPubKey));
    1339           1 :     BOOST_CHECK_EQUAL(derSig + "83 " + pubKey, ScriptToAsmStr(CScript() << ToByteVector(ParseHex(derSig + "83")) << vchPubKey));
    1340           1 : }
    1341             : 
    1342             : static CScript
    1343          30 : ScriptFromHex(const char* hex)
    1344             : {
    1345          30 :     std::vector<unsigned char> data = ParseHex(hex);
    1346          30 :     return CScript(data.begin(), data.end());
    1347          30 : }
    1348             : 
    1349             : 
    1350          95 : BOOST_AUTO_TEST_CASE(script_FindAndDelete)
    1351             : {
    1352             :     // Exercise the FindAndDelete functionality
    1353           1 :     CScript s;
    1354           1 :     CScript d;
    1355           1 :     CScript expect;
    1356             : 
    1357           1 :     s = CScript() << OP_1 << OP_2;
    1358           1 :     d = CScript(); // delete nothing should be a no-op
    1359           1 :     expect = s;
    1360           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
    1361           1 :     BOOST_CHECK(s == expect);
    1362             : 
    1363           1 :     s = CScript() << OP_1 << OP_2 << OP_3;
    1364           1 :     d = CScript() << OP_2;
    1365           1 :     expect = CScript() << OP_1 << OP_3;
    1366           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1367           1 :     BOOST_CHECK(s == expect);
    1368             : 
    1369           1 :     s = CScript() << OP_3 << OP_1 << OP_3 << OP_3 << OP_4 << OP_3;
    1370           1 :     d = CScript() << OP_3;
    1371           1 :     expect = CScript() << OP_1 << OP_4;
    1372           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 4);
    1373           1 :     BOOST_CHECK(s == expect);
    1374             : 
    1375           1 :     s = ScriptFromHex("0302ff03"); // PUSH 0x02ff03 onto stack
    1376           1 :     d = ScriptFromHex("0302ff03");
    1377           1 :     expect = CScript();
    1378           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1379           1 :     BOOST_CHECK(s == expect);
    1380             : 
    1381           1 :     s = ScriptFromHex("0302ff030302ff03"); // PUSH 0x2ff03 PUSH 0x2ff03
    1382           1 :     d = ScriptFromHex("0302ff03");
    1383           1 :     expect = CScript();
    1384           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
    1385           1 :     BOOST_CHECK(s == expect);
    1386             : 
    1387           1 :     s = ScriptFromHex("0302ff030302ff03");
    1388           1 :     d = ScriptFromHex("02");
    1389           1 :     expect = s; // FindAndDelete matches entire opcodes
    1390           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
    1391           1 :     BOOST_CHECK(s == expect);
    1392             : 
    1393           1 :     s = ScriptFromHex("0302ff030302ff03");
    1394           1 :     d = ScriptFromHex("ff");
    1395           1 :     expect = s;
    1396           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
    1397           1 :     BOOST_CHECK(s == expect);
    1398             : 
    1399             :     // This is an odd edge case: strip of the push-three-bytes
    1400             :     // prefix, leaving 02ff03 which is push-two-bytes:
    1401           1 :     s = ScriptFromHex("0302ff030302ff03");
    1402           1 :     d = ScriptFromHex("03");
    1403           1 :     expect = CScript() << ParseHex("ff03") << ParseHex("ff03");
    1404           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
    1405           1 :     BOOST_CHECK(s == expect);
    1406             : 
    1407             :     // Byte sequence that spans multiple opcodes:
    1408           1 :     s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY
    1409           1 :     d = ScriptFromHex("feed51");
    1410           1 :     expect = s;
    1411           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0); // doesn't match 'inside' opcodes
    1412           1 :     BOOST_CHECK(s == expect);
    1413             : 
    1414           1 :     s = ScriptFromHex("02feed5169"); // PUSH(0xfeed) OP_1 OP_VERIFY
    1415           1 :     d = ScriptFromHex("02feed51");
    1416           1 :     expect = ScriptFromHex("69");
    1417           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1418           1 :     BOOST_CHECK(s == expect);
    1419             : 
    1420           1 :     s = ScriptFromHex("516902feed5169");
    1421           1 :     d = ScriptFromHex("feed51");
    1422           1 :     expect = s;
    1423           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 0);
    1424           1 :     BOOST_CHECK(s == expect);
    1425             : 
    1426           1 :     s = ScriptFromHex("516902feed5169");
    1427           1 :     d = ScriptFromHex("02feed51");
    1428           1 :     expect = ScriptFromHex("516969");
    1429           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1430           1 :     BOOST_CHECK(s == expect);
    1431             : 
    1432           1 :     s = CScript() << OP_0 << OP_0 << OP_1 << OP_1;
    1433           1 :     d = CScript() << OP_0 << OP_1;
    1434           1 :     expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
    1435           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1436           1 :     BOOST_CHECK(s == expect);
    1437             : 
    1438           1 :     s = CScript() << OP_0 << OP_0 << OP_1 << OP_0 << OP_1 << OP_1;
    1439           1 :     d = CScript() << OP_0 << OP_1;
    1440           1 :     expect = CScript() << OP_0 << OP_1; // FindAndDelete is single-pass
    1441           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 2);
    1442           1 :     BOOST_CHECK(s == expect);
    1443             : 
    1444             :     // Another weird edge case:
    1445             :     // End with invalid push (not enough data)...
    1446           1 :     s = ScriptFromHex("0003feed");
    1447           1 :     d = ScriptFromHex("03feed"); // ... can remove the invalid push
    1448           1 :     expect = ScriptFromHex("00");
    1449           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1450           1 :     BOOST_CHECK(s == expect);
    1451             : 
    1452           1 :     s = ScriptFromHex("0003feed");
    1453           1 :     d = ScriptFromHex("00");
    1454           1 :     expect = ScriptFromHex("03feed");
    1455           1 :     BOOST_CHECK_EQUAL(FindAndDelete(s, d), 1);
    1456           1 :     BOOST_CHECK(s == expect);
    1457           1 : }
    1458             : 
    1459          95 : BOOST_AUTO_TEST_CASE(script_HasValidOps)
    1460             : {
    1461             :     // Exercise the HasValidOps functionality
    1462           1 :     CScript script;
    1463           1 :     script = ScriptFromHex("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"); // Normal script
    1464           1 :     BOOST_CHECK(script.HasValidOps());
    1465           1 :     script = ScriptFromHex("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac");
    1466           1 :     BOOST_CHECK(script.HasValidOps());
    1467           1 :     script = ScriptFromHex("ff88ac"); // Script with OP_INVALIDOPCODE explicit
    1468           1 :     BOOST_CHECK(!script.HasValidOps());
    1469           1 :     script = ScriptFromHex("88acc0"); // Script with undefined opcode
    1470           1 :     BOOST_CHECK(!script.HasValidOps());
    1471           1 : }
    1472             : 
    1473             : #if defined(HAVE_CONSENSUS_LIB)
    1474             : 
    1475             : /* Test simple (successful) usage of bitcoinconsensus_verify_script */
    1476          95 : BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_returns_true)
    1477             : {
    1478             :     unsigned int libconsensus_flags = 0;
    1479             :     int nIn = 0;
    1480             : 
    1481           1 :     CScript scriptPubKey;
    1482           1 :     CScript scriptSig;
    1483           1 :     CScriptWitness wit;
    1484             : 
    1485           1 :     scriptPubKey << OP_1;
    1486           1 :     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
    1487           1 :     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
    1488             : 
    1489           1 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    1490           1 :     stream << spendTx;
    1491             : 
    1492           1 :     bitcoinconsensus_error err;
    1493           1 :     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err);
    1494           1 :     BOOST_CHECK_EQUAL(result, 1);
    1495           1 :     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_OK);
    1496           1 : }
    1497             : 
    1498             : /* Test bitcoinconsensus_verify_script returns invalid tx index err*/
    1499          95 : BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_index_err)
    1500             : {
    1501             :     unsigned int libconsensus_flags = 0;
    1502             :     int nIn = 3;
    1503             : 
    1504           1 :     CScript scriptPubKey;
    1505           1 :     CScript scriptSig;
    1506           1 :     CScriptWitness wit;
    1507             : 
    1508           1 :     scriptPubKey << OP_EQUAL;
    1509           1 :     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
    1510           1 :     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
    1511             : 
    1512           1 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    1513           1 :     stream << spendTx;
    1514             : 
    1515           1 :     bitcoinconsensus_error err;
    1516           1 :     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err);
    1517           1 :     BOOST_CHECK_EQUAL(result, 0);
    1518           1 :     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_INDEX);
    1519           1 : }
    1520             : 
    1521             : /* Test bitcoinconsensus_verify_script returns tx size mismatch err*/
    1522          95 : BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_size)
    1523             : {
    1524             :     unsigned int libconsensus_flags = 0;
    1525             :     int nIn = 0;
    1526             : 
    1527           1 :     CScript scriptPubKey;
    1528           1 :     CScript scriptSig;
    1529           1 :     CScriptWitness wit;
    1530             : 
    1531           1 :     scriptPubKey << OP_EQUAL;
    1532           1 :     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
    1533           1 :     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
    1534             : 
    1535           1 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    1536           1 :     stream << spendTx;
    1537             : 
    1538           1 :     bitcoinconsensus_error err;
    1539           1 :     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size() * 2, nIn, libconsensus_flags, &err);
    1540           1 :     BOOST_CHECK_EQUAL(result, 0);
    1541           1 :     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_SIZE_MISMATCH);
    1542           1 : }
    1543             : 
    1544             : /* Test bitcoinconsensus_verify_script returns invalid tx serialization error */
    1545          95 : BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_tx_serialization)
    1546             : {
    1547             :     unsigned int libconsensus_flags = 0;
    1548             :     int nIn = 0;
    1549             : 
    1550           1 :     CScript scriptPubKey;
    1551           1 :     CScript scriptSig;
    1552           1 :     CScriptWitness wit;
    1553             : 
    1554           1 :     scriptPubKey << OP_EQUAL;
    1555           1 :     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
    1556           1 :     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
    1557             : 
    1558           1 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    1559           1 :     stream << 0xffffffff;
    1560             : 
    1561           1 :     bitcoinconsensus_error err;
    1562           1 :     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err);
    1563           1 :     BOOST_CHECK_EQUAL(result, 0);
    1564           1 :     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_TX_DESERIALIZE);
    1565           1 : }
    1566             : 
    1567             : /* Test bitcoinconsensus_verify_script returns amount required error */
    1568          95 : BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_amount_required_err)
    1569             : {
    1570             :     unsigned int libconsensus_flags = bitcoinconsensus_SCRIPT_FLAGS_VERIFY_WITNESS;
    1571             :     int nIn = 0;
    1572             : 
    1573           1 :     CScript scriptPubKey;
    1574           1 :     CScript scriptSig;
    1575           1 :     CScriptWitness wit;
    1576             : 
    1577           1 :     scriptPubKey << OP_EQUAL;
    1578           1 :     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
    1579           1 :     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
    1580             : 
    1581           1 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    1582           1 :     stream << spendTx;
    1583             : 
    1584           1 :     bitcoinconsensus_error err;
    1585           1 :     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err);
    1586           1 :     BOOST_CHECK_EQUAL(result, 0);
    1587           1 :     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_AMOUNT_REQUIRED);
    1588           1 : }
    1589             : 
    1590             : /* Test bitcoinconsensus_verify_script returns invalid flags err */
    1591          95 : BOOST_AUTO_TEST_CASE(bitcoinconsensus_verify_script_invalid_flags)
    1592             : {
    1593             :     unsigned int libconsensus_flags = 1 << 3;
    1594             :     int nIn = 0;
    1595             : 
    1596           1 :     CScript scriptPubKey;
    1597           1 :     CScript scriptSig;
    1598           1 :     CScriptWitness wit;
    1599             : 
    1600           1 :     scriptPubKey << OP_EQUAL;
    1601           1 :     CTransaction creditTx = BuildCreditingTransaction(scriptPubKey, 1);
    1602           1 :     CTransaction spendTx = BuildSpendingTransaction(scriptSig, wit, creditTx);
    1603             : 
    1604           1 :     CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
    1605           1 :     stream << spendTx;
    1606             : 
    1607           1 :     bitcoinconsensus_error err;
    1608           1 :     int result = bitcoinconsensus_verify_script(scriptPubKey.data(), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), nIn, libconsensus_flags, &err);
    1609           1 :     BOOST_CHECK_EQUAL(result, 0);
    1610           1 :     BOOST_CHECK_EQUAL(err, bitcoinconsensus_ERR_INVALID_FLAGS);
    1611           1 : }
    1612             : 
    1613             : #endif
    1614          89 : BOOST_AUTO_TEST_SUITE_END()

Generated by: LCOV version 1.15