@@ -21,14 +21,72 @@ package crypto
2121import (
2222 "github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime"
2323 "github.com/ethereum/go-ethereum/common"
24- "golang.org/x/crypto/sha3"
2524)
2625
26+ // zirenKeccakState implements the KeccakState interface using the Ziren zkvm_runtime.
27+ // It accumulates data written to it and uses the zkvm's Keccak256 system call for hashing.
28+ type zirenKeccakState struct {
29+ buf []byte // accumulated data
30+ result []byte // cached result
31+ dirty bool // whether new data has been written since last hash
32+ }
33+
34+ func newZirenKeccakState () KeccakState {
35+ return & zirenKeccakState {
36+ buf : make ([]byte , 0 , 512 ), // pre-allocate reasonable capacity
37+ }
38+ }
39+
40+ func (s * zirenKeccakState ) Write (p []byte ) (n int , err error ) {
41+ s .buf = append (s .buf , p ... )
42+ s .dirty = true
43+ return len (p ), nil
44+ }
45+
46+ func (s * zirenKeccakState ) Sum (b []byte ) []byte {
47+ s .computeHashIfNeeded ()
48+ return append (b , s .result ... )
49+ }
50+
51+ func (s * zirenKeccakState ) Reset () {
52+ s .buf = s .buf [:0 ]
53+ s .result = nil
54+ s .dirty = false
55+ }
56+
57+ func (s * zirenKeccakState ) Size () int {
58+ return 32
59+ }
60+
61+ func (s * zirenKeccakState ) BlockSize () int {
62+ return 136 // Keccak256 rate
63+ }
64+
65+ func (s * zirenKeccakState ) Read (p []byte ) (n int , err error ) {
66+ s .computeHashIfNeeded ()
67+
68+ if len (p ) == 0 {
69+ return 0 , nil
70+ }
71+
72+ // After computeHashIfNeeded(), s.result is always a 32-byte slice
73+ n = copy (p , s .result )
74+ return n , nil
75+ }
76+
77+ func (s * zirenKeccakState ) computeHashIfNeeded () {
78+ if s .dirty || s .result == nil {
79+ // Use the zkvm_runtime Keccak256 which uses SyscallKeccakSponge
80+ hashArray := zkvm_runtime .Keccak256 (s .buf )
81+ s .result = hashArray [:]
82+ s .dirty = false
83+ }
84+ }
85+
2786// NewKeccakState creates a new KeccakState
28- // For now, we fallback to the original implementation for the stateful interface.
29- // TODO: Implement a stateful wrapper around zkvm_runtime.Keccak256 if needed.
87+ // This uses a Ziren-optimized implementation that leverages the zkvm_runtime.Keccak256 system call.
3088func NewKeccakState () KeccakState {
31- return sha3 . NewLegacyKeccak256 ().( KeccakState )
89+ return newZirenKeccakState ( )
3290}
3391
3492// Keccak256 calculates and returns the Keccak256 hash using the Ziren zkvm_runtime implementation.
0 commit comments