diff --git a/.golangci.yml b/.golangci.yml index fbfb7e4a5..5959b357a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,4 +14,4 @@ linters: run: skip-files: - pkg/assembler/grammar.go - - pkg/hintrunner/hintparser.go + - pkg/hintrunner/zero/hintparser.go diff --git a/Makefile b/Makefile index 3aaeb31fa..e471c7348 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ .PHONY: lint build clean test help format staticcheck pre-commit -GOPATH_DIR=`go env GOPATH` +GOPATH_DIR :=`go env GOPATH` BINARY_DIR := bin BINARY_NAME := cairo-vm @@ -59,5 +59,5 @@ bench: # Use the same version of the golangci-lint as in our CI linting config. lint: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.53.3 - golangci-lint run ./... + golangci-lint run ./... -v @echo "lint: all good!" diff --git a/cmd/cli/main.go b/cmd/cli/main.go index cc7b98e59..53f35de1e 100644 --- a/cmd/cli/main.go +++ b/cmd/cli/main.go @@ -5,7 +5,7 @@ import ( "math" "os" - hintrunner "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner" + hintrunner "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/zero" zero "github.com/NethermindEth/cairo-vm-go/pkg/parsers/zero" runnerzero "github.com/NethermindEth/cairo-vm-go/pkg/runners/zero" "github.com/urfave/cli/v2" diff --git a/pkg/hintrunner/hint.go b/pkg/hintrunner/core/hint.go similarity index 88% rename from pkg/hintrunner/hint.go rename to pkg/hintrunner/core/hint.go index cd63d103d..bf8a866f6 100644 --- a/pkg/hintrunner/hint.go +++ b/pkg/hintrunner/core/hint.go @@ -1,4 +1,4 @@ -package hintrunner +package core import ( "fmt" @@ -7,33 +7,29 @@ import ( "github.com/holiman/uint256" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" + u "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/utils" "github.com/NethermindEth/cairo-vm-go/pkg/utils" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" ) -type Hinter interface { - fmt.Stringer - - Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error -} - type AllocSegment struct { - dst CellRefer + Dst hinter.CellRefer } func (hint *AllocSegment) String() string { return "AllocSegment" } -func (hint *AllocSegment) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint *AllocSegment) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { newSegment := vm.Memory.AllocateEmptySegment() memAddress := mem.MemoryValueFromMemoryAddress(&newSegment) - regAddr, err := hint.dst.Get(vm) + regAddr, err := hint.Dst.Get(vm) if err != nil { - return fmt.Errorf("get register %s: %w", hint.dst, err) + return fmt.Errorf("get register %s: %w", hint.Dst, err) } err = vm.Memory.WriteToAddress(®Addr, &memAddress) @@ -45,16 +41,16 @@ func (hint *AllocSegment) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) e } type TestLessThan struct { - dst CellRefer - lhs ResOperander - rhs ResOperander + dst hinter.CellRefer + lhs hinter.ResOperander + rhs hinter.ResOperander } func (hint *TestLessThan) String() string { return "TestLessThan" } -func (hint *TestLessThan) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint *TestLessThan) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { lhsVal, err := hint.lhs.Resolve(vm) if err != nil { return fmt.Errorf("resolve lhs operand %s: %w", hint.lhs, err) @@ -95,16 +91,16 @@ func (hint *TestLessThan) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) e } type TestLessThanOrEqual struct { - dst CellRefer - lhs ResOperander - rhs ResOperander + dst hinter.CellRefer + lhs hinter.ResOperander + rhs hinter.ResOperander } func (hint *TestLessThanOrEqual) String() string { return "TestLessThanOrEqual" } -func (hint *TestLessThanOrEqual) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint *TestLessThanOrEqual) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { lhsVal, err := hint.lhs.Resolve(vm) if err != nil { return fmt.Errorf("resolve lhs operand %s: %w", hint.lhs, err) @@ -145,14 +141,14 @@ func (hint *TestLessThanOrEqual) Execute(vm *VM.VirtualMachine, _ *HintRunnerCon } type LinearSplit struct { - value ResOperander - scalar ResOperander - maxX ResOperander - x CellRefer - y CellRefer + value hinter.ResOperander + scalar hinter.ResOperander + maxX hinter.ResOperander + x hinter.CellRefer + y hinter.CellRefer } -func (hint LinearSplit) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint LinearSplit) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { value, err := hint.value.Resolve(vm) if err != nil { return fmt.Errorf("resolve value operand %s: %w", hint.value, err) @@ -225,17 +221,17 @@ func (hint LinearSplit) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) err } type WideMul128 struct { - lhs ResOperander - rhs ResOperander - high CellRefer - low CellRefer + lhs hinter.ResOperander + rhs hinter.ResOperander + high hinter.CellRefer + low hinter.CellRefer } func (hint *WideMul128) String() string { return "WideMul128" } -func (hint *WideMul128) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint *WideMul128) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { mask := &utils.Uint256Max128 lhs, err := hint.lhs.Resolve(vm) @@ -299,17 +295,17 @@ func (hint *WideMul128) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) err } type DivMod struct { - lhs ResOperander - rhs ResOperander - quotient CellRefer - remainder CellRefer + lhs hinter.ResOperander + rhs hinter.ResOperander + quotient hinter.CellRefer + remainder hinter.CellRefer } func (hint DivMod) String() string { return "DivMod" } -func (hint DivMod) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint DivMod) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { lhsVal, err := hint.lhs.Resolve(vm) if err != nil { @@ -382,21 +378,21 @@ func (hint DivMod) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { } type Uint256DivMod struct { - dividend0 ResOperander - dividend1 ResOperander - divisor0 ResOperander - divisor1 ResOperander - quotient0 CellRefer - quotient1 CellRefer - remainder0 CellRefer - remainder1 CellRefer + dividend0 hinter.ResOperander + dividend1 hinter.ResOperander + divisor0 hinter.ResOperander + divisor1 hinter.ResOperander + quotient0 hinter.CellRefer + quotient1 hinter.CellRefer + remainder0 hinter.CellRefer + remainder1 hinter.CellRefer } func (hint Uint256DivMod) String() string { return "Uint256DivMod" } -func (hint Uint256DivMod) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint Uint256DivMod) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { dividend0, err := hint.dividend0.Resolve(vm) if err != nil { return fmt.Errorf("resolve dividend0 operand %s: %v", hint.dividend0, err) @@ -506,11 +502,11 @@ func (hint Uint256DivMod) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) e } type DebugPrint struct { - start ResOperander - end ResOperander + start hinter.ResOperander + end hinter.ResOperander } -func (hint DebugPrint) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint DebugPrint) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { start, err := hint.start.Resolve(vm) if err != nil { return fmt.Errorf("resolve start operand %s: %v", hint.start, err) @@ -553,15 +549,15 @@ func (hint DebugPrint) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) erro } type SquareRoot struct { - value ResOperander - dst CellRefer + value hinter.ResOperander + dst hinter.CellRefer } func (hint *SquareRoot) String() string { return "SquareRoot" } -func (hint *SquareRoot) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint *SquareRoot) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { value, err := hint.value.Resolve(vm) if err != nil { return fmt.Errorf("resolve value operand %s: %w", hint.value, err) @@ -593,20 +589,20 @@ func (hint *SquareRoot) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) err } type Uint256SquareRoot struct { - valueLow ResOperander - valueHigh ResOperander - sqrt0 CellRefer - sqrt1 CellRefer - remainderLow CellRefer - remainderHigh CellRefer - sqrtMul2MinusRemainderGeU128 CellRefer + valueLow hinter.ResOperander + valueHigh hinter.ResOperander + sqrt0 hinter.CellRefer + sqrt1 hinter.CellRefer + remainderLow hinter.CellRefer + remainderHigh hinter.CellRefer + sqrtMul2MinusRemainderGeU128 hinter.CellRefer } func (hint Uint256SquareRoot) String() string { return "Uint256SquareRoot" } -func (hint Uint256SquareRoot) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint Uint256SquareRoot) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { valueLow, err := hint.valueLow.Resolve(vm) if err != nil { return fmt.Errorf("resolve valueLow operand %s: %v", hint.valueLow, err) @@ -750,16 +746,16 @@ func (hint Uint256SquareRoot) Execute(vm *VM.VirtualMachine, _ *HintRunnerContex // type AllocFelt252Dict struct { - SegmentArenaPtr ResOperander + SegmentArenaPtr hinter.ResOperander } func (hint *AllocFelt252Dict) String() string { return "AllocFelt252Dict" } -func (hint *AllocFelt252Dict) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { - InitializeDictionaryManagerIfNot(ctx) +func (hint *AllocFelt252Dict) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { + hinter.InitializeDictionaryManager(ctx) - arenaPtr, err := ResolveAsAddress(vm, hint.SegmentArenaPtr) + arenaPtr, err := hinter.ResolveAsAddress(vm, hint.SegmentArenaPtr) if err != nil { return fmt.Errorf("resolve segment arena pointer: %w", err) } @@ -804,21 +800,21 @@ func (hint *AllocFelt252Dict) Execute(vm *VM.VirtualMachine, ctx *HintRunnerCont } type Felt252DictEntryInit struct { - DictPtr ResOperander - Key ResOperander + DictPtr hinter.ResOperander + Key hinter.ResOperander } func (hint Felt252DictEntryInit) String() string { return "Felt252DictEntryInit" } -func (hint *Felt252DictEntryInit) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { - dictPtr, err := ResolveAsAddress(vm, hint.DictPtr) +func (hint *Felt252DictEntryInit) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { + dictPtr, err := hinter.ResolveAsAddress(vm, hint.DictPtr) if err != nil { return fmt.Errorf("resolve dictionary pointer: %w", err) } - key, err := ResolveAsFelt(vm, hint.Key) + key, err := hinter.ResolveAsFelt(vm, hint.Key) if err != nil { return fmt.Errorf("resolve key: %w", err) } @@ -836,16 +832,16 @@ func (hint *Felt252DictEntryInit) Execute(vm *VM.VirtualMachine, ctx *HintRunner } type Felt252DictEntryUpdate struct { - DictPtr ResOperander - Value ResOperander + DictPtr hinter.ResOperander + Value hinter.ResOperander } func (hint Felt252DictEntryUpdate) String() string { return "Felt252DictEntryUpdate" } -func (hint *Felt252DictEntryUpdate) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { - dictPtr, err := ResolveAsAddress(vm, hint.DictPtr) +func (hint *Felt252DictEntryUpdate) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { + dictPtr, err := hinter.ResolveAsAddress(vm, hint.DictPtr) if err != nil { return fmt.Errorf("resolve dictionary pointer: %w", err) } @@ -872,21 +868,21 @@ func (hint *Felt252DictEntryUpdate) Execute(vm *VM.VirtualMachine, ctx *HintRunn } type GetSegmentArenaIndex struct { - DictIndex CellRefer - DictEndPtr ResOperander + DictIndex hinter.CellRefer + DictEndPtr hinter.ResOperander } func (hint *GetSegmentArenaIndex) String() string { return "GetSegmentArenaIndex" } -func (hint *GetSegmentArenaIndex) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *GetSegmentArenaIndex) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { dictIndex, err := hint.DictIndex.Get(vm) if err != nil { return fmt.Errorf("get dict index: %w", err) } - dictEndPtr, err := ResolveAsAddress(vm, hint.DictEndPtr) + dictEndPtr, err := hinter.ResolveAsAddress(vm, hint.DictEndPtr) if err != nil { return fmt.Errorf("resolve dict end pointer: %w", err) } @@ -905,29 +901,29 @@ func (hint *GetSegmentArenaIndex) Execute(vm *VM.VirtualMachine, ctx *HintRunner // type InitSquashData struct { - FirstKey CellRefer - BigKeys CellRefer - DictAccesses ResOperander - NumAccesses ResOperander + FirstKey hinter.CellRefer + BigKeys hinter.CellRefer + DictAccesses hinter.ResOperander + NumAccesses hinter.ResOperander } func (hint *InitSquashData) String() string { return "InitSquashData" } -func (hint *InitSquashData) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *InitSquashData) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { // todo(rodro): Don't know if it could be called multiple times, or - err := InitializeSquashedDictionaryManager(ctx) + err := hinter.InitializeSquashedDictionaryManager(ctx) if err != nil { return err } - dictAccessPtr, err := ResolveAsAddress(vm, hint.DictAccesses) + dictAccessPtr, err := hinter.ResolveAsAddress(vm, hint.DictAccesses) if err != nil { return fmt.Errorf("resolve dict access: %w", err) } - numAccess, err := ResolveAsUint64(vm, hint.NumAccesses) + numAccess, err := hinter.ResolveAsUint64(vm, hint.NumAccesses) if err != nil { return fmt.Errorf("resolve num access: %w", err) } @@ -987,15 +983,15 @@ func (hint *InitSquashData) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContex } type GetCurrentAccessIndex struct { - RangeCheckPtr ResOperander + RangeCheckPtr hinter.ResOperander } func (hint *GetCurrentAccessIndex) String() string { return "GetCurrentAccessIndex" } -func (hint *GetCurrentAccessIndex) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { - rangeCheckPtr, err := ResolveAsAddress(vm, hint.RangeCheckPtr) +func (hint *GetCurrentAccessIndex) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { + rangeCheckPtr, err := hinter.ResolveAsAddress(vm, hint.RangeCheckPtr) if err != nil { return fmt.Errorf("resolve range check pointer: %w", err) } @@ -1012,14 +1008,14 @@ func (hint *GetCurrentAccessIndex) Execute(vm *VM.VirtualMachine, ctx *HintRunne } type ShouldSkipSquashLoop struct { - ShouldSkipLoop CellRefer + ShouldSkipLoop hinter.CellRefer } func (hint *ShouldSkipSquashLoop) String() string { return "ShouldSkipSquashLoop" } -func (hint *ShouldSkipSquashLoop) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *ShouldSkipSquashLoop) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { shouldSkipLoopAddr, err := hint.ShouldSkipLoop.Get(vm) if err != nil { return fmt.Errorf("get should skip loop address: %w", err) @@ -1037,14 +1033,14 @@ func (hint *ShouldSkipSquashLoop) Execute(vm *VM.VirtualMachine, ctx *HintRunner } type GetCurrentAccessDelta struct { - IndexDeltaMinusOne CellRefer + IndexDeltaMinusOne hinter.CellRefer } func (hint *GetCurrentAccessDelta) String() string { return "GetCurrentAccessDelta" } -func (hint *GetCurrentAccessDelta) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *GetCurrentAccessDelta) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { indexDeltaPtr, err := hint.IndexDeltaMinusOne.Get(vm) if err != nil { return fmt.Errorf("get index delta address: %w", err) @@ -1068,14 +1064,14 @@ func (hint *GetCurrentAccessDelta) Execute(vm *VM.VirtualMachine, ctx *HintRunne } type ShouldContinueSquashLoop struct { - ShouldContinue CellRefer + ShouldContinue hinter.CellRefer } func (hint *ShouldContinueSquashLoop) String() string { return "ShouldContinueSquashLoop" } -func (hint *ShouldContinueSquashLoop) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *ShouldContinueSquashLoop) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { shouldContinuePtr, err := hint.ShouldContinue.Get(vm) if err != nil { return fmt.Errorf("get should continue address: %w", err) @@ -1093,14 +1089,14 @@ func (hint *ShouldContinueSquashLoop) Execute(vm *VM.VirtualMachine, ctx *HintRu } type GetNextDictKey struct { - NextKey CellRefer + NextKey hinter.CellRefer } func (hint *GetNextDictKey) String() string { return "GetNextDictKey" } -func (hint *GetNextDictKey) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *GetNextDictKey) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { nextKeyAddr, err := hint.NextKey.Get(vm) if err != nil { return fmt.Errorf("get next key address: %w", err) @@ -1116,25 +1112,25 @@ func (hint *GetNextDictKey) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContex } type Uint512DivModByUint256 struct { - dividend0 ResOperander - dividend1 ResOperander - dividend2 ResOperander - dividend3 ResOperander - divisor0 ResOperander - divisor1 ResOperander - quotient0 CellRefer - quotient1 CellRefer - quotient2 CellRefer - quotient3 CellRefer - remainder0 CellRefer - remainder1 CellRefer + dividend0 hinter.ResOperander + dividend1 hinter.ResOperander + dividend2 hinter.ResOperander + dividend3 hinter.ResOperander + divisor0 hinter.ResOperander + divisor1 hinter.ResOperander + quotient0 hinter.CellRefer + quotient1 hinter.CellRefer + quotient2 hinter.CellRefer + quotient3 hinter.CellRefer + remainder0 hinter.CellRefer + remainder1 hinter.CellRefer } func (hint Uint512DivModByUint256) String() string { return "Uint512DivModByUint256" } -func (hint Uint512DivModByUint256) Execute(vm *VM.VirtualMachine, _ *HintRunnerContext) error { +func (hint Uint512DivModByUint256) Execute(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error { dividend0, err := hint.dividend0.Resolve(vm) if err != nil { return fmt.Errorf("resolve dividend0 operand %s: %v", hint.dividend0, err) @@ -1289,16 +1285,16 @@ func (hint Uint512DivModByUint256) Execute(vm *VM.VirtualMachine, _ *HintRunnerC } type AllocConstantSize struct { - Size ResOperander - Dst CellRefer + Size hinter.ResOperander + Dst hinter.CellRefer } func (hint *AllocConstantSize) String() string { return "AllocConstantSize" } -func (hint *AllocConstantSize) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { - size, err := ResolveAsUint64(vm, hint.Size) +func (hint *AllocConstantSize) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { + size, err := hinter.ResolveAsUint64(vm, hint.Size) if err != nil { return fmt.Errorf("size to big: %w", err) } @@ -1323,16 +1319,16 @@ func (hint *AllocConstantSize) Execute(vm *VM.VirtualMachine, ctx *HintRunnerCon } type AssertLeFindSmallArc struct { - a ResOperander - b ResOperander - rangeCheckPtr ResOperander + a hinter.ResOperander + b hinter.ResOperander + rangeCheckPtr hinter.ResOperander } func (hint *AssertLeFindSmallArc) String() string { return "AssertLeFindSmallArc" } -func (hint *AssertLeFindSmallArc) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *AssertLeFindSmallArc) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { primeOver3High := uint256.Int{6148914691236517206, 192153584101141168, 0, 0} primeOver2High := uint256.Int{9223372036854775809, 288230376151711752, 0, 0} @@ -1378,7 +1374,7 @@ func (hint *AssertLeFindSmallArc) Execute(vm *VM.VirtualMachine, ctx *HintRunner // Exclude the largest arc after sorting ctx.ExcludedArc = lengthsAndIndices[2].Position - rangeCheckPtrMemAddr, err := ResolveAsAddress(vm, hint.rangeCheckPtr) + rangeCheckPtrMemAddr, err := hinter.ResolveAsAddress(vm, hint.rangeCheckPtr) if err != nil { return fmt.Errorf("resolve range check pointer: %w", err) } @@ -1438,14 +1434,14 @@ func (hint *AssertLeFindSmallArc) Execute(vm *VM.VirtualMachine, ctx *HintRunner } type AssertLeIsFirstArcExcluded struct { - skipExcludeAFlag CellRefer + skipExcludeAFlag hinter.CellRefer } func (hint *AssertLeIsFirstArcExcluded) String() string { return "AssertLeIsFirstArcExcluded" } -func (hint *AssertLeIsFirstArcExcluded) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *AssertLeIsFirstArcExcluded) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { addr, err := hint.skipExcludeAFlag.Get(vm) if err != nil { return fmt.Errorf("get skipExcludeAFlag addr: %v", err) @@ -1462,14 +1458,14 @@ func (hint *AssertLeIsFirstArcExcluded) Execute(vm *VM.VirtualMachine, ctx *Hint } type AssertLeIsSecondArcExcluded struct { - skipExcludeBMinusA CellRefer + skipExcludeBMinusA hinter.CellRefer } func (hint *AssertLeIsSecondArcExcluded) String() string { return "AssertLeIsSecondArcExcluded" } -func (hint *AssertLeIsSecondArcExcluded) Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error { +func (hint *AssertLeIsSecondArcExcluded) Execute(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error { addr, err := hint.skipExcludeBMinusA.Get(vm) if err != nil { return fmt.Errorf("get skipExcludeBMinusA addr: %v", err) @@ -1486,8 +1482,8 @@ func (hint *AssertLeIsSecondArcExcluded) Execute(vm *VM.VirtualMachine, ctx *Hin } type RandomEcPoint struct { - x CellRefer - y CellRefer + x hinter.CellRefer + y hinter.CellRefer } func (hint *RandomEcPoint) String() string { @@ -1501,9 +1497,9 @@ func (hint *RandomEcPoint) Execute(vm *VM.VirtualMachine) error { betaFelt := f.Element{3863487492851900874, 7432612994240712710, 12360725113329547591, 88155977965380735} var randomX, randomYSquared f.Element - rand := defaultRandGenerator() + rand := u.DefaultRandGenerator() for { - randomX = randomFeltElement(rand) + randomX = u.RandomFeltElement(rand) randomYSquared = f.Element{} randomYSquared.Square(&randomX) randomYSquared.Mul(&randomYSquared, &randomX) @@ -1545,8 +1541,8 @@ func (hint *RandomEcPoint) Execute(vm *VM.VirtualMachine) error { } type FieldSqrt struct { - val ResOperander - sqrt CellRefer + val hinter.ResOperander + sqrt hinter.CellRefer } func (hint *FieldSqrt) String() string { diff --git a/pkg/hintrunner/hint_bechmark_test.go b/pkg/hintrunner/core/hint_benchmark_test.go similarity index 58% rename from pkg/hintrunner/hint_bechmark_test.go rename to pkg/hintrunner/core/hint_benchmark_test.go index cb5c1fde9..ba0f3b030 100644 --- a/pkg/hintrunner/hint_bechmark_test.go +++ b/pkg/hintrunner/core/hint_benchmark_test.go @@ -1,8 +1,10 @@ -package hintrunner +package core import ( "testing" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/utils" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" "github.com/NethermindEth/cairo-vm-go/pkg/vm/builtins" "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" @@ -10,10 +12,10 @@ import ( ) func BenchmarkAllocSegment(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var ap ApCellRef = 1 + var ap hinter.ApCellRef = 1 b.ResetTimer() for i := 0; i < b.N; i++ { @@ -29,26 +31,26 @@ func BenchmarkAllocSegment(b *testing.B) { } func BenchmarkLessThan(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dst ApCellRef = 0 - var rhsRef ApCellRef = 1 + var dst hinter.ApCellRef = 0 + var rhsRef hinter.ApCellRef = 1 cell := uint64(0) - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() b.ResetTimer() for i := 0; i < b.N; i++ { - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Ap+uint64(rhsRef), memory.MemoryValueFromInt(rand.Int63()), ) - rhs := Deref{rhsRef} - lhs := Immediate(randomFeltElement(rand)) + rhs := hinter.Deref{Deref: rhsRef} + lhs := hinter.Immediate(utils.RandomFeltElement(rand)) hint := TestLessThan{ dst: dst, @@ -68,17 +70,17 @@ func BenchmarkLessThan(b *testing.B) { } func BenchmarkSquareRoot(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dst ApCellRef = 1 + var dst hinter.ApCellRef = 1 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() b.ResetTimer() for i := 0; i < b.N; i++ { - value := Immediate(randomFeltElement(rand)) + value := hinter.Immediate(utils.RandomFeltElement(rand)) hint := SquareRoot{ value: value, dst: dst, @@ -96,19 +98,19 @@ func BenchmarkSquareRoot(b *testing.B) { } func BenchmarkWideMul128(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dstLow ApCellRef = 0 - var dstHigh ApCellRef = 1 + var dstLow hinter.ApCellRef = 0 + var dstHigh hinter.ApCellRef = 1 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() b.ResetTimer() for i := 0; i < b.N; i++ { - lhs := Immediate(randomFeltElementU128(rand)) - rhs := Immediate(randomFeltElementU128(rand)) + lhs := hinter.Immediate(utils.RandomFeltElementU128(rand)) + rhs := hinter.Immediate(utils.RandomFeltElementU128(rand)) hint := WideMul128{ low: dstLow, @@ -128,19 +130,19 @@ func BenchmarkWideMul128(b *testing.B) { } func BenchmarkUintDivMod(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() - var quotient ApCellRef = 1 - var remainder ApCellRef = 2 + var quotient hinter.ApCellRef = 1 + var remainder hinter.ApCellRef = 2 b.ResetTimer() for i := 0; i < b.N; i++ { - lhs := Immediate(randomFeltElement(rand)) - rhs := Immediate(randomFeltElement(rand)) + lhs := hinter.Immediate(utils.RandomFeltElement(rand)) + rhs := hinter.Immediate(utils.RandomFeltElement(rand)) hint := DivMod{ lhs: lhs, rhs: rhs, @@ -158,24 +160,24 @@ func BenchmarkUintDivMod(b *testing.B) { } func BenchmarkUint256DivMod(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() - var quotient0 ApCellRef = 1 - var quotient1 ApCellRef = 2 - var remainder0 ApCellRef = 3 - var remainder1 ApCellRef = 4 + var quotient0 hinter.ApCellRef = 1 + var quotient1 hinter.ApCellRef = 2 + var remainder0 hinter.ApCellRef = 3 + var remainder1 hinter.ApCellRef = 4 b.ResetTimer() for i := 0; i < b.N; i++ { - dividend0 := Immediate(randomFeltElement(rand)) - dividend1 := Immediate(randomFeltElement(rand)) - divisor0 := Immediate(randomFeltElement(rand)) - divisor1 := Immediate(randomFeltElement(rand)) + dividend0 := hinter.Immediate(utils.RandomFeltElement(rand)) + dividend1 := hinter.Immediate(utils.RandomFeltElement(rand)) + divisor0 := hinter.Immediate(utils.RandomFeltElement(rand)) + divisor1 := hinter.Immediate(utils.RandomFeltElement(rand)) hint := Uint256DivMod{ dividend0, @@ -197,20 +199,20 @@ func BenchmarkUint256DivMod(b *testing.B) { } func BenchmarkLinearSplit(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() - var x ApCellRef = 0 - var y ApCellRef = 1 + var x hinter.ApCellRef = 0 + var y hinter.ApCellRef = 1 b.ResetTimer() for i := 0; i < b.N; i++ { - value := Immediate(randomFeltElement(rand)) - scalar := Immediate(randomFeltElement(rand)) - maxX := Immediate(randomFeltElement(rand)) + value := hinter.Immediate(utils.RandomFeltElement(rand)) + scalar := hinter.Immediate(utils.RandomFeltElement(rand)) + maxX := hinter.Immediate(utils.RandomFeltElement(rand)) hint := LinearSplit{ value: value, scalar: scalar, @@ -229,27 +231,27 @@ func BenchmarkLinearSplit(b *testing.B) { } func BenchmarkUint512DivModByUint256(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() - var quotient0 ApCellRef = 1 - var quotient1 ApCellRef = 2 - var quotient2 ApCellRef = 3 - var quotient3 ApCellRef = 4 - var remainder0 ApCellRef = 5 - var remainder1 ApCellRef = 6 + var quotient0 hinter.ApCellRef = 1 + var quotient1 hinter.ApCellRef = 2 + var quotient2 hinter.ApCellRef = 3 + var quotient3 hinter.ApCellRef = 4 + var remainder0 hinter.ApCellRef = 5 + var remainder1 hinter.ApCellRef = 6 b.ResetTimer() for i := 0; i < b.N; i++ { - dividend0 := Immediate(randomFeltElement(rand)) - dividend1 := Immediate(randomFeltElement(rand)) - dividend2 := Immediate(randomFeltElement(rand)) - dividend3 := Immediate(randomFeltElement(rand)) - divisor0 := Immediate(randomFeltElement(rand)) - divisor1 := Immediate(randomFeltElement(rand)) + dividend0 := hinter.Immediate(utils.RandomFeltElement(rand)) + dividend1 := hinter.Immediate(utils.RandomFeltElement(rand)) + dividend2 := hinter.Immediate(utils.RandomFeltElement(rand)) + dividend3 := hinter.Immediate(utils.RandomFeltElement(rand)) + divisor0 := hinter.Immediate(utils.RandomFeltElement(rand)) + divisor1 := hinter.Immediate(utils.RandomFeltElement(rand)) hint := Uint512DivModByUint256{ dividend0, @@ -276,22 +278,22 @@ func BenchmarkUint512DivModByUint256(b *testing.B) { } func BenchmarkUint256SquareRoot(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() - var sqrt0 ApCellRef = 1 - var sqrt1 ApCellRef = 2 - var remainderLow ApCellRef = 3 - var remainderHigh ApCellRef = 4 - var sqrtMul2MinusRemainderGeU128 ApCellRef = 5 + var sqrt0 hinter.ApCellRef = 1 + var sqrt1 hinter.ApCellRef = 2 + var remainderLow hinter.ApCellRef = 3 + var remainderHigh hinter.ApCellRef = 4 + var sqrtMul2MinusRemainderGeU128 hinter.ApCellRef = 5 b.ResetTimer() for i := 0; i < b.N; i++ { - valueLow := Immediate(randomFeltElement(rand)) - valueHigh := Immediate(randomFeltElement(rand)) + valueLow := hinter.Immediate(utils.RandomFeltElement(rand)) + valueHigh := hinter.Immediate(utils.RandomFeltElement(rand)) hint := Uint256SquareRoot{ valueLow: valueLow, valueHigh: valueHigh, @@ -312,15 +314,15 @@ func BenchmarkUint256SquareRoot(b *testing.B) { } func BenchmarkAssertLeIsFirstArcExcluded(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - ctx := HintRunnerContext{ + ctx := hinter.HintRunnerContext{ ExcludedArc: 0, } - var skipExcludeAFlag ApCellRef = 1 + var skipExcludeAFlag hinter.ApCellRef = 1 b.ResetTimer() for i := 0; i < b.N; i++ { @@ -340,15 +342,15 @@ func BenchmarkAssertLeIsFirstArcExcluded(b *testing.B) { } func BenchmarkAssertLeIsSecondArcExcluded(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - ctx := HintRunnerContext{ + ctx := hinter.HintRunnerContext{ ExcludedArc: 0, } - var skipExcludeBMinusA ApCellRef = 1 + var skipExcludeBMinusA hinter.ApCellRef = 1 b.ResetTimer() for i := 0; i < b.N; i++ { @@ -368,10 +370,10 @@ func BenchmarkAssertLeIsSecondArcExcluded(b *testing.B) { } func BenchmarkAssertLeFindSmallArc(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() - rand := defaultRandGenerator() - ctx := HintRunnerContext{ + rand := utils.DefaultRandGenerator() + ctx := hinter.HintRunnerContext{ ExcludedArc: 0, } @@ -380,19 +382,19 @@ func BenchmarkAssertLeFindSmallArc(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { // store the range check ptr at current ap - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Ap, memory.MemoryValueFromMemoryAddress(&rangeCheckPtr), ) - r1 := randomFeltElement(rand) - r2 := randomFeltElement(rand) + r1 := utils.RandomFeltElement(rand) + r2 := utils.RandomFeltElement(rand) hint := AssertLeFindSmallArc{ - a: Immediate(r1), - b: Immediate(r2), - rangeCheckPtr: Deref{ApCellRef(0)}, + a: hinter.Immediate(r1), + b: hinter.Immediate(r2), + rangeCheckPtr: hinter.Deref{Deref: hinter.ApCellRef(0)}, } if err := hint.Execute(vm, &ctx); err != nil && @@ -407,14 +409,14 @@ func BenchmarkAssertLeFindSmallArc(b *testing.B) { } func BenchmarkRandomEcPoint(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() b.ResetTimer() for i := 0; i < b.N; i++ { hint := RandomEcPoint{ - x: ApCellRef(0), - y: ApCellRef(1), + x: hinter.ApCellRef(0), + y: hinter.ApCellRef(1), } err := hint.Execute(vm) @@ -428,16 +430,16 @@ func BenchmarkRandomEcPoint(b *testing.B) { } func BenchmarkFieldSqrt(b *testing.B) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() - rand := defaultRandGenerator() + rand := utils.DefaultRandGenerator() b.ResetTimer() for i := 0; i < b.N; i++ { hint := FieldSqrt{ - val: Immediate(randomFeltElement(rand)), - sqrt: ApCellRef(0), + val: hinter.Immediate(utils.RandomFeltElement(rand)), + sqrt: hinter.ApCellRef(0), } err := hint.Execute(vm) diff --git a/pkg/hintrunner/hint_test.go b/pkg/hintrunner/core/hint_test.go similarity index 65% rename from pkg/hintrunner/hint_test.go rename to pkg/hintrunner/core/hint_test.go index 58cde8bf2..469aad6a7 100644 --- a/pkg/hintrunner/hint_test.go +++ b/pkg/hintrunner/core/hint_test.go @@ -1,4 +1,4 @@ -package hintrunner +package core import ( "io" @@ -6,6 +6,8 @@ import ( "os" "testing" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/utils" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" "github.com/NethermindEth/cairo-vm-go/pkg/vm/builtins" mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" @@ -15,12 +17,12 @@ import ( ) func TestAllocSegment(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 3 vm.Context.Fp = 0 - var ap ApCellRef = 5 - var fp FpCellRef = 9 + var ap hinter.ApCellRef = 5 + var fp hinter.FpCellRef = 9 alloc1 := AllocSegment{ap} alloc2 := AllocSegment{fp} @@ -31,7 +33,7 @@ func TestAllocSegment(t *testing.T) { require.Equal( t, mem.MemoryValueFromSegmentAndOffset(2, 0), - readFrom(vm, VM.ExecutionSegment, vm.Context.Ap+5), + utils.ReadFrom(vm, VM.ExecutionSegment, vm.Context.Ap+5), ) err = alloc2.Execute(vm, nil) @@ -40,22 +42,22 @@ func TestAllocSegment(t *testing.T) { require.Equal( t, mem.MemoryValueFromSegmentAndOffset(3, 0), - readFrom(vm, VM.ExecutionSegment, vm.Context.Fp+9), + utils.ReadFrom(vm, VM.ExecutionSegment, vm.Context.Fp+9), ) } func TestTestLessThanTrue(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - writeTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(23)) + utils.WriteTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(23)) - var dst ApCellRef = 1 - var rhsRef FpCellRef = 0 - rhs := Deref{rhsRef} + var dst hinter.ApCellRef = 1 + var rhsRef hinter.FpCellRef = 0 + rhs := hinter.Deref{Deref: rhsRef} - lhs := Immediate(f.NewElement(13)) + lhs := hinter.Immediate(f.NewElement(13)) hint := TestLessThan{ dst: dst, @@ -68,7 +70,7 @@ func TestTestLessThanTrue(t *testing.T) { require.Equal( t, mem.MemoryValueFromInt(1), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), "Expected the hint to evaluate to True when lhs is less than rhs", ) } @@ -83,16 +85,16 @@ func TestTestLessThanFalse(t *testing.T) { for _, tc := range testCases { t.Run(tc.expectedMsg, func(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - writeTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(17)) + utils.WriteTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(17)) - var dst ApCellRef = 1 - var rhsRef FpCellRef = 0 - rhs := Deref{rhsRef} + var dst hinter.ApCellRef = 1 + var rhsRef hinter.FpCellRef = 0 + rhs := hinter.Deref{Deref: rhsRef} - lhs := Immediate(tc.lhsValue) + lhs := hinter.Immediate(tc.lhsValue) hint := TestLessThan{ dst: dst, lhs: lhs, @@ -104,7 +106,7 @@ func TestTestLessThanFalse(t *testing.T) { require.Equal( t, mem.EmptyMemoryValueAsFelt(), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), tc.expectedMsg, ) }) @@ -122,16 +124,16 @@ func TestTestLessThanOrEqTrue(t *testing.T) { for _, tc := range testCases { t.Run(tc.expectedMsg, func(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - writeTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(23)) + utils.WriteTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(23)) - var dst ApCellRef = 1 - var rhsRef FpCellRef = 0 - rhs := Deref{rhsRef} + var dst hinter.ApCellRef = 1 + var rhsRef hinter.FpCellRef = 0 + rhs := hinter.Deref{Deref: rhsRef} - lhs := Immediate(tc.lhsValue) + lhs := hinter.Immediate(tc.lhsValue) hint := TestLessThanOrEqual{ dst: dst, lhs: lhs, @@ -143,7 +145,7 @@ func TestTestLessThanOrEqTrue(t *testing.T) { require.Equal( t, mem.MemoryValueFromInt(1), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), tc.expectedMsg, ) }) @@ -151,16 +153,16 @@ func TestTestLessThanOrEqTrue(t *testing.T) { } func TestTestLessThanOrEqFalse(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - writeTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(17)) + utils.WriteTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromInt(17)) - var dst ApCellRef = 1 - var rhsRef FpCellRef = 0 - rhs := Deref{rhsRef} + var dst hinter.ApCellRef = 1 + var rhsRef hinter.FpCellRef = 0 + rhs := hinter.Deref{Deref: rhsRef} - lhs := Immediate(f.NewElement(32)) + lhs := hinter.Immediate(f.NewElement(32)) hint := TestLessThanOrEqual{ dst: dst, @@ -173,21 +175,21 @@ func TestTestLessThanOrEqFalse(t *testing.T) { require.Equal( t, mem.EmptyMemoryValueAsFelt(), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), "Expected the hint to evaluate to False when lhs is larger", ) } func TestLinearSplit(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - value := Immediate(f.NewElement(42*223344 + 14)) - scalar := Immediate(f.NewElement(42)) - maxX := Immediate(f.NewElement(9999999999)) - var x ApCellRef = 0 - var y ApCellRef = 1 + value := hinter.Immediate(f.NewElement(42*223344 + 14)) + scalar := hinter.Immediate(f.NewElement(42)) + maxX := hinter.Immediate(f.NewElement(9999999999)) + var x hinter.ApCellRef = 0 + var y hinter.ApCellRef = 1 hint := LinearSplit{ value: value, @@ -199,17 +201,17 @@ func TestLinearSplit(t *testing.T) { err := hint.Execute(vm, nil) require.NoError(t, err) - xx := readFrom(vm, VM.ExecutionSegment, 0) + xx := utils.ReadFrom(vm, VM.ExecutionSegment, 0) require.Equal(t, xx, mem.MemoryValueFromInt(223344)) - yy := readFrom(vm, VM.ExecutionSegment, 1) + yy := utils.ReadFrom(vm, VM.ExecutionSegment, 1) require.Equal(t, yy, mem.MemoryValueFromInt(14)) - vm = defaultVirtualMachine() + vm = VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 //Lower max_x - maxX = Immediate(f.NewElement(223343)) + maxX = hinter.Immediate(f.NewElement(223343)) hint = LinearSplit{ value: value, scalar: scalar, @@ -220,19 +222,19 @@ func TestLinearSplit(t *testing.T) { err = hint.Execute(vm, nil) require.NoError(t, err) - xx = readFrom(vm, VM.ExecutionSegment, 0) + xx = utils.ReadFrom(vm, VM.ExecutionSegment, 0) require.Equal(t, xx, mem.MemoryValueFromInt(223343)) - yy = readFrom(vm, VM.ExecutionSegment, 1) + yy = utils.ReadFrom(vm, VM.ExecutionSegment, 1) require.Equal(t, yy, mem.MemoryValueFromInt(14+42)) } func TestWideMul128(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dstLow ApCellRef = 1 - var dstHigh ApCellRef = 2 + var dstLow hinter.ApCellRef = 1 + var dstHigh hinter.ApCellRef = 2 lhsBytes := new(uint256.Int).Lsh(uint256.NewInt(1), 127).Bytes32() lhsFelt, err := f.BigEndian.Element(&lhsBytes) @@ -240,8 +242,8 @@ func TestWideMul128(t *testing.T) { rhsFelt := f.NewElement(1<<8 + 1) - lhs := Immediate(lhsFelt) - rhs := Immediate(rhsFelt) + lhs := hinter.Immediate(lhsFelt) + rhs := hinter.Immediate(rhsFelt) hint := WideMul128{ low: dstLow, @@ -259,25 +261,25 @@ func TestWideMul128(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(low), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), ) require.Equal( t, mem.MemoryValueFromInt(1<<7), - readFrom(vm, VM.ExecutionSegment, 2), + utils.ReadFrom(vm, VM.ExecutionSegment, 2), ) } func TestDivMod(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var quo ApCellRef = 1 - var rem ApCellRef = 2 + var quo hinter.ApCellRef = 1 + var rem hinter.ApCellRef = 2 - lhsValue := Immediate(f.NewElement(89)) - rhsValue := Immediate(f.NewElement(7)) + lhsValue := hinter.Immediate(f.NewElement(89)) + rhsValue := hinter.Immediate(f.NewElement(7)) hint := DivMod{ lhs: lhsValue, @@ -292,23 +294,23 @@ func TestDivMod(t *testing.T) { expectedQuotient := mem.MemoryValueFromInt(12) expectedRemainder := mem.MemoryValueFromInt(5) - actualQuotient := readFrom(vm, VM.ExecutionSegment, 1) - actualRemainder := readFrom(vm, VM.ExecutionSegment, 2) + actualQuotient := utils.ReadFrom(vm, VM.ExecutionSegment, 1) + actualRemainder := utils.ReadFrom(vm, VM.ExecutionSegment, 2) require.Equal(t, expectedQuotient, actualQuotient) require.Equal(t, expectedRemainder, actualRemainder) } func TestDivModDivisionByZeroError(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var quo ApCellRef = 1 - var rem ApCellRef = 2 + var quo hinter.ApCellRef = 1 + var rem hinter.ApCellRef = 2 - lhsValue := Immediate(f.NewElement(43)) - rhsValue := Immediate(f.NewElement(0)) + lhsValue := hinter.Immediate(f.NewElement(43)) + rhsValue := hinter.Immediate(f.NewElement(0)) hint := DivMod{ lhs: lhsValue, @@ -323,14 +325,14 @@ func TestDivModDivisionByZeroError(t *testing.T) { func TestUint256DivMod(t *testing.T) { t.Run("test uint256DivMod", func(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var quotient0 ApCellRef = 1 - var quotient1 ApCellRef = 2 - var remainder0 ApCellRef = 3 - var remainder1 ApCellRef = 4 + var quotient0 hinter.ApCellRef = 1 + var quotient1 hinter.ApCellRef = 2 + var remainder0 hinter.ApCellRef = 3 + var remainder1 hinter.ApCellRef = 4 dividend0Felt := f.NewElement(89) dividend1Felt := f.NewElement(72) @@ -339,10 +341,10 @@ func TestUint256DivMod(t *testing.T) { divisor1Felt := f.NewElement(7) hint := Uint256DivMod{ - dividend0: Immediate(dividend0Felt), - dividend1: Immediate(dividend1Felt), - divisor0: Immediate(divisor0Felt), - divisor1: Immediate(divisor1Felt), + dividend0: hinter.Immediate(dividend0Felt), + dividend1: hinter.Immediate(dividend1Felt), + divisor0: hinter.Immediate(divisor0Felt), + divisor1: hinter.Immediate(divisor1Felt), quotient0: quotient0, quotient1: quotient1, remainder0: remainder0, @@ -359,7 +361,7 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient0Val), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), ) quotient1Val := &f.Element{} @@ -369,7 +371,7 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient1Val), - readFrom(vm, VM.ExecutionSegment, 2), + utils.ReadFrom(vm, VM.ExecutionSegment, 2), ) remainder0Val := &f.Element{} @@ -379,7 +381,7 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(remainder0Val), - readFrom(vm, VM.ExecutionSegment, 3), + utils.ReadFrom(vm, VM.ExecutionSegment, 3), ) remainder1Val := &f.Element{} @@ -389,18 +391,18 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(remainder1Val), - readFrom(vm, VM.ExecutionSegment, 4), + utils.ReadFrom(vm, VM.ExecutionSegment, 4), ) }) t.Run("test uint256DivMod with 256-bit numbers;", func(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var quotient0 ApCellRef = 1 - var quotient1 ApCellRef = 2 - var remainder0 ApCellRef = 3 - var remainder1 ApCellRef = 4 + var quotient0 hinter.ApCellRef = 1 + var quotient1 hinter.ApCellRef = 2 + var remainder0 hinter.ApCellRef = 3 + var remainder1 hinter.ApCellRef = 4 b := new(uint256.Int).Lsh(uint256.NewInt(1), 127).Bytes32() @@ -412,10 +414,10 @@ func TestUint256DivMod(t *testing.T) { divisor1Felt := f.NewElement(1<<8 + 1) hint := Uint256DivMod{ - dividend0: Immediate(dividend0Felt), - dividend1: Immediate(dividend1Felt), - divisor0: Immediate(divisor0Felt), - divisor1: Immediate(divisor1Felt), + dividend0: hinter.Immediate(dividend0Felt), + dividend1: hinter.Immediate(dividend1Felt), + divisor0: hinter.Immediate(divisor0Felt), + divisor1: hinter.Immediate(divisor1Felt), quotient0: quotient0, quotient1: quotient1, remainder0: remainder0, @@ -432,7 +434,7 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient0Val), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), ) quotient1Val := &f.Element{} @@ -442,7 +444,7 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient1Val), - readFrom(vm, VM.ExecutionSegment, 2), + utils.ReadFrom(vm, VM.ExecutionSegment, 2), ) remainder0Val := &f.Element{} @@ -452,7 +454,7 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(remainder0Val), - readFrom(vm, VM.ExecutionSegment, 3), + utils.ReadFrom(vm, VM.ExecutionSegment, 3), ) remainder1Val := &f.Element{} @@ -462,20 +464,20 @@ func TestUint256DivMod(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(remainder1Val), - readFrom(vm, VM.ExecutionSegment, 4), + utils.ReadFrom(vm, VM.ExecutionSegment, 4), ) }) } func TestUint256DivModDivisionByZero(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dstQuotient0 ApCellRef = 1 - var dstQuotient1 ApCellRef = 2 - var dstRemainder0 ApCellRef = 3 - var dstRemainder1 ApCellRef = 4 + var dstQuotient0 hinter.ApCellRef = 1 + var dstQuotient1 hinter.ApCellRef = 2 + var dstRemainder0 hinter.ApCellRef = 3 + var dstRemainder1 hinter.ApCellRef = 4 dividend0Felt := f.NewElement(1<<8 + 1) dividend1Felt := f.NewElement(1<<8 + 1) @@ -484,10 +486,10 @@ func TestUint256DivModDivisionByZero(t *testing.T) { divisor1Felt := f.NewElement(0) hint := Uint256DivMod{ - dividend0: Immediate(dividend0Felt), - dividend1: Immediate(dividend1Felt), - divisor0: Immediate(divisor0Felt), - divisor1: Immediate(divisor1Felt), + dividend0: hinter.Immediate(dividend0Felt), + dividend1: hinter.Immediate(dividend1Felt), + divisor0: hinter.Immediate(divisor0Felt), + divisor1: hinter.Immediate(divisor1Felt), quotient0: dstQuotient0, quotient1: dstQuotient1, remainder0: dstRemainder0, @@ -499,19 +501,19 @@ func TestUint256DivModDivisionByZero(t *testing.T) { } func TestWideMul128IncorrectRange(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dstLow ApCellRef = 1 - var dstHigh ApCellRef = 2 + var dstLow hinter.ApCellRef = 1 + var dstHigh hinter.ApCellRef = 2 lhsBytes := new(uint256.Int).Lsh(uint256.NewInt(1), 128).Bytes32() lhsFelt, err := f.BigEndian.Element(&lhsBytes) require.NoError(t, err) - lhs := Immediate(lhsFelt) - rhs := Immediate(f.NewElement(1)) + lhs := hinter.Immediate(lhsFelt) + rhs := hinter.Immediate(f.NewElement(1)) hint := WideMul128{ low: dstLow, @@ -530,20 +532,20 @@ func TestDebugPrint(t *testing.T) { r, w, _ := os.Pipe() os.Stdout = w - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - writeTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromSegmentAndOffset(VM.ExecutionSegment, 2)) - writeTo(vm, VM.ExecutionSegment, 1, mem.MemoryValueFromSegmentAndOffset(VM.ExecutionSegment, 5)) - writeTo(vm, VM.ExecutionSegment, 2, mem.MemoryValueFromInt(10)) - writeTo(vm, VM.ExecutionSegment, 3, mem.MemoryValueFromInt(20)) - writeTo(vm, VM.ExecutionSegment, 4, mem.MemoryValueFromInt(30)) + utils.WriteTo(vm, VM.ExecutionSegment, 0, mem.MemoryValueFromSegmentAndOffset(VM.ExecutionSegment, 2)) + utils.WriteTo(vm, VM.ExecutionSegment, 1, mem.MemoryValueFromSegmentAndOffset(VM.ExecutionSegment, 5)) + utils.WriteTo(vm, VM.ExecutionSegment, 2, mem.MemoryValueFromInt(10)) + utils.WriteTo(vm, VM.ExecutionSegment, 3, mem.MemoryValueFromInt(20)) + utils.WriteTo(vm, VM.ExecutionSegment, 4, mem.MemoryValueFromInt(30)) - var starRef ApCellRef = 0 - var endRef ApCellRef = 1 - start := Deref{starRef} - end := Deref{endRef} + var starRef hinter.ApCellRef = 0 + var endRef hinter.ApCellRef = 1 + start := hinter.Deref{Deref: starRef} + end := hinter.Deref{Deref: endRef} hint := DebugPrint{ start: start, end: end, @@ -561,12 +563,12 @@ func TestDebugPrint(t *testing.T) { } func TestSquareRoot(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dst ApCellRef = 1 + var dst hinter.ApCellRef = 1 - value := Immediate(f.NewElement(36)) + value := hinter.Immediate(f.NewElement(36)) hint := SquareRoot{ value: value, dst: dst, @@ -578,11 +580,11 @@ func TestSquareRoot(t *testing.T) { require.Equal( t, mem.MemoryValueFromInt(6), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), ) dst = 2 - value = Immediate(f.NewElement(30)) + value = hinter.Immediate(f.NewElement(30)) hint = SquareRoot{ value: value, dst: dst, @@ -594,23 +596,23 @@ func TestSquareRoot(t *testing.T) { require.Equal( t, mem.MemoryValueFromInt(5), - readFrom(vm, VM.ExecutionSegment, 2), + utils.ReadFrom(vm, VM.ExecutionSegment, 2), ) } func TestUint256SquareRootLow(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var sqrt0 ApCellRef = 1 - var sqrt1 ApCellRef = 2 - var remainderLow ApCellRef = 3 - var remainderHigh ApCellRef = 4 - var sqrtMul2MinusRemainderGeU128 ApCellRef = 5 + var sqrt0 hinter.ApCellRef = 1 + var sqrt1 hinter.ApCellRef = 2 + var remainderLow hinter.ApCellRef = 3 + var remainderHigh hinter.ApCellRef = 4 + var sqrtMul2MinusRemainderGeU128 hinter.ApCellRef = 5 - valueLow := Immediate(f.NewElement(121)) - valueHigh := Immediate(f.NewElement(0)) + valueLow := hinter.Immediate(f.NewElement(121)) + valueHigh := hinter.Immediate(f.NewElement(0)) hint := Uint256SquareRoot{ valueLow: valueLow, @@ -632,11 +634,11 @@ func TestUint256SquareRootLow(t *testing.T) { expectedRemainderHigh := mem.MemoryValueFromInt(0) expectedSqrtMul2MinusRemainderGeU128 := mem.MemoryValueFromInt(0) - actualSqrt0 := readFrom(vm, VM.ExecutionSegment, 1) - actualSqrt1 := readFrom(vm, VM.ExecutionSegment, 2) - actualRemainderLow := readFrom(vm, VM.ExecutionSegment, 3) - actualRemainderHigh := readFrom(vm, VM.ExecutionSegment, 4) - actualSqrtMul2MinusRemainderGeU128 := readFrom(vm, VM.ExecutionSegment, 5) + actualSqrt0 := utils.ReadFrom(vm, VM.ExecutionSegment, 1) + actualSqrt1 := utils.ReadFrom(vm, VM.ExecutionSegment, 2) + actualRemainderLow := utils.ReadFrom(vm, VM.ExecutionSegment, 3) + actualRemainderHigh := utils.ReadFrom(vm, VM.ExecutionSegment, 4) + actualSqrtMul2MinusRemainderGeU128 := utils.ReadFrom(vm, VM.ExecutionSegment, 5) require.Equal(t, expectedSqrt0, actualSqrt0) require.Equal(t, expectedSqrt1, actualSqrt1) @@ -646,18 +648,18 @@ func TestUint256SquareRootLow(t *testing.T) { } func TestUint256SquareRootHigh(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var sqrt0 ApCellRef = 1 - var sqrt1 ApCellRef = 2 - var remainderLow ApCellRef = 3 - var remainderHigh ApCellRef = 4 - var sqrtMul2MinusRemainderGeU128 ApCellRef = 5 + var sqrt0 hinter.ApCellRef = 1 + var sqrt1 hinter.ApCellRef = 2 + var remainderLow hinter.ApCellRef = 3 + var remainderHigh hinter.ApCellRef = 4 + var sqrtMul2MinusRemainderGeU128 hinter.ApCellRef = 5 - valueLow := Immediate(f.NewElement(0)) - valueHigh := Immediate(f.NewElement(1 << 8)) + valueLow := hinter.Immediate(f.NewElement(0)) + valueHigh := hinter.Immediate(f.NewElement(1 << 8)) hint := Uint256SquareRoot{ valueLow: valueLow, @@ -679,11 +681,11 @@ func TestUint256SquareRootHigh(t *testing.T) { expectedRemainderHigh := mem.MemoryValueFromInt(0) expectedSqrtMul2MinusRemainderGeU128 := mem.MemoryValueFromInt(0) - actualSqrt0 := readFrom(vm, VM.ExecutionSegment, 1) - actualSqrt1 := readFrom(vm, VM.ExecutionSegment, 2) - actualRemainderLow := readFrom(vm, VM.ExecutionSegment, 3) - actualRemainderHigh := readFrom(vm, VM.ExecutionSegment, 4) - actualSqrtMul2MinusRemainderGeU128 := readFrom(vm, VM.ExecutionSegment, 5) + actualSqrt0 := utils.ReadFrom(vm, VM.ExecutionSegment, 1) + actualSqrt1 := utils.ReadFrom(vm, VM.ExecutionSegment, 2) + actualRemainderLow := utils.ReadFrom(vm, VM.ExecutionSegment, 3) + actualRemainderHigh := utils.ReadFrom(vm, VM.ExecutionSegment, 4) + actualSqrtMul2MinusRemainderGeU128 := utils.ReadFrom(vm, VM.ExecutionSegment, 5) require.Equal(t, expectedSqrt0, actualSqrt0) require.Equal(t, expectedSqrt1, actualSqrt1) @@ -693,18 +695,18 @@ func TestUint256SquareRootHigh(t *testing.T) { } func TestUint256SquareRoot(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var sqrt0 ApCellRef = 1 - var sqrt1 ApCellRef = 2 - var remainderLow ApCellRef = 3 - var remainderHigh ApCellRef = 4 - var sqrtMul2MinusRemainderGeU128 ApCellRef = 5 + var sqrt0 hinter.ApCellRef = 1 + var sqrt1 hinter.ApCellRef = 2 + var remainderLow hinter.ApCellRef = 3 + var remainderHigh hinter.ApCellRef = 4 + var sqrtMul2MinusRemainderGeU128 hinter.ApCellRef = 5 - valueLow := Immediate(f.NewElement(51)) - valueHigh := Immediate(f.NewElement(1024)) + valueLow := hinter.Immediate(f.NewElement(51)) + valueHigh := hinter.Immediate(f.NewElement(1024)) hint := Uint256SquareRoot{ valueLow: valueLow, @@ -726,11 +728,11 @@ func TestUint256SquareRoot(t *testing.T) { expectedRemainderHigh := mem.MemoryValueFromInt(0) expectedSqrtMul2MinusRemainderGeU128 := mem.MemoryValueFromInt(0) - actualSqrt0 := readFrom(vm, VM.ExecutionSegment, 1) - actualSqrt1 := readFrom(vm, VM.ExecutionSegment, 2) - actualRemainderLow := readFrom(vm, VM.ExecutionSegment, 3) - actualRemainderHigh := readFrom(vm, VM.ExecutionSegment, 4) - actualSqrtMul2MinusRemainderGeU128 := readFrom(vm, VM.ExecutionSegment, 5) + actualSqrt0 := utils.ReadFrom(vm, VM.ExecutionSegment, 1) + actualSqrt1 := utils.ReadFrom(vm, VM.ExecutionSegment, 2) + actualRemainderLow := utils.ReadFrom(vm, VM.ExecutionSegment, 3) + actualRemainderHigh := utils.ReadFrom(vm, VM.ExecutionSegment, 4) + actualSqrtMul2MinusRemainderGeU128 := utils.ReadFrom(vm, VM.ExecutionSegment, 5) require.Equal(t, expectedSqrt0, actualSqrt0) require.Equal(t, expectedSqrt1, actualSqrt1) @@ -740,16 +742,16 @@ func TestUint256SquareRoot(t *testing.T) { } func TestUint512DivModByUint256(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dstQuotient0 ApCellRef = 1 - var dstQuotient1 ApCellRef = 2 - var dstQuotient2 ApCellRef = 3 - var dstQuotient3 ApCellRef = 4 - var dstRemainder0 ApCellRef = 5 - var dstRemainder1 ApCellRef = 6 + var dstQuotient0 hinter.ApCellRef = 1 + var dstQuotient1 hinter.ApCellRef = 2 + var dstQuotient2 hinter.ApCellRef = 3 + var dstQuotient3 hinter.ApCellRef = 4 + var dstRemainder0 hinter.ApCellRef = 5 + var dstRemainder1 hinter.ApCellRef = 6 b := new(uint256.Int).Lsh(uint256.NewInt(1), 127).Bytes32() @@ -764,12 +766,12 @@ func TestUint512DivModByUint256(t *testing.T) { divisor1Felt := f.NewElement(1<<8 + 1) hint := Uint512DivModByUint256{ - dividend0: Immediate(dividend0Felt), - dividend1: Immediate(dividend1Felt), - dividend2: Immediate(dividend2Felt), - dividend3: Immediate(dividend3Felt), - divisor0: Immediate(divisor0Felt), - divisor1: Immediate(divisor1Felt), + dividend0: hinter.Immediate(dividend0Felt), + dividend1: hinter.Immediate(dividend1Felt), + dividend2: hinter.Immediate(dividend2Felt), + dividend3: hinter.Immediate(dividend3Felt), + divisor0: hinter.Immediate(divisor0Felt), + divisor1: hinter.Immediate(divisor1Felt), quotient0: dstQuotient0, quotient1: dstQuotient1, quotient2: dstQuotient2, @@ -788,7 +790,7 @@ func TestUint512DivModByUint256(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient0), - readFrom(vm, VM.ExecutionSegment, 1), + utils.ReadFrom(vm, VM.ExecutionSegment, 1), ) quotient1 := &f.Element{} @@ -798,7 +800,7 @@ func TestUint512DivModByUint256(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient1), - readFrom(vm, VM.ExecutionSegment, 2), + utils.ReadFrom(vm, VM.ExecutionSegment, 2), ) quotient2 := &f.Element{} @@ -807,7 +809,7 @@ func TestUint512DivModByUint256(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient2), - readFrom(vm, VM.ExecutionSegment, 3), + utils.ReadFrom(vm, VM.ExecutionSegment, 3), ) quotient3 := &f.Element{} @@ -816,7 +818,7 @@ func TestUint512DivModByUint256(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(quotient3), - readFrom(vm, VM.ExecutionSegment, 4), + utils.ReadFrom(vm, VM.ExecutionSegment, 4), ) remainder0 := &f.Element{} @@ -826,7 +828,7 @@ func TestUint512DivModByUint256(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(remainder0), - readFrom(vm, VM.ExecutionSegment, 5), + utils.ReadFrom(vm, VM.ExecutionSegment, 5), ) remainder1 := &f.Element{} @@ -835,21 +837,21 @@ func TestUint512DivModByUint256(t *testing.T) { require.Equal( t, mem.MemoryValueFromFieldElement(remainder1), - readFrom(vm, VM.ExecutionSegment, 6), + utils.ReadFrom(vm, VM.ExecutionSegment, 6), ) } func TestUint512DivModByUint256DivisionByZero(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - var dstQuotient0 ApCellRef = 1 - var dstQuotient1 ApCellRef = 2 - var dstQuotient2 ApCellRef = 3 - var dstQuotient3 ApCellRef = 4 - var dstRemainder0 ApCellRef = 5 - var dstRemainder1 ApCellRef = 6 + var dstQuotient0 hinter.ApCellRef = 1 + var dstQuotient1 hinter.ApCellRef = 2 + var dstQuotient2 hinter.ApCellRef = 3 + var dstQuotient3 hinter.ApCellRef = 4 + var dstRemainder0 hinter.ApCellRef = 5 + var dstRemainder1 hinter.ApCellRef = 6 b := new(uint256.Int).Lsh(uint256.NewInt(1), 127).Bytes32() @@ -864,12 +866,12 @@ func TestUint512DivModByUint256DivisionByZero(t *testing.T) { divisor1Felt := f.NewElement(0) hint := Uint512DivModByUint256{ - dividend0: Immediate(dividend0Felt), - dividend1: Immediate(dividend1Felt), - dividend2: Immediate(dividend2Felt), - dividend3: Immediate(dividend3Felt), - divisor0: Immediate(divisor0Felt), - divisor1: Immediate(divisor1Felt), + dividend0: hinter.Immediate(dividend0Felt), + dividend1: hinter.Immediate(dividend1Felt), + dividend2: hinter.Immediate(dividend2Felt), + dividend3: hinter.Immediate(dividend3Felt), + divisor0: hinter.Immediate(divisor0Felt), + divisor1: hinter.Immediate(divisor1Felt), quotient0: dstQuotient0, quotient1: dstQuotient1, quotient2: dstQuotient2, @@ -883,12 +885,12 @@ func TestUint512DivModByUint256DivisionByZero(t *testing.T) { } func TestAllocConstantSize(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() - sizes := [3]Immediate{ - Immediate(f.NewElement(15)), - Immediate(f.NewElement(13)), - Immediate(f.NewElement(2)), + sizes := [3]hinter.Immediate{ + hinter.Immediate(f.NewElement(15)), + hinter.Immediate(f.NewElement(13)), + hinter.Immediate(f.NewElement(2)), } expectedAddrs := [3]mem.MemoryAddress{ {SegmentIndex: 2, Offset: 0}, @@ -896,20 +898,20 @@ func TestAllocConstantSize(t *testing.T) { {SegmentIndex: 2, Offset: 28}, } - ctx := HintRunnerContext{ + ctx := hinter.HintRunnerContext{ ConstantSizeSegment: mem.UnknownAddress, } for i := 0; i < len(sizes); i++ { hint := AllocConstantSize{ - Dst: ApCellRef(i), + Dst: hinter.ApCellRef(i), Size: sizes[i], } err := hint.Execute(vm, &ctx) require.NoError(t, err) - val := readFrom(vm, 1, uint64(i)) + val := utils.ReadFrom(vm, 1, uint64(i)) ptr, err := val.MemoryAddress() require.NoError(t, err) @@ -977,20 +979,20 @@ func TestAssertLeFindSmallArc(t *testing.T) { for _, tc := range testCases { // Need to create a new VM for each test case // to avoid rewriting in same memory address error - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 // The addr that the range check pointer will point to addr := vm.Memory.AllocateBuiltinSegment(&builtins.RangeCheck{}) - writeTo(vm, VM.ExecutionSegment, vm.Context.Ap, mem.MemoryValueFromMemoryAddress(&addr)) + utils.WriteTo(vm, VM.ExecutionSegment, vm.Context.Ap, mem.MemoryValueFromMemoryAddress(&addr)) hint := AssertLeFindSmallArc{ - a: Immediate(tc.aFelt), - b: Immediate(tc.bFelt), - rangeCheckPtr: Deref{ApCellRef(0)}, + a: hinter.Immediate(tc.aFelt), + b: hinter.Immediate(tc.bFelt), + rangeCheckPtr: hinter.Deref{Deref: hinter.ApCellRef(0)}, } - ctx := HintRunnerContext{ + ctx := hinter.HintRunnerContext{ ExcludedArc: 0, } @@ -1000,11 +1002,11 @@ func TestAssertLeFindSmallArc(t *testing.T) { expectedPtr := mem.MemoryValueFromMemoryAddress(&addr) - actualRem1 := readFrom(vm, 2, 0) - actualQuotient1 := readFrom(vm, 2, 1) - actualRem2 := readFrom(vm, 2, 2) - actualQuotient2 := readFrom(vm, 2, 3) - actual1Ptr := readFrom(vm, 1, 0) + actualRem1 := utils.ReadFrom(vm, 2, 0) + actualQuotient1 := utils.ReadFrom(vm, 2, 1) + actualRem2 := utils.ReadFrom(vm, 2, 2) + actualQuotient2 := utils.ReadFrom(vm, 2, 3) + actual1Ptr := utils.ReadFrom(vm, 1, 0) require.Equal(t, tc.expectedRem1, actualRem1) require.Equal(t, tc.expectedQuotient1, actualQuotient1) @@ -1016,13 +1018,13 @@ func TestAssertLeFindSmallArc(t *testing.T) { } func TestAssertLeIsFirstArcExcluded(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() - ctx := HintRunnerContext{ + ctx := hinter.HintRunnerContext{ ExcludedArc: 2, } - var flag ApCellRef = 0 + var flag hinter.ApCellRef = 0 hint := AssertLeIsFirstArcExcluded{ skipExcludeAFlag: flag, @@ -1034,21 +1036,21 @@ func TestAssertLeIsFirstArcExcluded(t *testing.T) { expected := mem.MemoryValueFromInt(1) - actual := readFrom(vm, VM.ExecutionSegment, 0) + actual := utils.ReadFrom(vm, VM.ExecutionSegment, 0) require.Equal(t, expected, actual) } func TestAssertLeIsSecondArcExcluded(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - ctx := HintRunnerContext{ + ctx := hinter.HintRunnerContext{ ExcludedArc: 1, } - var flag ApCellRef = 0 + var flag hinter.ApCellRef = 0 hint := AssertLeIsSecondArcExcluded{ skipExcludeBMinusA: flag, @@ -1060,19 +1062,19 @@ func TestAssertLeIsSecondArcExcluded(t *testing.T) { expected := mem.MemoryValueFromInt(0) - actual := readFrom(vm, VM.ExecutionSegment, 0) + actual := utils.ReadFrom(vm, VM.ExecutionSegment, 0) require.Equal(t, expected, actual) } func TestRandomEcPoint(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 hint := RandomEcPoint{ - x: ApCellRef(0), - y: ApCellRef(1), + x: hinter.ApCellRef(0), + y: hinter.ApCellRef(1), } err := hint.Execute(vm) @@ -1086,8 +1088,8 @@ func TestRandomEcPoint(t *testing.T) { &f.Element{12193331470568888984, 1737428559173019240, 11500517745011090163, 245183001587853482}, ) - actualX := readFrom(vm, VM.ExecutionSegment, 0) - actualY := readFrom(vm, VM.ExecutionSegment, 1) + actualX := utils.ReadFrom(vm, VM.ExecutionSegment, 0) + actualY := utils.ReadFrom(vm, VM.ExecutionSegment, 1) require.Equal(t, expectedX, actualX) require.Equal(t, expectedY, actualY) @@ -1113,14 +1115,14 @@ func TestFieldSqrt(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 0 vm.Context.Fp = 0 - value := Immediate(f.NewElement(tc.value)) + value := hinter.Immediate(f.NewElement(tc.value)) hint := FieldSqrt{ val: value, - sqrt: ApCellRef(0), + sqrt: hinter.ApCellRef(0), } err := hint.Execute(vm) @@ -1129,7 +1131,7 @@ func TestFieldSqrt(t *testing.T) { require.Equal( t, mem.MemoryValueFromInt(tc.expected), - readFrom(vm, VM.ExecutionSegment, 0), + utils.ReadFrom(vm, VM.ExecutionSegment, 0), ) }) } diff --git a/pkg/hintrunner/hinter/hinter.go b/pkg/hintrunner/hinter/hinter.go new file mode 100644 index 000000000..568c50ee5 --- /dev/null +++ b/pkg/hintrunner/hinter/hinter.go @@ -0,0 +1,197 @@ +package hinter + +import ( + "fmt" + + VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" + mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" + f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" +) + +type Hinter interface { + fmt.Stringer + + Execute(vm *VM.VirtualMachine, ctx *HintRunnerContext) error +} + +// Used to keep track of all dictionaries data +type Dictionary struct { + // The data contained on a dictionary + data map[f.Element]*mem.MemoryValue + // Unique id assigned at the moment of creation + idx uint64 +} + +// Gets the memory value at certain key +func (d *Dictionary) At(key *f.Element) (*mem.MemoryValue, error) { + if value, ok := d.data[*key]; ok { + return value, nil + } + return nil, fmt.Errorf("no value for key %s", key) +} + +// Given a key and a value, it sets the value at the given key +func (d *Dictionary) Set(key *f.Element, value *mem.MemoryValue) { + d.data[*key] = value +} + +// Returns the initialization number when the dictionary was created +func (d *Dictionary) InitNumber() uint64 { + return d.idx +} + +// Used to manage dictionaries creation +type DictionaryManager struct { + // a map that links a segment index to a dictionary + dictionaries map[uint64]Dictionary +} + +func InitializeDictionaryManager(ctx *HintRunnerContext) { + if ctx.DictionaryManager.dictionaries == nil { + ctx.DictionaryManager.dictionaries = make(map[uint64]Dictionary) + } +} + +// It creates a new segment which will hold dictionary values. It links this +// segment with the current dictionary and returns the address that points +// to the start of this segment +func (dm *DictionaryManager) NewDictionary(vm *VM.VirtualMachine) mem.MemoryAddress { + newDictAddr := vm.Memory.AllocateEmptySegment() + dm.dictionaries[newDictAddr.SegmentIndex] = Dictionary{ + data: make(map[f.Element]*mem.MemoryValue), + idx: uint64(len(dm.dictionaries)), + } + return newDictAddr +} + +// Given a memory address, it looks for the right dictionary using the segment index. If no +// segment is associated with the given segment index, it errors +func (dm *DictionaryManager) GetDictionary(dictAddr *mem.MemoryAddress) (Dictionary, error) { + dict, ok := dm.dictionaries[dictAddr.SegmentIndex] + if ok { + return dict, nil + } + return Dictionary{}, fmt.Errorf("no dictionary at address %s", dictAddr) +} + +// Given a memory address and a key it returns the value held at that position. The address is used +// to locate the correct dictionary and the key to index on it +func (dm *DictionaryManager) At(dictAddr *mem.MemoryAddress, key *f.Element) (*mem.MemoryValue, error) { + if dict, ok := dm.dictionaries[dictAddr.SegmentIndex]; ok { + return dict.At(key) + } + return nil, fmt.Errorf("no dictionary at address %s", dictAddr) +} + +// Given a memory address,a key and a value it stores the value at the correct position. +func (dm *DictionaryManager) Set(dictAddr *mem.MemoryAddress, key *f.Element, value *mem.MemoryValue) error { + if dict, ok := dm.dictionaries[dictAddr.SegmentIndex]; ok { + dict.Set(key, value) + return nil + } + return fmt.Errorf("no dictionary at address %s", dictAddr) +} + +// Used to keep track of squashed dictionaries +type SquashedDictionaryManager struct { + // A map from each key to a list of indices where the key is present + // the list in reversed order. + // Note: The indices should be Felts, but current memory limitations + // make it impossible to use an index that big so we use uint64 instead + KeyToIndices map[f.Element][]uint64 + + // A descending list of keys + Keys []f.Element +} + +func InitializeSquashedDictionaryManager(ctx *HintRunnerContext) error { + if ctx.SquashedDictionaryManager.KeyToIndices != nil || + ctx.SquashedDictionaryManager.Keys != nil { + return fmt.Errorf("squashed dictionary manager already initialized") + } + ctx.SquashedDictionaryManager.KeyToIndices = make(map[f.Element][]uint64, 100) + ctx.SquashedDictionaryManager.Keys = make([]f.Element, 0, 100) + return nil +} + +// It adds another index to the list of indices associated to the given key +// If the key is not present, it creates a new entry +func (sdm *SquashedDictionaryManager) Insert(key *f.Element, index uint64) { + keyIndex := *key + if indices, ok := sdm.KeyToIndices[keyIndex]; ok { + sdm.KeyToIndices[keyIndex] = append(indices, index) + } else { + sdm.KeyToIndices[keyIndex] = []uint64{index} + } +} + +// It returns the smallest key in the key list +func (sdm *SquashedDictionaryManager) LastKey() (f.Element, error) { + if len(sdm.Keys) == 0 { + return f.Element{}, fmt.Errorf("no keys left") + } + return sdm.Keys[len(sdm.Keys)-1], nil +} + +// It pops out the smallest key in the key list +func (sdm *SquashedDictionaryManager) PopKey() (f.Element, error) { + key, err := sdm.LastKey() + if err != nil { + return key, err + } + + sdm.Keys = sdm.Keys[:len(sdm.Keys)-1] + return key, nil +} + +// It returns the list of indices associated to the smallest key +func (sdm *SquashedDictionaryManager) LastIndices() ([]uint64, error) { + key, err := sdm.LastKey() + if err != nil { + return nil, err + } + + return sdm.KeyToIndices[key], nil +} + +// It returns smallest index associated with the smallest key +func (sdm *SquashedDictionaryManager) LastIndex() (uint64, error) { + key, err := sdm.LastKey() + if err != nil { + return 0, err + } + + indices := sdm.KeyToIndices[key] + if len(indices) == 0 { + return 0, fmt.Errorf("no indices for key %s", &key) + } + + return indices[len(indices)-1], nil +} + +// It pops out smallest index associated with the smallest key +func (sdm *SquashedDictionaryManager) PopIndex() (uint64, error) { + key, err := sdm.LastKey() + if err != nil { + return 0, err + } + + indices := sdm.KeyToIndices[key] + if len(indices) == 0 { + return 0, fmt.Errorf("no indices for key %s", &key) + } + + index := indices[len(indices)-1] + sdm.KeyToIndices[key] = indices[:len(indices)-1] + return index, nil +} + +// Global context to keep track of different results across different +// hints execution. +type HintRunnerContext struct { + DictionaryManager DictionaryManager + SquashedDictionaryManager SquashedDictionaryManager + ExcludedArc int + // points towards free memory of a segment + ConstantSizeSegment mem.MemoryAddress +} diff --git a/pkg/hintrunner/operand.go b/pkg/hintrunner/hinter/operand.go similarity index 90% rename from pkg/hintrunner/operand.go rename to pkg/hintrunner/hinter/operand.go index 42c997a52..517ce5555 100644 --- a/pkg/hintrunner/operand.go +++ b/pkg/hintrunner/hinter/operand.go @@ -1,4 +1,4 @@ -package hintrunner +package hinter import ( "fmt" @@ -56,7 +56,7 @@ type ResOperander interface { } type Deref struct { - deref CellRefer + Deref CellRefer } func (deref Deref) String() string { @@ -64,7 +64,7 @@ func (deref Deref) String() string { } func (deref Deref) Resolve(vm *VM.VirtualMachine) (mem.MemoryValue, error) { - address, err := deref.deref.Get(vm) + address, err := deref.Deref.Get(vm) if err != nil { return mem.MemoryValue{}, fmt.Errorf("get cell: %w", err) } @@ -72,8 +72,8 @@ func (deref Deref) Resolve(vm *VM.VirtualMachine) (mem.MemoryValue, error) { } type DoubleDeref struct { - deref CellRefer - offset int16 + Deref CellRefer + Offset int16 } func (dderef DoubleDeref) String() string { @@ -81,7 +81,7 @@ func (dderef DoubleDeref) String() string { } func (dderef DoubleDeref) Resolve(vm *VM.VirtualMachine) (mem.MemoryValue, error) { - lhsAddr, err := dderef.deref.Get(vm) + lhsAddr, err := dderef.Deref.Get(vm) if err != nil { return mem.UnknownValue, fmt.Errorf("get lhs address %s: %w", lhsAddr, err) } @@ -96,9 +96,9 @@ func (dderef DoubleDeref) Resolve(vm *VM.VirtualMachine) (mem.MemoryValue, error return mem.UnknownValue, err } - newOffset, overflow := utils.SafeOffset(address.Offset, dderef.offset) + newOffset, overflow := utils.SafeOffset(address.Offset, dderef.Offset) if overflow { - return mem.UnknownValue, fmt.Errorf("overflow %d + %d", address.Offset, dderef.offset) + return mem.UnknownValue, fmt.Errorf("overflow %d + %d", address.Offset, dderef.Offset) } resAddr := mem.MemoryAddress{ SegmentIndex: address.SegmentIndex, @@ -133,9 +133,9 @@ const ( ) type BinaryOp struct { - operator Operator - lhs CellRefer - rhs ResOperander // (except DoubleDeref and BinaryOp) + Operator Operator + Lhs CellRefer + Rhs ResOperander // (except DoubleDeref and BinaryOp) } func (bop BinaryOp) String() string { @@ -143,21 +143,21 @@ func (bop BinaryOp) String() string { } func (bop BinaryOp) Resolve(vm *VM.VirtualMachine) (mem.MemoryValue, error) { - lhsAddr, err := bop.lhs.Get(vm) + lhsAddr, err := bop.Lhs.Get(vm) if err != nil { - return mem.UnknownValue, fmt.Errorf("get lhs address %s: %w", bop.lhs, err) + return mem.UnknownValue, fmt.Errorf("get lhs address %s: %w", bop.Lhs, err) } lhs, err := vm.Memory.ReadFromAddress(&lhsAddr) if err != nil { return mem.UnknownValue, fmt.Errorf("read lhs address %s: %w", lhsAddr, err) } - rhs, err := bop.rhs.Resolve(vm) + rhs, err := bop.Rhs.Resolve(vm) if err != nil { return mem.UnknownValue, fmt.Errorf("resolve rhs operand %s: %w", rhs, err) } - switch bop.operator { + switch bop.Operator { case Add: mv := mem.EmptyMemoryValueAs(lhs.IsAddress() || rhs.IsAddress()) err := mv.Add(&lhs, &rhs) @@ -167,6 +167,6 @@ func (bop BinaryOp) Resolve(vm *VM.VirtualMachine) (mem.MemoryValue, error) { err := mv.Mul(&lhs, &rhs) return mv, err default: - return mem.UnknownValue, fmt.Errorf("unknown binary operator: %d", bop.operator) + return mem.UnknownValue, fmt.Errorf("unknown binary operator: %d", bop.Operator) } } diff --git a/pkg/hintrunner/operand_test.go b/pkg/hintrunner/hinter/operand_test.go similarity index 80% rename from pkg/hintrunner/operand_test.go rename to pkg/hintrunner/hinter/operand_test.go index 0446b8c3c..99d0bb7d5 100644 --- a/pkg/hintrunner/operand_test.go +++ b/pkg/hintrunner/hinter/operand_test.go @@ -1,8 +1,9 @@ -package hintrunner +package hinter import ( "testing" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/utils" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" @@ -10,9 +11,9 @@ import ( ) func TestGetAp(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 5 - writeTo(vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromInt(11)) + utils.WriteTo(vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromInt(11)) var apReg ApCellRef = 7 apAddr, err := apReg.Get(vm) @@ -26,9 +27,9 @@ func TestGetAp(t *testing.T) { } func TestGetFp(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Fp = 15 - writeTo(vm, VM.ExecutionSegment, vm.Context.Fp-7, memory.MemoryValueFromInt(11)) + utils.WriteTo(vm, VM.ExecutionSegment, vm.Context.Fp-7, memory.MemoryValueFromInt(11)) var fpReg FpCellRef = -7 fpAddr, err := fpReg.Get(vm) @@ -41,9 +42,9 @@ func TestGetFp(t *testing.T) { } func TestResolveDeref(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 5 - writeTo(vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromInt(11)) + utils.WriteTo(vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromInt(11)) var apCell ApCellRef = 7 deref := Deref{apCell} @@ -55,14 +56,14 @@ func TestResolveDeref(t *testing.T) { } func TestResolveDoubleDerefPositiveOffset(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 5 - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromSegmentAndOffset(VM.ExecutionSegment, 0), ) - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, 14, memory.MemoryValueFromInt(13), @@ -77,14 +78,14 @@ func TestResolveDoubleDerefPositiveOffset(t *testing.T) { } func TestResolveDoubleDerefNegativeOffset(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 5 - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromSegmentAndOffset(VM.ExecutionSegment, 20), ) - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, 6, memory.MemoryValueFromInt(13), @@ -110,17 +111,17 @@ func TestResolveImmediate(t *testing.T) { } func TestResolveAddOp(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() // Set the information used by the lhs vm.Context.Fp = 0 vm.Context.Ap = 5 - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromSegmentAndOffset(4, 29), ) // Set the information used by the rhs - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Fp+20, memory.MemoryValueFromInt(30), @@ -136,9 +137,9 @@ func TestResolveAddOp(t *testing.T) { operator := Add bop := BinaryOp{ - operator: operator, - lhs: ap, - rhs: deref, + Operator: operator, + Lhs: ap, + Rhs: deref, } res, err := bop.Resolve(vm) @@ -147,17 +148,17 @@ func TestResolveAddOp(t *testing.T) { } func TestResolveMulOp(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() // Set the information used by the lhs vm.Context.Fp = 0 vm.Context.Ap = 5 - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Ap+7, memory.MemoryValueFromInt(100), ) // Set the information used by the rhs - writeTo( + utils.WriteTo( vm, VM.ExecutionSegment, vm.Context.Fp+20, memory.MemoryValueFromInt(5), @@ -173,9 +174,9 @@ func TestResolveMulOp(t *testing.T) { operator := Mul bop := BinaryOp{ - operator: operator, - lhs: ap, - rhs: deref, + Operator: operator, + Lhs: ap, + Rhs: deref, } res, err := bop.Resolve(vm) diff --git a/pkg/hintrunner/utils.go b/pkg/hintrunner/hinter/utils.go similarity index 60% rename from pkg/hintrunner/utils.go rename to pkg/hintrunner/hinter/utils.go index 633b7adbb..7ee892195 100644 --- a/pkg/hintrunner/utils.go +++ b/pkg/hintrunner/hinter/utils.go @@ -1,9 +1,7 @@ -package hintrunner +package hinter import ( - "encoding/binary" "fmt" - "math/rand" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" @@ -51,26 +49,3 @@ func ResolveAsUint64(vm *VM.VirtualMachine, op ResOperander) (uint64, error) { return uint64Value, nil } - -func randomFeltElement(rand *rand.Rand) f.Element { - b := [32]byte{} - binary.BigEndian.PutUint64(b[24:32], rand.Uint64()) - binary.BigEndian.PutUint64(b[16:24], rand.Uint64()) - binary.BigEndian.PutUint64(b[8:16], rand.Uint64()) - //Limit to 59 bits so at max we have a 251 bit number - binary.BigEndian.PutUint64(b[0:8], rand.Uint64()>>5) - f, _ := f.BigEndian.Element(&b) - return f -} - -func randomFeltElementU128(rand *rand.Rand) f.Element { - b := [32]byte{} - binary.BigEndian.PutUint64(b[24:32], rand.Uint64()) - binary.BigEndian.PutUint64(b[16:24], rand.Uint64()) - f, _ := f.BigEndian.Element(&b) - return f -} - -func defaultRandGenerator() *rand.Rand { - return rand.New(rand.NewSource(0)) -} diff --git a/pkg/hintrunner/hintrunner.go b/pkg/hintrunner/hintrunner.go index e2e21f06e..6023332d4 100644 --- a/pkg/hintrunner/hintrunner.go +++ b/pkg/hintrunner/hintrunner.go @@ -3,209 +3,27 @@ package hintrunner import ( "fmt" + h "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" - f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" ) -// Used to keep track of all dictionaries data -type Dictionary struct { - // The data contained on a dictionary - data map[f.Element]*mem.MemoryValue - // Unique id assigned at the moment of creation - idx uint64 -} - -// Gets the memory value at certain key -func (d *Dictionary) At(key *f.Element) (*mem.MemoryValue, error) { - if value, ok := d.data[*key]; ok { - return value, nil - } - return nil, fmt.Errorf("no value for key %s", key) -} - -// Given a key and a value, it sets the value at the given key -func (d *Dictionary) Set(key *f.Element, value *mem.MemoryValue) { - d.data[*key] = value -} - -// Returns the initialization number when the dictionary was created -func (d *Dictionary) InitNumber() uint64 { - return d.idx -} - -// Used to manage dictionaries creation -type DictionaryManager struct { - // a map that links a segment index to a dictionary - dictionaries map[uint64]Dictionary -} - -func InitializeDictionaryManagerIfNot(ctx *HintRunnerContext) { - if ctx.DictionaryManager.dictionaries == nil { - ctx.DictionaryManager.dictionaries = make(map[uint64]Dictionary) - } -} - -// It creates a new segment which will hold dictionary values. It links this -// segment with the current dictionary and returns the address that points -// to the start of this segment -func (dm *DictionaryManager) NewDictionary(vm *VM.VirtualMachine) mem.MemoryAddress { - newDictAddr := vm.Memory.AllocateEmptySegment() - dm.dictionaries[newDictAddr.SegmentIndex] = Dictionary{ - data: make(map[f.Element]*mem.MemoryValue), - idx: uint64(len(dm.dictionaries)), - } - return newDictAddr -} - -// Given a memory address, it looks for the right dictionary using the segment index. If no -// segment is associated with the given segment index, it errors -func (dm *DictionaryManager) GetDictionary(dictAddr *mem.MemoryAddress) (Dictionary, error) { - dict, ok := dm.dictionaries[dictAddr.SegmentIndex] - if ok { - return dict, nil - } - return Dictionary{}, fmt.Errorf("no dictionary at address %s", dictAddr) -} - -// Given a memory address and a key it returns the value held at that position. The address is used -// to locate the correct dictionary and the key to index on it -func (dm *DictionaryManager) At(dictAddr *mem.MemoryAddress, key *f.Element) (*mem.MemoryValue, error) { - if dict, ok := dm.dictionaries[dictAddr.SegmentIndex]; ok { - return dict.At(key) - } - return nil, fmt.Errorf("no dictionary at address %s", dictAddr) -} - -// Given a memory address,a key and a value it stores the value at the correct position. -func (dm *DictionaryManager) Set(dictAddr *mem.MemoryAddress, key *f.Element, value *mem.MemoryValue) error { - if dict, ok := dm.dictionaries[dictAddr.SegmentIndex]; ok { - dict.Set(key, value) - return nil - } - return fmt.Errorf("no dictionary at address %s", dictAddr) -} - -// Used to keep track of squashed dictionaries -type SquashedDictionaryManager struct { - // A map from each key to a list of indices where the key is present - // the list in reversed order. - // Note: The indices should be Felts, but current memory limitations - // make it impossible to use an index that big so we use uint64 instead - KeyToIndices map[f.Element][]uint64 - - // A descending list of keys - Keys []f.Element -} - -func InitializeSquashedDictionaryManager(ctx *HintRunnerContext) error { - if ctx.SquashedDictionaryManager.KeyToIndices != nil || - ctx.SquashedDictionaryManager.Keys != nil { - return fmt.Errorf("squashed dictionary manager already initialized") - } - ctx.SquashedDictionaryManager.KeyToIndices = make(map[f.Element][]uint64, 100) - ctx.SquashedDictionaryManager.Keys = make([]f.Element, 0, 100) - return nil -} - -// It adds another index to the list of indices associated to the given key -// If the key is not present, it creates a new entry -func (sdm *SquashedDictionaryManager) Insert(key *f.Element, index uint64) { - keyIndex := *key - if indices, ok := sdm.KeyToIndices[keyIndex]; ok { - sdm.KeyToIndices[keyIndex] = append(indices, index) - } else { - sdm.KeyToIndices[keyIndex] = []uint64{index} - } -} - -// It returns the smallest key in the key list -func (sdm *SquashedDictionaryManager) LastKey() (f.Element, error) { - if len(sdm.Keys) == 0 { - return f.Element{}, fmt.Errorf("no keys left") - } - return sdm.Keys[len(sdm.Keys)-1], nil -} - -// It pops out the smallest key in the key list -func (sdm *SquashedDictionaryManager) PopKey() (f.Element, error) { - key, err := sdm.LastKey() - if err != nil { - return key, err - } - - sdm.Keys = sdm.Keys[:len(sdm.Keys)-1] - return key, nil -} - -// It returns the list of indices associated to the smallest key -func (sdm *SquashedDictionaryManager) LastIndices() ([]uint64, error) { - key, err := sdm.LastKey() - if err != nil { - return nil, err - } - - return sdm.KeyToIndices[key], nil -} - -// It returns smallest index associated with the smallest key -func (sdm *SquashedDictionaryManager) LastIndex() (uint64, error) { - key, err := sdm.LastKey() - if err != nil { - return 0, err - } - - indices := sdm.KeyToIndices[key] - if len(indices) == 0 { - return 0, fmt.Errorf("no indices for key %s", &key) - } - - return indices[len(indices)-1], nil -} - -// It pops out smallest index associated with the smallest key -func (sdm *SquashedDictionaryManager) PopIndex() (uint64, error) { - key, err := sdm.LastKey() - if err != nil { - return 0, err - } - - indices := sdm.KeyToIndices[key] - if len(indices) == 0 { - return 0, fmt.Errorf("no indices for key %s", &key) - } - - index := indices[len(indices)-1] - sdm.KeyToIndices[key] = indices[:len(indices)-1] - return index, nil -} - -// Global context to keep track of different results across different -// hints execution. -type HintRunnerContext struct { - DictionaryManager DictionaryManager - SquashedDictionaryManager SquashedDictionaryManager - ExcludedArc int - // points towards free memory of a segment - ConstantSizeSegment mem.MemoryAddress -} - type HintRunner struct { // Execution context required by certain hints such as dictionaires - context HintRunnerContext + context h.HintRunnerContext // A mapping from program counter to hint implementation - hints map[uint64]Hinter + hints map[uint64]h.Hinter } -func NewHintRunner(hints map[uint64]Hinter) HintRunner { +func NewHintRunner(hints map[uint64]h.Hinter) HintRunner { return HintRunner{ // Context for certain hints that require it. Each manager is // initialized only when required by the hint - context: HintRunnerContext{ - DictionaryManager{}, - SquashedDictionaryManager{}, - 0, - mem.UnknownAddress, + context: h.HintRunnerContext{ + DictionaryManager: h.DictionaryManager{}, + SquashedDictionaryManager: h.SquashedDictionaryManager{}, + ExcludedArc: 0, + ConstantSizeSegment: mem.UnknownAddress, }, hints: hints, } diff --git a/pkg/hintrunner/hintrunner_test.go b/pkg/hintrunner/hintrunner_test.go index 4dcfd6670..8cb0b8422 100644 --- a/pkg/hintrunner/hintrunner_test.go +++ b/pkg/hintrunner/hintrunner_test.go @@ -3,19 +3,22 @@ package hintrunner import ( "testing" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/core" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/utils" VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" "github.com/stretchr/testify/require" ) func TestExistingHint(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 3 - var ap ApCellRef = 5 - allocHint := AllocSegment{ap} + var ap hinter.ApCellRef = 5 + allocHint := core.AllocSegment{Dst: ap} - hr := NewHintRunner(map[uint64]Hinter{ + hr := NewHintRunner(map[uint64]hinter.Hinter{ 10: &allocHint, }) @@ -28,18 +31,18 @@ func TestExistingHint(t *testing.T) { require.Equal( t, memory.MemoryValueFromSegmentAndOffset(2, 0), - readFrom(vm, VM.ExecutionSegment, vm.Context.Ap+5), + utils.ReadFrom(vm, VM.ExecutionSegment, vm.Context.Ap+5), ) } func TestNoHint(t *testing.T) { - vm := defaultVirtualMachine() + vm := VM.DefaultVirtualMachine() vm.Context.Ap = 3 - var ap ApCellRef = 5 - allocHint := AllocSegment{ap} + var ap hinter.ApCellRef = 5 + allocHint := core.AllocSegment{Dst: ap} - hr := NewHintRunner(map[uint64]Hinter{ + hr := NewHintRunner(map[uint64]hinter.Hinter{ 10: &allocHint, }) diff --git a/pkg/hintrunner/testutils.go b/pkg/hintrunner/testutils.go deleted file mode 100644 index 420507296..000000000 --- a/pkg/hintrunner/testutils.go +++ /dev/null @@ -1,34 +0,0 @@ -package hintrunner - -import ( - "github.com/NethermindEth/cairo-vm-go/pkg/vm" - VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" - "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" -) - -func defaultVirtualMachine() *vm.VirtualMachine { - memory := memory.InitializeEmptyMemory() - memory.AllocateEmptySegment() - memory.AllocateEmptySegment() - - vm, err := vm.NewVirtualMachine(vm.Context{}, memory, vm.VirtualMachineConfig{}) - if err != nil { - panic(err) - } - return vm -} - -func writeTo(vm *VM.VirtualMachine, segment uint64, offset uint64, val memory.MemoryValue) { - err := vm.Memory.Write(segment, offset, &val) - if err != nil { - panic(err) - } -} - -func readFrom(vm *VM.VirtualMachine, segment uint64, offset uint64) memory.MemoryValue { - val, err := vm.Memory.Read(segment, offset) - if err != nil { - panic(err) - } - return val -} diff --git a/pkg/hintrunner/utils/testutils.go b/pkg/hintrunner/utils/testutils.go new file mode 100644 index 000000000..9cf8bf35d --- /dev/null +++ b/pkg/hintrunner/utils/testutils.go @@ -0,0 +1,21 @@ +package utils + +import ( + VM "github.com/NethermindEth/cairo-vm-go/pkg/vm" + "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" +) + +func WriteTo(vm *VM.VirtualMachine, segment uint64, offset uint64, val memory.MemoryValue) { + err := vm.Memory.Write(segment, offset, &val) + if err != nil { + panic(err) + } +} + +func ReadFrom(vm *VM.VirtualMachine, segment uint64, offset uint64) memory.MemoryValue { + val, err := vm.Memory.Read(segment, offset) + if err != nil { + panic(err) + } + return val +} diff --git a/pkg/hintrunner/utils/utils.go b/pkg/hintrunner/utils/utils.go new file mode 100644 index 000000000..ac4296e45 --- /dev/null +++ b/pkg/hintrunner/utils/utils.go @@ -0,0 +1,31 @@ +package utils + +import ( + "encoding/binary" + "math/rand" + + f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" +) + +func RandomFeltElement(rand *rand.Rand) f.Element { + b := [32]byte{} + binary.BigEndian.PutUint64(b[24:32], rand.Uint64()) + binary.BigEndian.PutUint64(b[16:24], rand.Uint64()) + binary.BigEndian.PutUint64(b[8:16], rand.Uint64()) + //Limit to 59 bits so at max we have a 251 bit number + binary.BigEndian.PutUint64(b[0:8], rand.Uint64()>>5) + f, _ := f.BigEndian.Element(&b) + return f +} + +func RandomFeltElementU128(rand *rand.Rand) f.Element { + b := [32]byte{} + binary.BigEndian.PutUint64(b[24:32], rand.Uint64()) + binary.BigEndian.PutUint64(b[16:24], rand.Uint64()) + f, _ := f.BigEndian.Element(&b) + return f +} + +func DefaultRandGenerator() *rand.Rand { + return rand.New(rand.NewSource(0)) +} diff --git a/pkg/hintrunner/hintcode.go b/pkg/hintrunner/zero/hintcode.go similarity index 78% rename from pkg/hintrunner/hintcode.go rename to pkg/hintrunner/zero/hintcode.go index 839b511ee..696340215 100644 --- a/pkg/hintrunner/hintcode.go +++ b/pkg/hintrunner/zero/hintcode.go @@ -1,4 +1,4 @@ -package hintrunner +package zero const ( AllocSegmentCode string = "memory[ap] = segments.add()" diff --git a/pkg/hintrunner/hintparser.go b/pkg/hintrunner/zero/hintparser.go similarity index 77% rename from pkg/hintrunner/hintparser.go rename to pkg/hintrunner/zero/hintparser.go index bb7814b9c..19113d1cd 100644 --- a/pkg/hintrunner/hintparser.go +++ b/pkg/hintrunner/zero/hintparser.go @@ -1,9 +1,14 @@ -package hintrunner +package zero import ( "fmt" + + op "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" + "github.com/alecthomas/participle/v2" ) +var parser *participle.Parser[IdentifierExp] = participle.MustBuild[IdentifierExp](participle.UseLookahead(10)) + // Possible cases extracted from https://github.com/lambdaclass/cairo-vm_in_go/blob/main/pkg/hints/hint_utils/hint_reference.go#L41 // Immediate: cast(number, type) // Reference no deref 1 offset: cast(reg + off, type) @@ -32,7 +37,7 @@ type DerefCastExp struct { type CastExp struct { ValueExpr *Expression `"cast" "(" @@ ","` - CastType []string `@Ident ("." @Ident)* ("*")? ("*")? ")"` + CastType []string `@Ident ("." @Ident)* ("*")? ("*")? ")"` } type Expression struct { @@ -57,8 +62,8 @@ type DerefExp struct { } type BinOpExp struct { - LeftExp *LeftExp `@@ "+"` - RightExp *RightExp `@@` + LeftExp *LeftExp `@@ "+"` + RightExp *RightExp `@@` } type OffsetExp struct { @@ -68,7 +73,7 @@ type OffsetExp struct { type LeftExp struct { CellRefExp *RegisterOffset `@@ |` - DerefExp *DerefExp `@@` + DerefExp *DerefExp `@@` } type RightExp struct { @@ -77,15 +82,14 @@ type RightExp struct { } type DerefOffset struct { - Deref Deref + Deref op.Deref Offset *int } type DerefDeref struct { - LeftDeref Deref - RightDeref Deref + LeftDeref op.Deref + RightDeref op.Deref } - // AST Functionality func (expression IdentifierExp) Evaluate() (any, error) { switch { @@ -105,20 +109,20 @@ func (expression DerefCastExp) Evaluate() (any, error) { } switch result := value.(type) { - case CellRefer: - return Deref{result}, nil - case Deref: - return DoubleDeref{ - result.deref, - 0, - }, - nil + case op.CellRefer: + return op.Deref{Deref: result}, nil + case op.Deref: + return op.DoubleDeref{ + Deref: result.Deref, + Offset: 0, + }, + nil case DerefOffset: - return DoubleDeref{ - result.Deref.deref, - int16(*result.Offset), - }, - nil + return op.DoubleDeref{ + Deref: result.Deref.Deref, + Offset: int16(*result.Offset), + }, + nil default: return nil, fmt.Errorf("unexpected identifier value") } @@ -131,15 +135,15 @@ func (expression CastExp) Evaluate() (any, error) { } switch result := value.(type) { - case CellRefer: + case op.CellRefer: return result, nil - case Deref: + case op.Deref: return result, nil case DerefOffset: - return BinaryOp{ - 0, - result.Deref.deref, - Immediate{ + return op.BinaryOp{ + Operator: 0, + Lhs: result.Deref.Deref, + Rhs: op.Immediate{ uint64(0), uint64(0), uint64(0), @@ -147,10 +151,10 @@ func (expression CastExp) Evaluate() (any, error) { }, }, nil case DerefDeref: - return BinaryOp{ - 0, - result.LeftDeref.deref, - result.RightDeref, + return op.BinaryOp{ + Operator: 0, + Lhs: result.LeftDeref.Deref, + Rhs: result.RightDeref, }, nil default: return nil, fmt.Errorf("unexpected identifier value") @@ -176,7 +180,7 @@ func (expression RegisterOffset) Evaluate() (any, error) { if expression.Operator == "-" { offset = -offset } - + return EvaluateRegister(expression.Register, offset) } @@ -184,16 +188,16 @@ func (expression CellRefExp) Evaluate() (any, error) { if expression.RegisterOffset != nil { return expression.RegisterOffset.Evaluate() } - + return EvaluateRegister(expression.Register, 0) } -func EvaluateRegister(register string, offset int16) (CellRefer, error) { - switch register{ +func EvaluateRegister(register string, offset int16) (op.CellRefer, error) { + switch register { case "ap": - return ApCellRef(offset), nil + return op.ApCellRef(offset), nil case "fp": - return FpCellRef(offset), nil + return op.FpCellRef(offset), nil default: return nil, fmt.Errorf("invalid offset value") } @@ -216,11 +220,11 @@ func (expression DerefExp) Evaluate() (any, error) { if err != nil { return nil, err } - cellRef, ok := cellRefExp.(CellRefer) + cellRef, ok := cellRefExp.(op.CellRefer) if !ok { return nil, fmt.Errorf("Expected a CellRefer expression but got %s", cellRefExp) } - return Deref{cellRef}, nil + return op.Deref{Deref: cellRef}, nil } func (expression BinOpExp) Evaluate() (any, error) { @@ -230,12 +234,12 @@ func (expression BinOpExp) Evaluate() (any, error) { } rightExp, err := expression.RightExp.Evaluate() - if err != nil{ + if err != nil { return nil, err } - switch lResult := leftExp.(type){ - case CellRefer: + switch lResult := leftExp.(type) { + case op.CellRefer: offset, ok := rightExp.(*int) if !ok { return nil, fmt.Errorf("invalid type operation") @@ -244,23 +248,23 @@ func (expression BinOpExp) Evaluate() (any, error) { var cellRefOffset int16 switch register := lResult.(type) { - case ApCellRef: + case op.ApCellRef: cellRefOffset = int16(register) - case FpCellRef: + case op.FpCellRef: cellRefOffset = int16(register) } offsetValue = offsetValue + cellRefOffset switch lResult.(type) { - case ApCellRef: - return ApCellRef(offsetValue), nil - case FpCellRef: - return FpCellRef(offsetValue), nil + case op.ApCellRef: + return op.ApCellRef(offsetValue), nil + case op.FpCellRef: + return op.FpCellRef(offsetValue), nil } - - case Deref: + + case op.Deref: switch rResult := rightExp.(type) { - case Deref: + case op.Deref: return DerefDeref{ lResult, rResult, @@ -277,7 +281,7 @@ func (expression BinOpExp) Evaluate() (any, error) { } func (expression LeftExp) Evaluate() (any, error) { - switch{ + switch { case expression.CellRefExp != nil: return expression.CellRefExp.Evaluate() case expression.DerefExp != nil: @@ -287,7 +291,7 @@ func (expression LeftExp) Evaluate() (any, error) { } func (expression RightExp) Evaluate() (any, error) { - switch{ + switch { case expression.DerefExp != nil: return expression.DerefExp.Evaluate() case expression.Offset != nil: @@ -295,3 +299,12 @@ func (expression RightExp) Evaluate() (any, error) { } return nil, fmt.Errorf("Unexpected right expression in binary operation") } + +func ParseIdentifier(value string) (any, error) { + identifierExp, err := parser.ParseString("", value) + if err != nil { + return nil, err + } + + return identifierExp.Evaluate() +} diff --git a/pkg/hintrunner/zerohint_test.go b/pkg/hintrunner/zero/hintparser_test.go similarity index 64% rename from pkg/hintrunner/zerohint_test.go rename to pkg/hintrunner/zero/hintparser_test.go index 7a8039421..39b8fd8a1 100644 --- a/pkg/hintrunner/zerohint_test.go +++ b/pkg/hintrunner/zero/hintparser_test.go @@ -1,47 +1,47 @@ -package hintrunner +package zero import ( "testing" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" "github.com/stretchr/testify/require" ) func TestHintParser(t *testing.T) { type testSetType struct { Parameter string - ExpectedCellRefer CellRefer - ExpectedResOperander ResOperander + ExpectedCellRefer hinter.CellRefer + ExpectedResOperander hinter.ResOperander } testSet := []testSetType{ { Parameter: "cast(fp + (-3), felt*)", - ExpectedCellRefer: FpCellRef(-3), + ExpectedCellRefer: hinter.FpCellRef(-3), ExpectedResOperander: nil, }, { Parameter: "[cast(ap + (-1) + 2, starkware.cairo.common.cairo_builtins.BitwiseBuiltin**)]", ExpectedCellRefer: nil, - ExpectedResOperander: Deref{ - deref: ApCellRef(1), + ExpectedResOperander: hinter.Deref{ + Deref: hinter.ApCellRef(1), }, }, { Parameter: "[cast([ap + 2], felt)]", ExpectedCellRefer: nil, - ExpectedResOperander: DoubleDeref{ - deref: ApCellRef(2), - offset: 0, - }, + ExpectedResOperander: hinter.DoubleDeref{ + Deref: hinter.ApCellRef(2), + Offset: 0}, }, { Parameter: "cast([ap + 2] + [ap], felt)", ExpectedCellRefer: nil, - ExpectedResOperander: BinaryOp{ - operator: Add, - lhs: ApCellRef(2), - rhs: Deref{ - deref: ApCellRef(0), + ExpectedResOperander: hinter.BinaryOp{ + Operator: hinter.Add, + Lhs: hinter.ApCellRef(2), + Rhs: hinter.Deref{ + Deref: hinter.ApCellRef(0), }, }, }, diff --git a/pkg/hintrunner/zerohint.go b/pkg/hintrunner/zero/zerohint.go similarity index 76% rename from pkg/hintrunner/zerohint.go rename to pkg/hintrunner/zero/zerohint.go index cf8998825..2fb7f4ece 100644 --- a/pkg/hintrunner/zerohint.go +++ b/pkg/hintrunner/zero/zerohint.go @@ -1,18 +1,17 @@ -package hintrunner +package zero import ( "fmt" "strconv" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/core" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" sn "github.com/NethermindEth/cairo-vm-go/pkg/parsers/starknet" zero "github.com/NethermindEth/cairo-vm-go/pkg/parsers/zero" - "github.com/alecthomas/participle/v2" ) -var parser *participle.Parser[IdentifierExp] = participle.MustBuild[IdentifierExp](participle.UseLookahead(10)) - -func GetZeroHints(cairoZeroJson *zero.ZeroProgram) (map[uint64]Hinter, error) { - hints := make(map[uint64]Hinter) +func GetZeroHints(cairoZeroJson *zero.ZeroProgram) (map[uint64]hinter.Hinter, error) { + hints := make(map[uint64]hinter.Hinter) for counter, rawHints := range cairoZeroJson.Hints { pc, err := strconv.ParseUint(counter, 10, 64) if err != nil { @@ -36,7 +35,7 @@ func GetZeroHints(cairoZeroJson *zero.ZeroProgram) (map[uint64]Hinter, error) { return hints, nil } -func GetHintFromCode(program *zero.ZeroProgram, rawHint zero.Hint, hintPC uint64) (Hinter, error) { +func GetHintFromCode(program *zero.ZeroProgram, rawHint zero.Hint, hintPC uint64) (hinter.Hinter, error) { cellRefParams, resOpParams, err := GetParameters(program, rawHint, hintPC) if err != nil { return nil, err @@ -50,16 +49,16 @@ func GetHintFromCode(program *zero.ZeroProgram, rawHint zero.Hint, hintPC uint64 } } -func CreateAllocSegmentHinter(cellRefParams []CellRefer, resOpParams []ResOperander) (Hinter, error) { +func CreateAllocSegmentHinter(cellRefParams []hinter.CellRefer, resOpParams []hinter.ResOperander) (hinter.Hinter, error) { if len(cellRefParams)+len(resOpParams) != 0 { return nil, fmt.Errorf("Expected no arguments for %s hint", sn.AllocSegmentName) } - return &AllocSegment{dst: ApCellRef(0)}, nil + return &core.AllocSegment{Dst: hinter.ApCellRef(0)}, nil } -func GetParameters(zeroProgram *zero.ZeroProgram, hint zero.Hint, hintPC uint64) ([]CellRefer, []ResOperander, error) { - var cellRefParams []CellRefer - var resOpParams []ResOperander +func GetParameters(zeroProgram *zero.ZeroProgram, hint zero.Hint, hintPC uint64) ([]hinter.CellRefer, []hinter.ResOperander, error) { + var cellRefParams []hinter.CellRefer + var resOpParams []hinter.ResOperander for referenceName := range hint.FlowTrackingData.ReferenceIds { rawIdentifier, ok := zeroProgram.Identifiers[referenceName] if !ok { @@ -98,9 +97,9 @@ func GetParameters(zeroProgram *zero.ZeroProgram, hint zero.Hint, hintPC uint64) return nil, nil, err } switch result := param.(type) { - case CellRefer: + case hinter.CellRefer: cellRefParams = append(cellRefParams, result) - case ResOperander: + case hinter.ResOperander: resOpParams = append(resOpParams, result) default: return nil, nil, fmt.Errorf("unexpected type for identifier value %s", reference.Value) @@ -109,12 +108,3 @@ func GetParameters(zeroProgram *zero.ZeroProgram, hint zero.Hint, hintPC uint64) return cellRefParams, resOpParams, nil } - -func ParseIdentifier(value string) (any, error) { - identifierExp, err := parser.ParseString("", value) - if err != nil { - return nil, err - } - - return identifierExp.Evaluate() -} diff --git a/pkg/runners/zero/zero.go b/pkg/runners/zero/zero.go index b73868e75..05791f457 100644 --- a/pkg/runners/zero/zero.go +++ b/pkg/runners/zero/zero.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" "github.com/NethermindEth/cairo-vm-go/pkg/utils" "github.com/NethermindEth/cairo-vm-go/pkg/vm" "github.com/NethermindEth/cairo-vm-go/pkg/vm/builtins" @@ -26,7 +27,7 @@ type ZeroRunner struct { } // Creates a new Runner of a Cairo Zero program -func NewRunner(program *Program, hints map[uint64]hintrunner.Hinter, proofmode bool, maxsteps uint64) (ZeroRunner, error) { +func NewRunner(program *Program, hints map[uint64]hinter.Hinter, proofmode bool, maxsteps uint64) (ZeroRunner, error) { hintrunner := hintrunner.NewHintRunner(hints) return ZeroRunner{ diff --git a/pkg/runners/zero/zero_benchmark_test.go b/pkg/runners/zero/zero_benchmark_test.go index adeab4b9e..b85bffc8d 100644 --- a/pkg/runners/zero/zero_benchmark_test.go +++ b/pkg/runners/zero/zero_benchmark_test.go @@ -4,7 +4,7 @@ import ( "math" "testing" - hintrunner "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner" + hintrunner "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/zero" zero "github.com/NethermindEth/cairo-vm-go/pkg/parsers/zero" ) diff --git a/pkg/runners/zero/zero_test.go b/pkg/runners/zero/zero_test.go index 9d0332cdd..0ccf38180 100644 --- a/pkg/runners/zero/zero_test.go +++ b/pkg/runners/zero/zero_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/NethermindEth/cairo-vm-go/pkg/assembler" - "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner" + "github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter" sn "github.com/NethermindEth/cairo-vm-go/pkg/parsers/starknet" "github.com/NethermindEth/cairo-vm-go/pkg/vm" "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" @@ -26,7 +26,7 @@ func TestSimpleProgram(t *testing.T) { ret; `) - hints := make(map[uint64]hintrunner.Hinter) + hints := make(map[uint64]hinter.Hinter) runner, err := NewRunner(program, hints, false, math.MaxUint64) require.NoError(t, err) @@ -73,7 +73,7 @@ func TestStepLimitExceeded(t *testing.T) { ret; `) - hints := make(map[uint64]hintrunner.Hinter) + hints := make(map[uint64]hinter.Hinter) runner, err := NewRunner(program, hints, false, 3) require.NoError(t, err) @@ -132,7 +132,7 @@ func TestStepLimitExceededProofMode(t *testing.T) { t.Logf("Using maxstep: %d\n", maxstep) // when maxstep = 6, it fails executing the extra step required by proof mode // when maxstep = 7, it fails trying to get the trace to be a power of 2 - hints := make(map[uint64]hintrunner.Hinter) + hints := make(map[uint64]hinter.Hinter) runner, err := NewRunner(program, hints, true, uint64(maxstep)) require.NoError(t, err) @@ -367,7 +367,7 @@ func TestEcOpBuiltin(t *testing.T) { func createRunner(code string, builtins ...sn.Builtin) ZeroRunner { program := createProgramWithBuiltins(code, builtins...) - hints := make(map[uint64]hintrunner.Hinter) + hints := make(map[uint64]hinter.Hinter) runner, err := NewRunner(program, hints, false, math.MaxUint64) if err != nil { panic(err) diff --git a/pkg/vm/utils.go b/pkg/vm/utils.go new file mode 100644 index 000000000..97ec924f3 --- /dev/null +++ b/pkg/vm/utils.go @@ -0,0 +1,37 @@ +package vm + +import ( + f "github.com/consensys/gnark-crypto/ecc/stark-curve/fp" + + a "github.com/NethermindEth/cairo-vm-go/pkg/assembler" + mem "github.com/NethermindEth/cairo-vm-go/pkg/vm/memory" +) + +func DefaultVirtualMachine() *VirtualMachine { + return defaultVirtualMachineWithBytecode(nil) +} + +func defaultVirtualMachineWithCode(code string) *VirtualMachine { + bytecode, err := a.CasmToBytecode(code) + if err != nil { + panic(err) + } + + return defaultVirtualMachineWithBytecode(bytecode) +} + +func defaultVirtualMachineWithBytecode(bytecode []*f.Element) *VirtualMachine { + memory := mem.InitializeEmptyMemory() + _, err := memory.AllocateSegment(bytecode) + if err != nil { + panic(err) + } + + memory.AllocateEmptySegment() + + vm, err := NewVirtualMachine(Context{}, memory, VirtualMachineConfig{}) + if err != nil { + panic(err) + } + return vm +} diff --git a/pkg/vm/vm_test.go b/pkg/vm/vm_test.go index 332d8c921..72fff9f3e 100644 --- a/pkg/vm/vm_test.go +++ b/pkg/vm/vm_test.go @@ -17,7 +17,7 @@ import ( // =========================================== func TestGetCellApDst(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const offDest = 15 @@ -40,7 +40,7 @@ func TestGetCellApDst(t *testing.T) { } func TestGetCellFpDst(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const ( @@ -67,7 +67,7 @@ func TestGetCellFpDst(t *testing.T) { } func TestGetCellApDstWithDifferentOffsets(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() offsets := []int{-10, -5, 0, 5, 10} for _, offset := range offsets { @@ -92,7 +92,7 @@ func TestGetCellApDstWithDifferentOffsets(t *testing.T) { } func TestGetCellDstApNegativeOffset(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() const ( offDest = -2 @@ -117,7 +117,7 @@ func TestGetCellDstApNegativeOffset(t *testing.T) { } func TestGetCellDstFpNegativeOffset(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() const ( offDest = -19 @@ -142,7 +142,7 @@ func TestGetCellDstFpNegativeOffset(t *testing.T) { } func TestGetApCellOp0(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const ( @@ -168,7 +168,7 @@ func TestGetApCellOp0(t *testing.T) { func TestGetApCellOp0NegOff(t *testing.T) { // Op0 & Ap & Negative case - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const ( @@ -194,7 +194,7 @@ func TestGetApCellOp0NegOff(t *testing.T) { func TestGetFpCellOp0(t *testing.T) { // Op0 & Fp & Positive case - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const ( @@ -220,7 +220,7 @@ func TestGetFpCellOp0(t *testing.T) { func TestGetFpCellOp0NegOff(t *testing.T) { // Op0 & Fp & Negative case - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const ( @@ -328,7 +328,7 @@ func TestGetOp0NegCellOp1(t *testing.T) { } func TestGetFpPosCellOp1(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const offOp1 = 2 // target relative to Fp @@ -350,7 +350,7 @@ func TestGetFpPosCellOp1(t *testing.T) { } func TestGetFpNegCellOp1(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values const offOp1 = -2 // target relative to Fp @@ -372,7 +372,7 @@ func TestGetFpNegCellOp1(t *testing.T) { } func TestGetApPosCellOp1(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values vm.Context.Ap = 3 // "allocation pointer" @@ -393,7 +393,7 @@ func TestGetApPosCellOp1(t *testing.T) { } func TestGetApNegCellOp1(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() // Prepare vm with dummy values vm.Context.Ap = 3 // "allocation pointer" @@ -414,7 +414,7 @@ func TestGetApNegCellOp1(t *testing.T) { } func TestInferOperandSub(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{ Opcode: a.OpCodeAssertEq, Res: a.AddOperands, @@ -436,7 +436,7 @@ func TestInferOperandSub(t *testing.T) { } func TestInferResOp1(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{ Opcode: a.OpCodeAssertEq, Res: a.Op1, @@ -457,7 +457,7 @@ func TestInferResOp1(t *testing.T) { } func TestComputeResUnconstrained(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.Unconstrained} res, err := vm.computeRes(&instruction, nil, nil) require.NoError(t, err) @@ -465,7 +465,7 @@ func TestComputeResUnconstrained(t *testing.T) { } func TestComputeResOp1(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.Op1} writeToDataSegment(vm, 3, 15) @@ -479,7 +479,7 @@ func TestComputeResOp1(t *testing.T) { } func TestComputeAddResAddrToFelt(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.AddOperands} op0Addr := writeToDataSegment( @@ -495,7 +495,7 @@ func TestComputeAddResAddrToFelt(t *testing.T) { } func TestComputeAddResFeltToAddr(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.AddOperands} op0Addr := writeToDataSegment(vm, 2, 8) @@ -510,7 +510,7 @@ func TestComputeAddResFeltToAddr(t *testing.T) { } func TestComputeAddResBothAddrs(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.AddOperands} op0Addr := writeToDataSegment( @@ -525,7 +525,7 @@ func TestComputeAddResBothAddrs(t *testing.T) { } func TestComputeAddResBothFelts(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.AddOperands} op0Addr := writeToDataSegment(vm, 3, 10) @@ -540,7 +540,7 @@ func TestComputeAddResBothFelts(t *testing.T) { // Felt should be Positive or Negative. Thus four test cases func TestComputeMulResPosToPosFelt(t *testing.T) { //Positive Felt to Positive Felt compute - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} op0Addr := writeToDataSegment(vm, 3, 10) @@ -553,7 +553,7 @@ func TestComputeMulResPosToPosFelt(t *testing.T) { } func TestComputeMulResNegToPosFelts(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} //Negative to Positive op0Addr := writeToDataSegment(vm, 3, -10) @@ -566,7 +566,7 @@ func TestComputeMulResNegToPosFelts(t *testing.T) { } func TestComputeMulResPosToNegFelt(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} //Positive to Negative op0Addr := writeToDataSegment(vm, 3, 10) @@ -579,7 +579,7 @@ func TestComputeMulResPosToNegFelt(t *testing.T) { } func TestComputeMulResNegToNegFelt(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} //Netagive to Negative op0Addr := writeToDataSegment(vm, 3, -10) @@ -594,7 +594,7 @@ func TestComputeMulResNegToNegFelt(t *testing.T) { // Multiplication does not involve addresses // three failing cases func TestComputeMulResAddrToFelt(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} op0Addr := writeToDataSegment( @@ -607,7 +607,7 @@ func TestComputeMulResAddrToFelt(t *testing.T) { } func TestComputeMulResFeltToAddr(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} op0Addr := writeToDataSegment(vm, 3, 10) @@ -620,7 +620,7 @@ func TestComputeMulResFeltToAddr(t *testing.T) { } func TestComputeMulResBothAddrs(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{Res: a.MulOperands} op0Addr := writeToDataSegment( @@ -635,7 +635,7 @@ func TestComputeMulResBothAddrs(t *testing.T) { } func TestOpcodeAssertionAssertEq(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() dstAddr := mem.MemoryAddress{SegmentIndex: ExecutionSegment, Offset: 0} instruction := a.Instruction{ @@ -652,7 +652,7 @@ func TestOpcodeAssertionAssertEq(t *testing.T) { } func TestUpdatePcNextInstr(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Pc = mem.MemoryAddress{SegmentIndex: 0, Offset: 3} instruction := a.Instruction{ @@ -666,7 +666,7 @@ func TestUpdatePcNextInstr(t *testing.T) { } func TestUpdatePcNextInstrImm(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Pc = mem.MemoryAddress{SegmentIndex: 0, Offset: 3} instruction := a.Instruction{ @@ -680,7 +680,7 @@ func TestUpdatePcNextInstrImm(t *testing.T) { } func TestUpdatePcJump(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() instruction := a.Instruction{ PcUpdate: a.PcUpdateJump, @@ -707,7 +707,7 @@ func TestUpdatePcJump(t *testing.T) { } func TestUpdatePcJumpRel(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Pc = mem.MemoryAddress{SegmentIndex: 0, Offset: 3} relAddr := uint64(10) @@ -723,7 +723,7 @@ func TestUpdatePcJumpRel(t *testing.T) { } func TestUpdatePcJnz(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() relAddr := uint64(10) writeToDataSegment(vm, 0, 10) //dstCell writeToDataSegment(vm, 1, relAddr) //op1Cell @@ -743,7 +743,7 @@ func TestUpdatePcJnz(t *testing.T) { } func TestUpdatePcJnzDstZero(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() writeToDataSegment(vm, 0, 0) //dstCell dstAddr := mem.MemoryAddress{SegmentIndex: ExecutionSegment, Offset: 0} @@ -760,7 +760,7 @@ func TestUpdatePcJnzDstZero(t *testing.T) { } func TestUpdatePcJnzDstZeroImm(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() writeToDataSegment(vm, 0, 0) //dstCell dstAddr := mem.MemoryAddress{SegmentIndex: ExecutionSegment, Offset: 0} @@ -777,7 +777,7 @@ func TestUpdatePcJnzDstZeroImm(t *testing.T) { } func TestUpdateApSameAp(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Ap = 5 instruction := a.Instruction{ @@ -791,7 +791,7 @@ func TestUpdateApSameAp(t *testing.T) { } func TestUpdateApAddImmPos(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Ap = 5 instruction := a.Instruction{ @@ -807,7 +807,7 @@ func TestUpdateApAddImmPos(t *testing.T) { } func TestUpdateApAddImmNeg(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Ap = 10 instruction := a.Instruction{ @@ -823,7 +823,7 @@ func TestUpdateApAddImmNeg(t *testing.T) { } func TestUpdateApAddOne(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Ap = 5 instruction := a.Instruction{ @@ -837,7 +837,7 @@ func TestUpdateApAddOne(t *testing.T) { } func TestUpdateApAddTwo(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Ap = 5 instruction := a.Instruction{ @@ -851,7 +851,7 @@ func TestUpdateApAddTwo(t *testing.T) { } func TestUpdateFp(t *testing.T) { - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() vm.Context.Fp = 5 instruction := a.Instruction{ @@ -1136,7 +1136,7 @@ func TestMemoryRelocationWithFelt(t *testing.T) { // segment 0: [2, -, -, 3] // segment 3: [5, -, 7, -, 11, 13] // relocated: [-, 2, -, -, 3, 5, -, 7, -, 11, 13] - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() updateMemoryWithValues( vm.Memory, @@ -1189,7 +1189,7 @@ func TestMemoryRelocationWithAddress(t *testing.T) { // four: 1, 6, 10, 15, // ] - vm := defaultVirtualMachine() + vm := DefaultVirtualMachine() updateMemoryWithValues( vm.Memory, []memoryWrite{ @@ -1358,35 +1358,6 @@ func writeToDataSegment(vm *VirtualMachine, index uint64, value any) mem.MemoryA } } -func defaultVirtualMachine() *VirtualMachine { - return defaultVirtualMachineWithBytecode(nil) -} - -func defaultVirtualMachineWithCode(code string) *VirtualMachine { - bytecode, err := a.CasmToBytecode(code) - if err != nil { - panic(err) - } - - return defaultVirtualMachineWithBytecode(bytecode) -} - -func defaultVirtualMachineWithBytecode(bytecode []*f.Element) *VirtualMachine { - memory := mem.InitializeEmptyMemory() - _, err := memory.AllocateSegment(bytecode) - if err != nil { - panic(err) - } - - memory.AllocateEmptySegment() - - vm, err := NewVirtualMachine(Context{}, memory, VirtualMachineConfig{}) - if err != nil { - panic(err) - } - return vm -} - // create a pointer to an Element func newElementPtr(val uint64) *f.Element { element := f.NewElement(val)