Overflow/underflow of []byte integer operations - General - Algorand

Overflow/underflow of []byte integer operations

post by hungpq on Feb 15, 2022

I did read about byte operation here Opcodes - Algorand Developer Portal. So I think if need require large result number, I should use byte instead of uint64 (due to the value).

But I want to know what if the +,* failed on overflow or - operation failed on underflow for bytes (I see in uint operation it did)? What happened when they do not fail (the result will be unexpected)?

post by fabrice on Feb 16, 2022

The byte integer operations b+ and b* do not overflow. The result will just be larger than 64 bytes.

b- fails on underflow.

See Transaction Execution Approval Language (TEAL) - Algorand Developer Portal for details.

post by hungpq on Feb 16, 2022

I still have some confusion when reading the doc.

Sorry if I’m not getting it but I really want to deeply understand this.

post by fabrice on Feb 16, 2022

The result can be larger than 64 bytes.

It can never happen. When you add or multiply two 64-byte numbers, the result always fits in 128 bytes.

post by hungpq on Feb 16, 2022

Thanks for your answer. It helped me a lot.

Just to be clear, for example with this PyTeal operation BytesDiv(BytesMul(a,b),c):

If a*b exceeds 64 bytes, then the (a*b)/c will fail (since the left argument (which is a*b) exceeds 64 bytes), right? The same happens with b*, b+, b-?

post by fabrice on Feb 16, 2022

Yes, if a*b exceeds 64 bytes, the above operation will fail.

Note that it is “bytes” not “bits”. 64 bytes = 512 bits, which is very, very large.

(Remember uint64 = 64 bits = 8 bytes.)

BytesMul in PyTeal compiles to b*.

BytesDiv in PyTeal compiles to b/.

And so on.

post by fabrice on Feb 16, 2022

These are used if you don’t want to use the b... operations.

Nowadays, I think b... operations are much easier.

post by hungpq on Mar 31, 2022

Thanks for your answer. I have another question regarding byte calculation.

Back to the scenario where I have BytesMul(a,b). If a*b exceeds 64 bytes and I store the result in a scratch slot or global/local slot (which is defined as bytes), will it work?

If not, what does the result of a*b that exceeds 64 bytes can work? Why doesn’t it fail on overflow?

post by fabrice on Mar 31, 2022

Inputs of the b+, b*, … operations are limited to 64 bytes.

But outputs are not.

So b* output may be 128 bytes. There is never an overflow.

However, then you cannot use the 128-byte output in any of the b+, b*, … operations.

post by hungpq on Mar 31, 2022

Thanks for your answer.

My question is can the 128-byte output be stored in a scratch slot or global variable in an application (which type is defined as bytes)?

If not, what can this 128-byte output be used for?