@@ -126,3 +126,54 @@ func (r *triedbRecorder) Update(
126126func (r * triedbRecorder ) Reader (_ common.Hash ) (database.Reader , error ) {
127127 return r .Database .Reader (common.Hash {})
128128}
129+
130+ type highByteFlipper struct {}
131+
132+ func flipHighByte (h common.Hash ) common.Hash {
133+ h [0 ] = ^ h [0 ]
134+ return h
135+ }
136+
137+ func (highByteFlipper ) TransformStateKey (_ common.Address , key common.Hash ) common.Hash {
138+ return flipHighByte (key )
139+ }
140+
141+ func TestTransformStateKey (t * testing.T ) {
142+ cache := NewDatabase (rawdb .NewMemoryDatabase ())
143+ sdb , err := New (types .EmptyRootHash , cache , nil )
144+ require .NoErrorf (t , err , "New()" )
145+
146+ addr := common.Address {1 }
147+ regularKey := common.Hash {0 , 'k' , 'e' , 'y' }
148+ flippedKey := flipHighByte (regularKey )
149+ regularVal := common.Hash {'r' , 'e' , 'g' , 'u' , 'l' , 'a' , 'r' }
150+ flippedVal := common.Hash {'f' , 'l' , 'i' , 'p' , 'p' , 'e' , 'd' }
151+
152+ sdb .SetState (addr , regularKey , regularVal )
153+ sdb .SetState (addr , flippedKey , flippedVal )
154+
155+ assertEq := func (t * testing.T , key , want common.Hash , opts ... stateconf.StateDBStateOption ) {
156+ t .Helper ()
157+ assert .Equal (t , want , sdb .GetState (addr , key , opts ... ))
158+ }
159+
160+ assertEq (t , regularKey , regularVal )
161+ assertEq (t , flippedKey , flippedVal )
162+
163+ // Typically the hook would be registered before any state access or
164+ // setting, but doing it here aids testing by showing the before-and-after
165+ // effects.
166+ RegisterExtras (highByteFlipper {})
167+ t .Cleanup (TestOnlyClearRegisteredExtras )
168+
169+ noTransform := stateconf .SkipStateKeyTransformation ()
170+ assertEq (t , regularKey , flippedVal )
171+ assertEq (t , regularKey , regularVal , noTransform )
172+ assertEq (t , flippedKey , regularVal )
173+ assertEq (t , flippedKey , flippedVal , noTransform )
174+
175+ updatedVal := common.Hash {'u' , 'p' , 'd' , 'a' , 't' , 'e' , 'd' }
176+ sdb .SetState (addr , regularKey , updatedVal )
177+ assertEq (t , regularKey , updatedVal )
178+ assertEq (t , flippedKey , updatedVal , noTransform )
179+ }
0 commit comments