Unexpected Overflow on U256

Hi!
I am getting an unexpected overflow on the following calculation:

contract;
use std::{
    u256::U256,
};

abi MyContract {
    fn test_function() -> bool;
}

impl MyContract for Contract {
    fn test_function() -> bool {
        let sum_u64_max = U256::from((0, 0, 0, u64::max())) + U256::from((0, 0, 0, u64::max()));
        let will_overflow = sum_u64_max * sum_u64_max;
        true
    }
}

The number will_overflow = (264-1+264-1)*(264-1+264-1) which is << 2^256-1 returns the following error:

thread 'will_overflow' panicked at 'called `Result::unwrap()` on an `Err` value: RevertTransactionError("ArithmeticOverflow", [Call { id: 0000000000000000000000000000000000000000000000000000000000000000, to: 615aefc112c0d5bde30230cc4202e7b2e6e759d3139bdde8250d5ce0ad676f3b, amount: 0, asset_id: 0000000000000000000000000000000000000000000000000000000000000000, gas: 100000000, param1: 559005003, param2: 1, pc: 11624, is: 11624 }, Panic { id: 615aefc112c0d5bde30230cc4202e7b2e6e759d3139bdde8250d5ce0ad676f3b, reason: InstructionResult { reason: ArithmeticOverflow, instruction: Instruction { op: 45, ra: 16, rb: 18, rc: 19, rd: 17, imm06: 209, imm12: 1233, imm18: 74961, imm24: 4269265 } }, pc: 21320, is: 11624, contract_id: None }, ScriptResult { result: Panic, gas_used: 190373 }])', tests/harness.rs:47:6

Can this be an issue with the overflow checks ?

No, this is an arithmetic issue.

sum_u64_max^2 is a pretty big number. That does not fit in a u256, and causes an overflow.

1 Like

If I understand the snippet correctly, the expression should evaluate to a number of the order (2^64)^2 rather than 2^(64^2) as per the wolfram link.

In this case, it should fit in a U256… the exact calculation here

I’ll try and reproduce.

1 Like

Correct. With the contract above you should be able to reproduce the error.