1

I've been playing with huff language (assembly for EVM) and tried creating a macro for subtraction modulo n.

At first, I thought it would be easy since addmod(a,n-b,n) would do the job, but this isn't the case since all intermediate calculations of this operation are not subject to the 2^256 modulo.

and resulting a+n-b as negative number such as -2 would not give the correct representation.

So my question is: does somebody have an idea of the algorithm needed to implement this?

1 Answer 1

1

I think I did it, but anyway want to hear other thoughts:

#define macro SUB_MOD() = takes (0) returns (0) {
    // a - b % n = a + (n-b) % n
    0x44 calldataload     // [number3] // load third 32 bytes onto the stack - (n)

    0x24 calldataload     // [number2] // load second 32 bytes onto the stack - (n)
    0x44 calldataload     // [number3] // load third 32 bytes onto the stack - (b)
    sub                   // [number3-number2]
    0x04 calldataload     // [number1] // load first 32 bytes onto the stack - (a)
    add                   // [number1 + (number3-number2)]
    mod                   // [number1 + (number3-number2)] mod number3
    0x00 mstore           // place [number1 + (number3-number2) % number3] in memory
    0x20 0x00 return      // return first 32 bytes (result)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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