Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#530] Added BigIntPackDivmod and BigIntSafeDiv hints #613

Merged
merged 14 commits into from
Jul 30, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions pkg/hintrunner/utils/secp_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/consensys/gnark-crypto/ecc/stark-curve/fp"
)

func getBaseBig() (big.Int, bool) {
func GetBaseBig() (big.Int, bool) {
// 2**86
base, ok := new(big.Int).SetString("77371252455336267181195264", 10)
return *base, ok
Expand All @@ -35,9 +35,9 @@ func GetN() (big.Int, bool) {
func SecPPacked(limbs [3]*fp.Element) (big.Int, error) {
// https://github.com/starkware-libs/cairo-lang/blob/efa9648f57568aad8f8a13fbf027d2de7c63c2c0/src/starkware/cairo/common/cairo_secp/secp_utils.py#L28

baseBig, ok := getBaseBig()
baseBig, ok := GetBaseBig()
if !ok {
return *big.NewInt(0), fmt.Errorf("getBaseBig failed")
return *big.NewInt(0), fmt.Errorf("GetBaseBig failed")
}

packedBig := new(big.Int)
Expand All @@ -60,7 +60,7 @@ func SecPSplit(num *big.Int) ([]big.Int, error) {

split := make([]big.Int, 3)

baseBig, ok := getBaseBig()
baseBig, ok := GetBaseBig()
if !ok {
return nil, fmt.Errorf("GetBaseBig failed")
}
Expand Down
2 changes: 2 additions & 0 deletions pkg/hintrunner/zero/hintcode.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ const (
recoverYCode string = "from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME\nfrom starkware.python.math_utils import recover_y\nids.p.x = ids.x\n# This raises an exception if `x` is not on the curve.\nids.p.y = recover_y(ids.x, ALPHA, BETA, FIELD_PRIME)"
randomEcPointCode string = "from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME\nfrom starkware.python.math_utils import random_ec_point\nfrom starkware.python.utils import to_bytes\n\n# Define a seed for random_ec_point that's dependent on all the input, so that:\n# (1) The added point s is deterministic.\n# (2) It's hard to choose inputs for which the builtin will fail.\nseed = b\"\".join(map(to_bytes, [ids.p.x, ids.p.y, ids.m, ids.q.x, ids.q.y]))\nids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"
chainedEcOpCode string = "from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME\nfrom starkware.python.math_utils import random_ec_point\nfrom starkware.python.utils import to_bytes\n\nn_elms = ids.len\nassert isinstance(n_elms, int) and n_elms >= 0, \\\n f'Invalid value for len. Got: {n_elms}.'\nif '__chained_ec_op_max_len' in globals():\n assert n_elms <= __chained_ec_op_max_len, \\\n f'chained_ec_op() can only be used with len<={__chained_ec_op_max_len}. ' \\\n f'Got: n_elms={n_elms}.'\n\n# Define a seed for random_ec_point that's dependent on all the input, so that:\n# (1) The added point s is deterministic.\n# (2) It's hard to choose inputs for which the builtin will fail.\nseed = b\"\".join(\n map(\n to_bytes,\n [\n ids.p.x,\n ids.p.y,\n *memory.get_range(ids.m, n_elms),\n *memory.get_range(ids.q.address_, 2 * n_elms),\n ],\n )\n)\nids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"
bigIntPackDivModCode string = "from starkware.cairo.common.cairo_secp.secp_utils import pack\nfrom starkware.cairo.common.math_utils import as_int\nfrom starkware.python.math_utils import div_mod, safe_div\n\np = pack(ids.P, PRIME)\nx = pack(ids.x, PRIME) + as_int(ids.x.d3, PRIME) * ids.BASE ** 3 + as_int(ids.x.d4, PRIME) * ids.BASE ** 4\ny = pack(ids.y, PRIME)\n\nvalue = res = div_mod(x, y, p)"
bigIntSaveDivCode string = "k = safe_div(res * y - x, p)\nvalue = k if k > 0 else 0 - k\nids.flag = 1 if k > 0 else 0"

// ------ Signature hints related code ------
verifyECDSASignatureCode string = "ecdsa_builtin.add_signature(ids.ecdsa_ptr.address_, (ids.signature_r, ids.signature_s))"
Expand Down
4 changes: 4 additions & 0 deletions pkg/hintrunner/zero/zerohint.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ func GetHintFromCode(program *zero.ZeroProgram, rawHint zero.Hint) (hinter.Hinte
return createRandomEcPointHinter(resolver)
case chainedEcOpCode:
return createChainedEcOpHinter(resolver)
case bigIntPackDivModCode:
return createBigIntPackDivModHinter(resolver)
case bigIntSaveDivCode:
return createBigIntSaveDivHinter()
// Blake hints
case blake2sAddUint256BigendCode:
return createBlake2sAddUint256Hinter(resolver, true)
Expand Down
189 changes: 189 additions & 0 deletions pkg/hintrunner/zero/zerohint_ec.go
Original file line number Diff line number Diff line change
Expand Up @@ -1695,3 +1695,192 @@ func createChainedEcOpHinter(resolver hintReferenceResolver) (hinter.Hinter, err

return newChainedEcOpHint(len, p, m, q, s), nil
}

// BigIntPackDivMod hint divides two values modulo a prime number
//
// `newBigIntPackDivModHint` takes 3 operanders as arguments
// - `P` is the prime modulus
// - `x` is the numerator
// - `y` is the denominator
//
// `newBigIntPackDivModHint` assigns the result as `value` in the current scope
func newBigIntPackDivModHint(x, y, p hinter.ResOperander) hinter.Hinter {
return &GenericZeroHinter{
Name: "DivMod",
Op: func(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error {
//> from starkware.cairo.common.cairo_secp.secp_utils import pack
//> from starkware.cairo.common.math_utils import as_int
//> from starkware.python.math_utils import div_mod, safe_div
//>
//> p = pack(ids.P, PRIME)
//> x = pack(ids.x, PRIME) + as_int(ids.x.d3, PRIME) * ids.BASE ** 3 + as_int(ids.x.d4, PRIME) * ids.BASE ** 4
//> y = pack(ids.y, PRIME)
//>
//> value = res = div_mod(x, y, p)

pAddr, err := p.GetAddress(vm)
if err != nil {
return err
}

pValues, err := vm.Memory.ResolveAsBigInt3(pAddr)
if err != nil {
return err
}

xAddr, err := x.GetAddress(vm)
if err != nil {
return err
}

xValues, err := vm.Memory.ResolveAsBigInt3(xAddr)
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}

yAddr, err := y.GetAddress(vm)
if err != nil {
return err
}

yValues, err := vm.Memory.ResolveAsBigInt3(yAddr)
if err != nil {
return err
}

var xD3Big big.Int
var xD4Big big.Int

xValues[0].BigInt(&xD3Big)
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
xValues[1].BigInt(&xD4Big)

base, ok := secp_utils.GetBaseBig()
if !ok {
return fmt.Errorf("getBaseBig failed")
}

//> p = pack(ids.P, PRIME)
pBig, err := secp_utils.SecPPacked(pValues)
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}

//> x = pack(ids.x, PRIME) + as_int(ids.x.d3, PRIME) * ids.BASE ** 3 + as_int(ids.x.d4, PRIME) * ids.BASE ** 4
xPacked, err := secp_utils.SecPPacked(xValues)
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}

base3Big := new(big.Int)

base3Big.Exp(&base, big.NewInt(3), big.NewInt(0))

base4Big := new(big.Int)

base4Big.Exp(&base, big.NewInt(4), big.NewInt(0))

xBig := new(big.Int)

xBig.Mul(&xD3Big, base3Big)

xBig.Add(xBig, xBig.Mul(&xD4Big, base4Big))

xBig.Add(xBig, &xPacked)

//> y = pack(ids.y, PRIME)
yBig, err := secp_utils.SecPPacked(yValues)
if err != nil {
return err
}

//> value = res = div_mod(x, y, p)
res, err := secp_utils.Divmod(xBig, &yBig, &pBig)
if err != nil {
return err
}

return ctx.ScopeManager.AssignVariables(map[string]any{"value": &res})
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
},
}
}

func createBigIntPackDivModHinter(resolver hintReferenceResolver) (hinter.Hinter, error) {
x, err := resolver.GetResOperander("x")
if err != nil {
return nil, err
}

y, err := resolver.GetResOperander("y")
if err != nil {
return nil, err
}

p, err := resolver.GetResOperander("P")
if err != nil {
return nil, err
}

return newBigIntPackDivModHint(x, y, p), nil
}

// SafeDiv hint safely divides two numbers and assigns the result based on a condition
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
//
// `newSafeDivHint` does not take any arguments
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
//
// `newSafeDivHint` assigns the result as `value` and sets `flag` based on the result in the current scope
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
func newBigIntSafeDivHint() hinter.Hinter {
return &GenericZeroHinter{
Name: "SafeDiv",
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
Op: func(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error {
//> k = safe_div(res * y - x, p)
//> value = k if k > 0 else 0 - k
//> ids.flag = 1 if k > 0 else 0

x, err := hinter.GetVariableAs[*big.Int](&ctx.ScopeManager, "x")
if err != nil {
return err
}

y, err := hinter.GetVariableAs[*big.Int](&ctx.ScopeManager, "y")
if err != nil {
return err
}

p, err := hinter.GetVariableAs[*big.Int](&ctx.ScopeManager, "p")
if err != nil {
return err
}

res, err := hinter.GetVariableAs[*big.Int](&ctx.ScopeManager, "res")
if err != nil {
return err
}

//> k = safe_div(res * y - x, p)
tmp := new(big.Int)
tmp.Mul(res, y)
tmp.Sub(tmp, x)
k := new(big.Int).Div(tmp, p)

//> value = k if k > 0 else 0 - k
value := new(big.Int).Abs(k)

//> ids.flag = 1 if k > 0 else 0
flag := big.NewInt(0)
if k.Sign() > 0 {
flag.SetInt64(1)
}

err = ctx.ScopeManager.AssignVariables(map[string]any{"value": value, "flag": flag})
TAdev0 marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}

return nil
},
}
}

func createBigIntSaveDivHinter() (hinter.Hinter, error) {
return newBigIntSafeDivHint(), nil
}
Loading