-
Notifications
You must be signed in to change notification settings - Fork 50
/
zerohint_keccak.go
350 lines (308 loc) · 11.6 KB
/
zerohint_keccak.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package zero
import (
"fmt"
"math"
"github.com/NethermindEth/cairo-vm-go/pkg/hintrunner/hinter"
"github.com/NethermindEth/cairo-vm-go/pkg/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"
"github.com/consensys/gnark-crypto/ecc/stark-curve/fp"
"github.com/holiman/uint256"
"golang.org/x/crypto/sha3"
)
// CairoKeccakFinalize writes the result of F1600 Keccak permutation padded by __keccak_state_size_felts__ zeros to consecutive memory cells, __block_size__ times.
//
// `CairoKeccakFinalize` takes 1 operander as argument
// - `keccakPtrEnd` is the address in memory where to start writing the result
func newCairoKeccakFinalizeHint(keccakPtrEnd hinter.ResOperander) hinter.Hinter {
return &GenericZeroHinter{
Name: "CairoKeccakFinalize",
Op: func(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error {
//> _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
//> _block_size = int(ids.BLOCK_SIZE)
//> assert 0 <= _keccak_state_size_felts < 100
//> assert 0 <= _block_size < 10
//> inp = [0] * _keccak_state_size_felts
//> padding = (inp + keccak_func(inp)) * _block_size
//> segments.write_arg(ids.keccak_ptr_end, padding)
keccakStateSizeFeltsVal := uint64(25)
blockSizeVal := uint64(3)
var input [25]uint64
builtins.KeccakF1600(&input)
padding := make([]uint64, keccakStateSizeFeltsVal)
padding = append(padding, input[:]...)
result := make([]uint64, 0, keccakStateSizeFeltsVal*blockSizeVal)
for i := uint64(0); i < blockSizeVal; i++ {
result = append(result, padding...)
}
keccakPtrEnd, err := hinter.ResolveAsAddress(vm, keccakPtrEnd)
if err != nil {
return err
}
for i := 0; i < len(result); i++ {
resultMV := memory.MemoryValueFromUint(result[i])
err = vm.Memory.WriteToAddress(keccakPtrEnd, &resultMV)
if err != nil {
return err
}
keccakPtrEndIncremented, err := keccakPtrEnd.AddOffset(1)
if err != nil {
return err
}
keccakPtrEnd = &keccakPtrEndIncremented
}
return nil
},
}
}
func createCairoKeccakFinalizeHinter(resolver hintReferenceResolver) (hinter.Hinter, error) {
keccakPtrEnd, err := resolver.GetResOperander("keccak_ptr_end")
if err != nil {
return nil, err
}
return newCairoKeccakFinalizeHint(keccakPtrEnd), nil
}
// UnsafeKeccak computes keccak hash of the data in memory without validity enforcement and writes the result in the `low` and `high` memory cells
//
// `newUnsafeKeccakHint` takes 4 operanders as arguments
// - `data` is the address in memory where the base of the data array to be hashed is stored. Each word in the array is 16 bytes long, except the last one, which could vary
// - `length` is the length of the data to hash
// - `low` is the low part of the produced hash
// - `high` is the high part of the produced hash
func newUnsafeKeccakHint(data, length, high, low hinter.ResOperander) hinter.Hinter {
return &GenericZeroHinter{
Name: "UnsafeKeccak",
Op: func(vm *VM.VirtualMachine, ctx *hinter.HintRunnerContext) error {
//> from eth_hash.auto import keccak
//> data, length = ids.data, ids.length
//> if '__keccak_max_size' in globals():
//> assert length <= __keccak_max_size, \
//> f'unsafe_keccak() can only be used with length<={__keccak_max_size}. ' \
//> f'Got: length={length}.'
//> keccak_input = bytearray()
//> for word_i, byte_i in enumerate(range(0, length, 16)):
//> word = memory[data + word_i]
//> n_bytes = min(16, length - byte_i)
//> assert 0 <= word < 2 ** (8 * n_bytes)
//> keccak_input += word.to_bytes(n_bytes, 'big')
//> hashed = keccak(keccak_input)
//> ids.high = int.from_bytes(hashed[:16], 'big')
//> ids.low = int.from_bytes(hashed[16:32], 'big')
lengthVal, err := hinter.ResolveAsUint64(vm, length)
if err != nil {
return err
}
keccakMaxSize := uint64(1 << 20)
if lengthVal > keccakMaxSize {
return fmt.Errorf("unsafe_keccak() can only be used with length<=%d.\n Got: length=%d.", keccakMaxSize, lengthVal)
}
dataPtr, err := hinter.ResolveAsAddress(vm, data)
if err != nil {
return err
}
keccakInput := make([]byte, 0)
for i := uint64(0); i < lengthVal; i += 16 {
wordFelt, err := vm.Memory.ReadAsElement(dataPtr.SegmentIndex, dataPtr.Offset)
if err != nil {
return err
}
word := uint256.Int(wordFelt.Bits())
nBytes := utils.Min(lengthVal-i, 16)
if uint64(word.BitLen()) >= 8*nBytes {
return fmt.Errorf("word %v is out range 0 <= word < 2 ** %d", &word, 8*nBytes)
}
wordBytes := word.Bytes20()
keccakInput = append(keccakInput, wordBytes[20-int(nBytes):]...)
*dataPtr, err = dataPtr.AddOffset(1)
if err != nil {
return err
}
}
hash := sha3.NewLegacyKeccak256()
hash.Write(keccakInput)
hashedBytes := hash.Sum(nil)
hashedHigh := new(fp.Element).SetBytes(hashedBytes[:16])
hashedLow := new(fp.Element).SetBytes(hashedBytes[16:32])
highAddr, err := high.GetAddress(vm)
if err != nil {
return err
}
hashedHighMV := memory.MemoryValueFromFieldElement(hashedHigh)
err = vm.Memory.WriteToAddress(&highAddr, &hashedHighMV)
if err != nil {
return err
}
lowAddr, err := low.GetAddress(vm)
if err != nil {
return err
}
hashedLowMV := memory.MemoryValueFromFieldElement(hashedLow)
return vm.Memory.WriteToAddress(&lowAddr, &hashedLowMV)
},
}
}
func createUnsafeKeccakHinter(resolver hintReferenceResolver) (hinter.Hinter, error) {
data, err := resolver.GetResOperander("data")
if err != nil {
return nil, err
}
length, err := resolver.GetResOperander("length")
if err != nil {
return nil, err
}
high, err := resolver.GetResOperander("high")
if err != nil {
return nil, err
}
low, err := resolver.GetResOperander("low")
if err != nil {
return nil, err
}
return newUnsafeKeccakHint(data, length, high, low), nil
}
// KeccakWriteArgs hint writes Keccak function arguments in memory
//
// `newKeccakWriteArgsHint` takes 3 operanders as arguments
// - `inputs` is the address in memory where to write Keccak arguments
// - `low` is the low part of the `uint256` argument for the Keccac function
// - `high` is the high part of the `uint256` argument for the Keccac function
func newKeccakWriteArgsHint(inputs, low, high hinter.ResOperander) hinter.Hinter {
name := "KeccakWriteArgs"
return &GenericZeroHinter{
Name: name,
Op: func(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error {
//> segments.write_arg(ids.inputs, [ids.low % 2 ** 64, ids.low // 2 ** 64])
//> segments.write_arg(ids.inputs + 2, [ids.high % 2 ** 64, ids.high // 2 ** 64])
low, err := hinter.ResolveAsFelt(vm, low)
if err != nil {
return err
}
high, err := hinter.ResolveAsFelt(vm, high)
if err != nil {
return err
}
inputsPtr, err := hinter.ResolveAsAddress(vm, inputs)
if err != nil {
return err
}
var lowUint256 uint256.Int = uint256.Int(low.Bits())
var highUint256 uint256.Int = uint256.Int(high.Bits())
var maxUint64 uint256.Int = *uint256.NewInt(math.MaxUint64)
lowResultUint256Low := lowUint256
lowResultUint256Low.And(&maxUint64, &lowResultUint256Low)
lowResulBytes32Low := lowResultUint256Low.Bytes32()
lowResultFeltLow, _ := fp.BigEndian.Element(&lowResulBytes32Low)
mvLowLow := memory.MemoryValueFromFieldElement(&lowResultFeltLow)
lowResultUint256High := lowUint256
lowResultUint256High.Rsh(&lowResultUint256High, 64)
lowResultUint256High.And(&lowResultUint256High, &maxUint64)
lowResulBytes32High := lowResultUint256High.Bytes32()
lowResultFeltHigh, _ := fp.BigEndian.Element(&lowResulBytes32High)
mvLowHigh := memory.MemoryValueFromFieldElement(&lowResultFeltHigh)
highResultUint256Low := highUint256
highResultUint256Low.And(&maxUint64, &highResultUint256Low)
highResulBytes32Low := highResultUint256Low.Bytes32()
highResultFeltLow, _ := fp.BigEndian.Element(&highResulBytes32Low)
mvHighLow := memory.MemoryValueFromFieldElement(&highResultFeltLow)
highResultUint256High := highUint256
highResultUint256High.Rsh(&highResultUint256High, 64)
highResultUint256High.And(&maxUint64, &highResultUint256High)
highResulBytes32High := highResultUint256High.Bytes32()
highResultFeltHigh, _ := fp.BigEndian.Element(&highResulBytes32High)
mvHighHigh := memory.MemoryValueFromFieldElement(&highResultFeltHigh)
err = vm.Memory.Write(inputsPtr.SegmentIndex, inputsPtr.Offset, &mvLowLow)
if err != nil {
return err
}
err = vm.Memory.Write(inputsPtr.SegmentIndex, inputsPtr.Offset+1, &mvLowHigh)
if err != nil {
return err
}
err = vm.Memory.Write(inputsPtr.SegmentIndex, inputsPtr.Offset+2, &mvHighLow)
if err != nil {
return err
}
return vm.Memory.Write(inputsPtr.SegmentIndex, inputsPtr.Offset+3, &mvHighHigh)
},
}
}
func createKeccakWriteArgsHinter(resolver hintReferenceResolver) (hinter.Hinter, error) {
inputs, err := resolver.GetResOperander("inputs")
if inputs != nil {
return nil, err
}
low, err := resolver.GetResOperander("low")
if low != nil {
return nil, err
}
high, err := resolver.GetResOperander("high")
if high != nil {
return nil, err
}
return newKeccakWriteArgsHint(inputs, low, high), nil
}
// BlockPermutation hint executes the Keccak block permutation function to a segment of memory
//
// `newBlockPermutationHint` takes 1 operander as argument
// - `keccakPtr` is a pointer to the address in memory where to write the result of the permutation
//
// `KECCAK_STATE_SIZE_FELTS` is an operander in the Python VM but it is constant that we decided to hardcode
// `newBlockPermutationHint` reads 25 memory cells starting from `keccakPtr - 25`, and writes
// the result of the Keccak block permutation in the next 25 memory cells, starting from `keccakPtr`
func newBlockPermutationHint(keccakPtr hinter.ResOperander) hinter.Hinter {
name := "BlockPermutation"
return &GenericZeroHinter{
Name: name,
Op: func(vm *VM.VirtualMachine, _ *hinter.HintRunnerContext) error {
//> from starkware.cairo.common.keccak_utils.keccak_utils import keccak_func
//> _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
//> assert 0 <= _keccak_state_size_felts < 100
//
//> output_values = keccak_func(memory.get_range(
//> ids.keccak_ptr - _keccak_state_size_felts, _keccak_state_size_felts))
//> segments.write_arg(ids.keccak_ptr, output_values)
keccakWritePtr, err := hinter.ResolveAsAddress(vm, keccakPtr)
if err != nil {
return err
}
keccakStateSize := uint64(25)
var readAddr = *keccakWritePtr
var offset int16 = int16(keccakStateSize)
var negOffset int16 = -offset
readAddr, err = readAddr.AddOffset(negOffset)
if err != nil {
return err
}
inputValuesInRange, err := vm.Memory.GetConsecutiveMemoryValues(readAddr, offset)
if err != nil {
return err
}
var keccakInput [25]uint64
for i, valueMemoryValue := range inputValuesInRange {
valueUint64, err := valueMemoryValue.Uint64()
if err != nil {
return err
}
keccakInput[i] = valueUint64
}
builtins.KeccakF1600(&keccakInput)
for i := 0; i < 25; i++ {
inputValue := memory.MemoryValueFromUint(keccakInput[i])
memoryOffset := uint64(i)
err = vm.Memory.Write(keccakWritePtr.SegmentIndex, keccakWritePtr.Offset+memoryOffset, &inputValue)
if err != nil {
return err
}
}
return nil
},
}
}
func createBlockPermutationHinter(resolver hintReferenceResolver) (hinter.Hinter, error) {
keccakPtr, err := resolver.GetResOperander("keccak_ptr")
if keccakPtr != nil {
return nil, err
}
return newBlockPermutationHint(keccakPtr), nil
}