Skip to content

Commit 5b75c47

Browse files
committed
Add a valid opcode sanity check to CScript
Added a function in CScript that checks if the script contains valid opcodes. Add a test for that function
1 parent 9fec4da commit 5b75c47

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

src/script/script.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,3 +267,15 @@ std::string CScriptWitness::ToString() const
267267
}
268268
return ret + ")";
269269
}
270+
271+
bool CScript::HasValidOps() const
272+
{
273+
CScript::const_iterator it = begin();
274+
while (it < end()) {
275+
opcodetype opcode;
276+
if (!GetOp(it, opcode) || opcode > 0xb9) {
277+
return false;
278+
}
279+
}
280+
return true;
281+
}

src/script/script.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,9 @@ class CScript : public CScriptBase
630630
bool IsPushOnly(const_iterator pc) const;
631631
bool IsPushOnly() const;
632632

633+
/** Check if the script contains valid OP_CODES */
634+
bool HasValidOps() const;
635+
633636
/**
634637
* Returns whether the script is guaranteed to fail at execution,
635638
* regardless of the initial stack. This allows outputs to be pruned

src/test/script_tests.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1438,4 +1438,18 @@ BOOST_AUTO_TEST_CASE(script_FindAndDelete)
14381438
BOOST_CHECK(s == expect);
14391439
}
14401440

1441+
BOOST_AUTO_TEST_CASE(script_HasValidOps)
1442+
{
1443+
// Exercise the HasValidOps functionality
1444+
CScript script;
1445+
script = ScriptFromHex("76a9141234567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac"); // Normal script
1446+
BOOST_CHECK(script.HasValidOps());
1447+
script = ScriptFromHex("76a914ff34567890abcdefa1a2a3a4a5a6a7a8a9a0aaab88ac");
1448+
BOOST_CHECK(script.HasValidOps());
1449+
script = ScriptFromHex("ff88ac"); // Script with OP_INVALIDOPCODE explicit
1450+
BOOST_CHECK(!script.HasValidOps());
1451+
script = ScriptFromHex("88acc0"); // Script with undefined opcode
1452+
BOOST_CHECK(!script.HasValidOps());
1453+
}
1454+
14411455
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)