bit-matrix / script-wiz-lib

MIT License
42 stars 5 forks source link

Negative zero is buggy in scriptwiz #49

Open brilliancebitcoin opened 1 year ago

brilliancebitcoin commented 1 year ago

I am experimenting with a script that utilizes negative 0. But negative zero seems to not work in scriptwiz. For example if I do this:

OP_0 OP_NEGATE

Scriptwiz shows me the ordinary zero, not a negated version. Also, if I try to express this sequence:

-1, -0, 0, 1

using their hex encodings, I try this:

<0x81>
<0x80>
<0x>
<0x01>

But I get this unexpected result:

-1 0x80 0 1

Negative zero is sometimes necessary when doing 32 bit binary addition in bitcoin script. For example, suppose you binary-add together 64 bits (treating them as two sets of 32 bits each) and you happen to get this result:

10000000000000000000000000000000

If, to save space on the stack, you roll that 32 bit number up into a 4 byte integer, everything after the leading bit is 0, but, because bitcoin script uses signed integers, it will interpret the leading 1 as a negator, resulting in -0. So I would want to store a negative 0 on the stack to represent these 32 bits. Similarly, if I want to take the representation -0 later in my script and "unpack" it into its constituent 32 bits, I need to know the sign of the 0 so that I can compute whether the leading bit should be a 1 or a 0.

It would be great if scriptwiz handled negative 0s properly so that I can use it to continue experimenting with 32 bit adders.

By the way, the reason I want 32 bit adders is because I am trying to implement a sha256 algorithm in bitcoin script that allows for checking if the hash of the input has a certain number of leading 0s. To do this on I need to implement the entirety of the sha256 algorithm in bitcoin script, and the algorithm uses 32 bit addition several times, and -- when experimenting with hashing an empty string in particular, which is a common test vector -- this requires rolling up 10000000000000000000000000000000 and representing it as negative 0.

brqgoo commented 1 year ago

Hi @brilliancebitcoin I just tried OP_0 OP_NEGATE on regtest. It resulted in an ordinary zero (empty element). Let me know a tangible example that may result in a negative zero (0x81).