diff --git a/pkg/lambdaworks/lambdaworks.go b/pkg/lambdaworks/lambdaworks.go index f944eaeb..d66e7b24 100644 --- a/pkg/lambdaworks/lambdaworks.go +++ b/pkg/lambdaworks/lambdaworks.go @@ -284,6 +284,11 @@ func (f Felt) ToBigInt() *big.Int { } func FeltFromBigInt(n *big.Int) Felt { + // Perform modulo prime + prime, _ := new(big.Int).SetString(CAIRO_PRIME_HEX, 0) + if n.Cmp(prime) != -1 { + n = new(big.Int).Mod(n, prime) + } bytes := n.Bytes() var bytes32 [32]byte copy(bytes32[:], bytes) diff --git a/pkg/lambdaworks/lambdaworks_test.go b/pkg/lambdaworks/lambdaworks_test.go index 9b03f186..bffb7e7a 100644 --- a/pkg/lambdaworks/lambdaworks_test.go +++ b/pkg/lambdaworks/lambdaworks_test.go @@ -78,6 +78,14 @@ func TestFromBigInt(t *testing.T) { } } +func TestFromBigIntPrime(t *testing.T) { + expectedFelt := lambdaworks.FeltFromDecString("0") + bigInt, _ := new(big.Int).SetString(lambdaworks.CAIRO_PRIME_HEX, 0) + if !reflect.DeepEqual(lambdaworks.FeltFromBigInt(bigInt), expectedFelt) { + t.Errorf("TestToBigInt failed. Expected: PRIME, Got: %v", lambdaworks.FeltFromBigInt(bigInt)) + } +} + func TestToSignedNegative(t *testing.T) { felt := lambdaworks.FeltFromDecString("-1") bigInt := felt.ToSigned()