Skip to content

Commit 8af5ae9

Browse files
authored
Merge pull request #9 from ethereum-optimism/tip/pcw109550/local-context
feat: Local Context
2 parents 51138bc + 6116ed8 commit 8af5ae9

File tree

8 files changed

+86
-28
lines changed

8 files changed

+86
-28
lines changed

rvgo/fast/evm.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ package fast
33
import "github.com/ethereum/go-ethereum/crypto"
44

55
var (
6-
StepBytes4 = crypto.Keccak256([]byte("step(bytes,bytes)"))[:4]
6+
StepBytes4 = crypto.Keccak256([]byte("step(bytes,bytes,bytes32)"))[:4]
77
CheatBytes4 = crypto.Keccak256([]byte("cheat(uint256,bytes32,bytes32,uint256)"))[:4]
8+
CheatLocalKeyBytes4 = crypto.Keccak256([]byte("cheatLocalKey(uint256,bytes32,bytes32,uint256,bytes32)"))[:4]
89
LoadKeccak256PreimagePartBytes4 = crypto.Keccak256([]byte("loadKeccak256PreimagePart(uint256,bytes)"))[:4]
910
)

rvgo/fast/witness.go

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@ import (
55
"errors"
66
"fmt"
77

8-
"github.com/ethereum-optimism/optimism/op-preimage"
8+
preimage "github.com/ethereum-optimism/optimism/op-preimage"
9+
"github.com/ethereum/go-ethereum/common"
910
)
1011

12+
type LocalContext common.Hash
13+
1114
type StepWitness struct {
1215
// encoded state witness
1316
State []byte
@@ -25,29 +28,35 @@ func uint64ToBytes32(v uint64) []byte {
2528
return out[:]
2629
}
2730

28-
func (wit *StepWitness) EncodeStepInput() []byte {
31+
func (wit *StepWitness) EncodeStepInput(localContext LocalContext) []byte {
2932
abiStatePadding := (32 - (uint64(len(wit.State)) % 32)) % 32
33+
abiProofPadding := (32 - (uint64(len(wit.MemProof)) % 32)) % 32
3034

3135
var input []byte
3236
input = append(input, StepBytes4...)
33-
input = append(input, uint64ToBytes32(32*2)...) // state data offset in bytes
34-
input = append(input, uint64ToBytes32(32*2+32+uint64(len(wit.State))+abiStatePadding)...) // proof data offset in bytes
35-
// TODO pad state data to multiple of 32 bytes
36-
// TODO also pad proof data
37-
38-
input = append(input, uint64ToBytes32(uint64(len(wit.State)))...) // state data length in bytes
37+
// state data offset in bytes
38+
input = append(input, uint64ToBytes32(32*3)...)
39+
// proof data offset in bytes
40+
input = append(input, uint64ToBytes32(32*3+32+uint64(len(wit.State))+abiStatePadding)...)
41+
// local context in bytes
42+
input = append(input, common.Hash(localContext).Bytes()...)
43+
44+
// state data length in bytes
45+
input = append(input, uint64ToBytes32(uint64(len(wit.State)))...)
3946
input = append(input, wit.State[:]...)
4047
input = append(input, make([]byte, abiStatePadding)...)
41-
input = append(input, uint64ToBytes32(uint64(len(wit.MemProof)))...) // proof data length in bytes
48+
// proof data length in bytes
49+
input = append(input, uint64ToBytes32(uint64(len(wit.MemProof)))...)
4250
input = append(input, wit.MemProof[:]...)
51+
input = append(input, make([]byte, abiProofPadding)...)
4352
return input
4453
}
4554

4655
func (wit *StepWitness) HasPreimage() bool {
4756
return wit.PreimageKey != ([32]byte{})
4857
}
4958

50-
func (wit *StepWitness) EncodePreimageOracleInput() ([]byte, error) {
59+
func (wit *StepWitness) EncodePreimageOracleInput(localContext LocalContext) ([]byte, error) {
5160
if wit.PreimageKey == ([32]byte{}) {
5261
return nil, errors.New("cannot encode pre-image oracle input, witness has no pre-image to proof")
5362
}
@@ -59,13 +68,14 @@ func (wit *StepWitness) EncodePreimageOracleInput() ([]byte, error) {
5968
// In production usage there should be an on-chain contract that exposes this,
6069
// rather than going through the global keccak256 oracle.
6170
var input []byte
62-
input = append(input, CheatBytes4...)
71+
input = append(input, CheatLocalKeyBytes4...)
6372
input = append(input, uint64ToBytes32(wit.PreimageOffset)...)
6473
input = append(input, wit.PreimageKey[:]...)
6574
var tmp [32]byte
6675
copy(tmp[:], wit.PreimageValue[wit.PreimageOffset:])
6776
input = append(input, tmp[:]...)
6877
input = append(input, uint64ToBytes32(uint64(len(wit.PreimageValue))-8)...)
78+
input = append(input, common.Hash(localContext).Bytes()...)
6979
// Note: we can pad calldata to 32 byte multiple, but don't strictly have to
7080
return input, nil
7181
case preimage.Keccak256KeyType:

rvgo/slow/vm.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package slow
33
import (
44
"encoding/binary"
55
"fmt"
6+
67
"github.com/ethereum/go-ethereum/common"
78
"github.com/ethereum/go-ethereum/crypto"
89
)
@@ -103,8 +104,8 @@ func Step(calldata []byte, po PreimageOracle) (stateHash common.Hash, outErr err
103104

104105
// TODO: validate abi offset values?
105106

106-
stateContentOffset := uint8(4 + 32 + 32 + 32)
107-
if iszero(eq(b32asBEWord(calldataload(toU64(4+32*2))), shortToU256(stateSize))) {
107+
stateContentOffset := uint8(4 + 32 + 32 + 32 + 32)
108+
if iszero(eq(b32asBEWord(calldataload(toU64(4+32*3))), shortToU256(stateSize))) {
108109
// user-provided state size must match expected state size
109110
panic("invalid state size input")
110111
}

rvgo/test/evm_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,13 @@ func stepEVM(t *testing.T, env *vm.EVM, wit *fast.StepWitness, addrs *Addresses,
149149
snap := env.StateDB.Snapshot()
150150

151151
if wit.HasPreimage() {
152-
input, err := wit.EncodePreimageOracleInput()
152+
input, err := wit.EncodePreimageOracleInput(fast.LocalContext{})
153153
require.NoError(t, err)
154154
ret, leftOverGas, err := env.Call(vm.AccountRef(addrs.Sender), addrs.Oracle, input, startingGas, big.NewInt(0))
155155
require.NoError(t, err, "evm must not fail (ret: %x, gas: %d)", ret, startingGas-leftOverGas)
156156
}
157157

158-
input := wit.EncodeStepInput()
158+
input := wit.EncodeStepInput(fast.LocalContext{})
159159

160160
ret, leftOverGas, err := env.Call(vm.AccountRef(addrs.Sender), addrs.RISCV, input, startingGas, big.NewInt(0))
161161
require.NoError(t, err, "evm must not fail (ret: %x), at step %d", ret, step)

rvgo/test/vm_go_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ func fullTest(t *testing.T, vmState *fast.VMState, po *testOracle, symbols fast.
108108
require.NoError(t, err)
109109

110110
if runSlow {
111-
slowPostHash, err := slow.Step(wit.EncodeStepInput(), po)
111+
slowPostHash, err := slow.Step(wit.EncodeStepInput(fast.LocalContext{}), po)
112112
require.NoErrorf(t, err, "slow VM err at step %d, PC %08x: %v", i, vmState.PC, err)
113113
require.Equal(t, fastStateHash, slowPostHash, "fast post-state must match slow post-state")
114114
}

rvgo/test/vm_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ func runSlowTestSuite(t *testing.T, path string) {
7575
require.NoError(t, err)
7676

7777
// Now run the same in slow mode
78-
input := wit.EncodeStepInput()
78+
input := wit.EncodeStepInput(fast.LocalContext{})
7979
post, err := slow.Step(input, nil)
8080
require.NoErrorf(t, err, "slow VM err at step %d, PC %08x: %v", i, vmState.PC, err)
8181

rvsol/src/PreimageOracle.sol

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,33 @@ contract PreimageOracle {
3232
preimageLengths[key] = size;
3333
}
3434

35+
// temporary method for localization. Will be removed to PreimageKeyLib.sol
36+
function localize(bytes32 _key, bytes32 _localContext) internal view returns (bytes32 localizedKey_) {
37+
assembly {
38+
// Grab the current free memory pointer to restore later.
39+
let ptr := mload(0x40)
40+
// Store the local data key and caller next to each other in memory for hashing.
41+
mstore(0, _key)
42+
mstore(0x20, caller())
43+
mstore(0x40, _localContext)
44+
// Localize the key with the above `localize` operation.
45+
localizedKey_ := or(and(keccak256(0, 0x60), not(shl(248, 0xFF))), shl(248, 1))
46+
// Restore the free memory pointer.
47+
mstore(0x40, ptr)
48+
}
49+
}
50+
51+
// temporary method for localization. Will be removed to PreimageKeyLib.sol
52+
function cheatLocalKey(uint256 partOffset, bytes32 key, bytes32 part, uint256 size, bytes32 localContext) external {
53+
// sanity check key is local key using prefix
54+
require(uint8(key[0]) == 1, "must be used for local key");
55+
56+
bytes32 localizedKey = localize(key, localContext);
57+
preimagePartOk[localizedKey][partOffset] = true;
58+
preimageParts[localizedKey][partOffset] = part;
59+
preimageLengths[localizedKey] = size;
60+
}
61+
3562
// loadKeccak256PreimagePart prepares the pre-image to be read by keccak256 key,
3663
// starting at the given offset, up to 32 bytes (clipped at preimage length, if out of data).
3764
function loadKeccak256PreimagePart(uint256 _partOffset, bytes calldata _preimage) external {

rvsol/src/Step.sol

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ contract Step {
1111
}
1212

1313
// Executes a single RISC-V instruction, starting from
14-
function step(bytes calldata stateData, bytes calldata proof) public returns (bytes32) {
14+
function step(bytes calldata stateData, bytes calldata proof, bytes32 localContext) public returns (bytes32) {
1515
assembly {
1616
function revertWithCode(code) {
1717
mstore(0, code)
@@ -270,8 +270,8 @@ contract Step {
270270
// expected memory check: no allocated memory (start after scratch + free-mem-ptr + zero slot = 0x80)
271271
revert(0, 0)
272272
}
273-
if iszero(eq(stateData.offset, 100)) {
274-
// 32*3+4 = 100 expected state data offset
273+
if iszero(eq(stateData.offset, 132)) {
274+
// 32*4+4 = 132 expected state data offset
275275
revert(0, 0)
276276
}
277277
if iszero(eq(calldataload(sub(stateData.offset, 32)), stateSize())) {
@@ -283,11 +283,12 @@ contract Step {
283283
out := add(v, padding)
284284
}
285285
if iszero(eq(proof.offset, add(add(stateData.offset, paddedLen(stateSize())), 32))) {
286-
// 100+stateSize+padding+32 = expected proof offset
286+
// 132+stateSize+padding+32 = expected proof offset
287287
revert(0, 0)
288288
}
289289
function proofContentOffset() -> out { // since we can't reference proof.offset in functions, blame Yul
290-
out := 516
290+
// 132+362+(32-362%32)+32=548
291+
out := 548
291292
}
292293
if iszero(eq(proof.offset, proofContentOffset())) {
293294
revert(0, 0)
@@ -772,10 +773,28 @@ contract Step {
772773
revertWithCode(0xbadf00d0)
773774
}
774775

775-
function readPreimageValue(addr, count) -> out {
776+
function localize(preImageKey, localContext_) -> localizedKey {
777+
// TODO: deduplicate definition of localize using lib
778+
// Grab the current free memory pointer to restore later.
779+
let ptr := mload(0x40)
780+
// Store the local data key and caller next to each other in memory for hashing.
781+
mstore(0, preImageKey)
782+
mstore(0x20, caller())
783+
mstore(0x40, localContext_)
784+
// Localize the key with the above `localize` operation.
785+
localizedKey := or(and(keccak256(0, 0x60), not(shl(248, 0xFF))), shl(248, 1))
786+
// Restore the free memory pointer.
787+
mstore(0x40, ptr)
788+
}
789+
790+
function readPreimageValue(addr, count, localContext_) -> out {
776791
let preImageKey := getPreimageKey()
777792
let offset := getPreimageOffset()
778-
793+
// If the preimage key is a local key, localize it in the context of the caller.
794+
let preImageKeyPrefix := shr(248, preImageKey) // 256-8=248
795+
if eq(preImageKeyPrefix, 1) {
796+
preImageKey := localize(preImageKey, localContext_)
797+
}
779798
// make call to pre-image oracle contract
780799
let pdatB32, pdatlen := readPreimagePart(preImageKey, offset)
781800
if iszero64(pdatlen) { // EOF
@@ -811,7 +830,7 @@ contract Step {
811830
//
812831
// Syscall handling
813832
//
814-
function sysCall() {
833+
function sysCall(localContext_) {
815834
let a7 := getRegister(toU64(17))
816835
switch a7
817836
case 93 { // exit the calling thread. No multi-thread support yet, so just exit.
@@ -872,7 +891,7 @@ contract Step {
872891
n := count
873892
errCode := toU64(0)
874893
} case 5 { // preimage read
875-
n := readPreimageValue(addr, count)
894+
n := readPreimageValue(addr, count, localContext_)
876895
errCode := toU64(0)
877896
} default {
878897
n := u64Mask() // -1 (reading error)
@@ -1275,7 +1294,7 @@ contract Step {
12751294
case 0 { // 000 = ECALL/EBREAK
12761295
switch shr64(toU64(20), instr) // I-type, top 12 bits
12771296
case 0 { // imm12 = 000000000000 ECALL
1278-
sysCall()
1297+
sysCall(localContext)
12791298
setPC(add64(_pc, toU64(4)))
12801299
} default { // imm12 = 000000000001 EBREAK
12811300
setPC(add64(_pc, toU64(4))) // ignore breakpoint

0 commit comments

Comments
 (0)