btc-vision / btc-runtime

Assemblyscript btc runtime
MIT License
4 stars 2 forks source link

u256.fromBytes fails with out of memory error on bytes array #39

Closed liquitious closed 7 hours ago

liquitious commented 5 days ago

Note that sha256(latestRandomSeed.toUint8Array()) works and logging it I get something like: 109,8,85,163,53,128,47,11,194,9,70,243,196,140,5,182,185,140,20,181,120,2,13,95,66,161,102,185,127,230,245,159

Easiest way to reproduce that shows issue is not related to sha256:

// this crashes with out of memory error!!
latestRandomSeed = u256.fromBytes([
                109, 8, 85, 163, 53, 128, 47, 11, 194, 9, 70, 243, 196, 140, 5, 182, 185, 140, 20,
                181, 120, 2, 13, 95, 66, 161, 102, 185, 127, 230, 245, 159,
            ] as u8[]);

even on an array of len 2 bytes or 4 bytes we get this same crash

BlobMaster41 commented 3 days ago

Thanks for reporting. ill investigate

BlobMaster41 commented 3 days ago

crashes: u256.fromBytes(sha256(latestRandomSeed.toUint8Array())). both LE and BE fail with error: [OPNetUnit HELP PANIC]: Error: out of memory

This means that your contract is using more memory that what you have specified. Are you using the asconfig file included in the project? This file set the memory at a maximum of 512 memory pages which equals to 32.768mb. This is the maximum a contract can consume.

If your memory is that high, your gas will be very high.

liquitious commented 7 hours ago

I drew incorrect conclusion that error was due to the u256.fromBytes. It is actually the following Safemath.mod we do. It seems this method if implemented inefficiently so if we pass a large number in we get a crash. Looks like solidity has optimized the % operation: https://github.com/polynetwork/eth-contracts/blob/master/contracts/libs/math/SafeMath.sol#L154

liquitious commented 6 hours ago

Opened new issue here: #42