Addmod / mulmod as built-in functions

I recently attempted a public key derivation of an elliptic curve using Cadence. This is part of an experimental art creation using smart contracts.
Take a look at the GitHub repository below.

In the process, I suffered from overflow constraints. I would prefer not to allow overflow/underflow in ordinary codes, but I thought there might be a certain demand for addmod / mulmod as built-in functions.

I realize that this will affect the security of the smart contract code, but at the same time, I think it will be an element of creativity in a great environment for resource oriented programming.

What do you think about this? Have you considered this in the past?


@avcd Awesome work!

If you want to perform over/underflowing arithmetic, you can use the Word* types instead of the UInt* types, see the bottom of the “Integers” section: Values and Types | Flow Blockchain

1 Like

Nice work!

I believe modular arithmetic for 256 bits numbers could be implemented on Cadence as a little “library” (modAdd, modSub, modMul and modInv). That’s what Math libraries do based on the low level “limited” operations.
The lib could hardcode some known modulos like the one you used from secp256k1, for a faster computation.

Btw multiplication on your code could nicely leverage the 128-bits or 64-bits operations provided by Cadence, by using Karatsuba algorithm. This should improve performance significantly.


Thank you for the info :blush:
If Word128 and Word256, which are even larger than Word64, were available…
Is there a reason why Word256 was never created? (If known)

1 Like

This is exactly what I want!

Karatsuba algorithm

Thanks for letting me know. This will make the calculations a lot smaller (but that’s still not a workable calculation :joy:)

@avcd We would highly appreciate a PR adding such functionality directly to Cadence!

Adding the Word128 and Word256 types is mainly copy and pasting existing code (UInt128 and UInt256). Adding the operations is little work, most of the effort is likely in testing it thoroughly.

We’re more than happy to assist you or anyone else who would like to add this!


Related Cadence issue:

cc @avcd