7

I wonder whether

OP_DEPTH 0 OP_EQUAL

has the exact same behavior as

OP_DEPTH OP_NOT

which is

1 if no items
0 if any number of items

I'm asking because the first script is used and I'm not sure if there is any justification for that. It's very likely that they took the simple approach but I need to make sure about that since I want to squeeze the largest number of bytes out of script.

7

In general 0 EQUAL is not equivalent to NOT, but in this case they are indeed equivalent.

The reason they're not equivalent in general is that 0 EQUAL checks that the top stack element is exactly a canonical 0 push, i.e. the zero-length stack element. NOT, on the other hand, checks that the top stack element is numerically equal to 0. This means that it is between 0 and 4 bytes inclusive and all bits are zero except possibly the most significant one, which would indicate -0. If the top stack element has more than 4 bytes then NOT will fail the script immediately, similar to RETURN; there is no way to make 0 EQUAL fail the script.

For all these reasons you should be a bit careful using NOT in general -- although in practice standardness rules in most of the network will prevent any of the noncanonical encodings of 0 (or any encoding of -0) to propagate. But in principle if you call NOT directly on witness data then this is a malleability vector.

However, all of this is moot because the output of DEPTH is guaranteed to be a canonically encoded number. So NOT is perfectly safe and does indeed save the extra byte.

2
  • NOT doesn't seem to fail if input has more than 4 bytes. I tested this by OP_PUSHDATA1 5 0x0500000000 OP_NOT OP_1 OP_ADD here or 500000000 op_not 1 op_add here
    – MCCCS
    Feb 18 at 12:18
  • 1
    @MCCCS then those two sites are wrong, and you shouldn't use them as script interpreters. Bitcoin Core interprets the top stack element as a number here which rejects numbers bigger than 4 here. Feb 19 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.