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