Skip to content

Commit

Permalink
docs(synthesizer): translate comments to English
Browse files Browse the repository at this point in the history
  • Loading branch information
SonYoungsung committed Jan 30, 2025
1 parent 42db8d2 commit a4a2be9
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 4,352 deletions.

This file was deleted.

This file was deleted.

9 changes: 6 additions & 3 deletions packages/frontend/synthesizer/src/evm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,9 +145,12 @@ export class EVM implements EVMInterface {
protected readonly _emit: (topic: string, data: any) => Promise<void>

private _bn254: EVMBN254Interface
// EVM에서 synthesizer를 생성하고, interpreter가 runState를 구성할 때 이를 상속받아 사용함.
// 결과적으로 CALL류 실행을 통해 하위 컨텍스트들이 구성될 때, 모든 컨텍스트에서 EVM에서 생성된 synthesizer가 공유됨.
// 이를 위해 interpreter의 constructor의 인자에 synthesizer를 추가하였음.
/**
* Synthesizer is created in EVM and inherited by interpreter when constructing runState.
* As a result, when sub-contexts are created through CALL-type executions,
* the synthesizer created in EVM is shared across all contexts.
* For this purpose, synthesizer was added as an argument to the interpreter's constructor.
*/
public synthesizer: Synthesizer

/**
Expand Down
21 changes: 9 additions & 12 deletions packages/frontend/synthesizer/src/interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,15 +431,12 @@ export class Interpreter {
// Execute opcode handler
const opFn = opEntry.opHandler


// 2. 일반 opcode 실행
if (opInfo.isAsync) {
await (opFn as AsyncOpHandler).apply(null, [this._runState, this.common])
} else {
opFn.apply(null, [this._runState, this.common])
}


// 2. Execute normal opcode
if (opInfo.isAsync) {
await (opFn as AsyncOpHandler).apply(null, [this._runState, this.common])
} else {
opFn.apply(null, [this._runState, this.common])
}
} finally {
if (this.profilerOpts?.enabled === true) {
this.performanceLogger.stopTimer(
Expand Down Expand Up @@ -505,7 +502,7 @@ export class Interpreter {
} else {
console.log(`Invalid command. Please type "${targetCommand}" to proceed.`)
rl.close()
waitForCommand(targetCommand).then(resolve) // 다시 대기
waitForCommand(targetCommand).then(resolve) // wait again
}
})
})
Expand Down Expand Up @@ -866,7 +863,7 @@ export class Interpreter {
}

/**
* Returns the blocks number.
* Returns the block's number.
*/
getBlockNumber(): bigint {
return this._env.block.header.number
Expand Down Expand Up @@ -1027,7 +1024,7 @@ export class Interpreter {
}

/**
* Message-call into this account with an alternative accounts code, but
* Message-call into this account with an alternative account's code, but
* persisting the current values for sender and value.
*/
async callDelegate(
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend/synthesizer/src/opcodes/codes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ export type OpcodeMapEntry = {
opHandler: OpHandler
gasHandler: AsyncDynamicGasHandler | SyncDynamicGasHandler
/**
* @todo: synthesizerHandler 추가 필요
* @todo: Need to add synthesizerHandler
*/
// synthesizerHandler: SynthesizerHandler
}
Expand Down Expand Up @@ -491,7 +491,7 @@ export function getOpcodesForHF(common: Common, customOpcodes?: CustomOpcode[]):
const dynamicGas = dynamicGasHandlersCopy.get(opNumber)!
const handler = handlersCopy.get(opNumber)!
/**
* @todo: synthesizerHandler 추가 필요
* @todo: Need to add synthesizerHandler
*/
// const synthesizerHandler = synthesizerHandlers.get(opNumber)!
// const subcircuitCode = subcircuits.find((entry) => parseInt(entry.opcode, 16) === opNumber)
Expand Down
28 changes: 14 additions & 14 deletions packages/frontend/synthesizer/src/opcodes/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1202,10 +1202,10 @@ export const handlers: Map<number, OpHandler> = new Map([
const dataPt = runState.stackPt.peek(2)[1]
const memPt = runState.synthesizer.placeMSTORE(dataPt, truncSize)
if (truncSize < dataPt.sourceSize) {
// StackPt에서 dataPt를 변형을 추적 memPt로 교체해 줍니다.
// Replace dataPt in StackPt with the tracked memPt
runState.stackPt.swap(1)
runState.stackPt.pop() // 기존 dataPt를 버립니다.
runState.stackPt.push(memPt) // 변형된 dataPt를 넣습니다.
runState.stackPt.pop() // Discard the original dataPt
runState.stackPt.push(memPt) // Replace dataPt in StackPt with the tracked memPt
runState.stackPt.swap(1)
}
const [offsetPt, newDataPt] = runState.stackPt.popN(2)
Expand Down Expand Up @@ -1242,18 +1242,18 @@ export const handlers: Map<number, OpHandler> = new Map([
runState.memory.write(offsetNum, 1, buf)

// For Synthesizer //
const truncSize = 1 // MSTORE8은 최하위 1바이트만을 저장하고, 상위 바이트는 버림.
const dataPt = runState.stackPt.peek(2)[1] // StackPt에서 최상위 두번째 포인터를 리턴 (stack.ts 참고)
// 데이터의 변형을 추적하면서 동시에 Placements에도 반영 해 줍니다.
const truncSize = 1 // MSTORE8 stores only the lowest byte and discards the higher bytes
const dataPt = runState.stackPt.peek(2)[1] // Return the top second pointer from StackPt (refer to stack.ts)
// Track data modifications and reflect them in Placements
const memPt = runState.synthesizer.placeMSTORE(dataPt, truncSize)
if (truncSize < dataPt.sourceSize) {
// StackPt에서 dataPt를 변형을 추적 memPt로 교체해 줍니다.
// Replace dataPt in StackPt with the tracked memPt
runState.stackPt.swap(1)
runState.stackPt.pop() // 기존 dataPt를 버립니다.
runState.stackPt.push(memPt) // 변형된 dataPt를 넣습니다.
runState.stackPt.pop() // Discard the original dataPt
runState.stackPt.push(memPt) // Replace dataPt in StackPt with the tracked memPt
runState.stackPt.swap(1)
}
// 이제 일반적인 MSTORE 연산을 수행합니다
// Now perform the usual MSTORE operation
const [offsetPt, newDataPt] = runState.stackPt.popN(2)
const _offsetNum = Number(offsetPt.value)
if (_offsetNum !== offsetNum || newDataPt.value !== bytesToBigInt(buf)) {
Expand Down Expand Up @@ -2059,7 +2059,7 @@ export const handlers: Map<number, OpHandler> = new Map([
calldataMemoryPts,
)

// Synthesizer를 위해 writeCallOutput을 수정하였음 (Write the return data on the memory)
// Modified writeCallOutput for Synthesizer (Write the return data on the memory)
writeCallOutput(runState, outOffset, outLength)
runState.stack.push(ret)
},
Expand Down Expand Up @@ -2118,7 +2118,7 @@ export const handlers: Map<number, OpHandler> = new Map([
calldataMemoryPts,
)

// Synthesizer를 위해 writeCallOutput을 수정하였음 (Write the return data on the memory)
// Modified writeCallOutput for Synthesizer (Write the return data on the memory)
writeCallOutput(runState, outOffset, outLength)
runState.stack.push(ret)
},
Expand Down Expand Up @@ -2172,7 +2172,7 @@ export const handlers: Map<number, OpHandler> = new Map([
calldataMemoryPts,
)

// Synthesizer를 위해 writeCallOutput을 수정하였음 (Write the return data on the memory)
// Modified writeCallOutput for Synthesizer (Write the return data on the memory)
writeCallOutput(runState, outOffset, outLength)
runState.stack.push(ret)
},
Expand Down Expand Up @@ -2310,7 +2310,7 @@ export const handlers: Map<number, OpHandler> = new Map([
calldataMemoryPts,
)

// Synthesizer를 위해 writeCallOutput을 수정하였음 (Write the return data on the memory)
// Modified writeCallOutput for Synthesizer (Write the return data on the memory)
writeCallOutput(runState, outOffset, outLength)
runState.stack.push(ret)
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ export const synthesizerHandlers: Map<number, SynthesizerHandler> = new Map([
} else {
r = fromTwos(a.value) % fromTwos(b.value)
}
// SMOD 연산의 결과를 2의 보수 표현으로 변환하여 EVM의 256비트 부호 없는 정수로 처리
// EVM은 모든 값을 부호 없는 256비트 정수로 처리하므로, 음수 결과를 올바르게 변환하기 위해 필요
// toTwos(r)를 사용하여 음수 결과를 2의 보수로 변환함으로써, SMOD 연산이 예상대로 작동하도록 보장
// Convert SMOD operation result to two's complement representation for EVM's 256-bit unsigned integer
// Required to properly handle negative results since EVM processes all values as unsigned 256-bit integers
// Using toTwos(r) to convert negative results to two's complement ensures SMOD operation works as expected
synthesizerArith('SMOD', [a.value, b.value], toTwos(r), runState)
}],

Expand Down
6 changes: 3 additions & 3 deletions packages/frontend/synthesizer/src/tokamak/core/finalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const halveWordSizeOfWires = (newDataPts: DataPt[], prevDataPt: DataPt, index: n
newDataPts[Number(indLow)].pairedInputWireIndices = prevDataPt.pairedInputWireIndices.flatMap(convertIndices)
}

// value가 문자열로 들어올 경우를 대비
// Handle cases where value comes as a string
const value = typeof prevDataPt.value === 'string' ? BigInt(prevDataPt.value) : prevDataPt.value

newDataPts[Number(indHigh)].value = value >> 128n
Expand Down Expand Up @@ -464,5 +464,5 @@ const testInstances = async (instances: PlacementInstances): Promise<void> => {
console.log(`Synthesizer: Instances passed subcircuits.`)
}

// Todo: permutationY와 permutationZ의 내용 압축해서 내보내기.
// Todo: WireFlattenMap과 Inverse를 buildQAP에서 수행하고 내용 압축해서 내보내고, 여기선 그걸 불러오기
// Todo: Export compressed content of permutationY and permutationZ
// Todo: Execute WireFlattenMap and Inverse in buildQAP, export compressed content, and load it here
18 changes: 9 additions & 9 deletions packages/frontend/synthesizer/src/tokamak/core/synthesizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ export async function synthesizerEnvInf(
target?: bigint,
offset?: bigint,
): Promise<void> {
// Environment information을 Stack에 load하는 경우만 다룹니다. 그 외의 경우 (~COPY)는 functionst.ts에서 직접 처리 합니다.
// Handles only cases where Environment information is loaded to Stack. Other cases (~COPY) are handled directly in functionst.ts.
let dataPt: DataPt
switch (op) {
case 'CALLDATALOAD': {
Expand Down Expand Up @@ -511,7 +511,7 @@ export class Synthesizer {
}

public loadKeccak(inPts: DataPt[], outValue: bigint, length?: bigint): DataPt {
// 연산 실행
// Execute operation
const nChunks = inPts.length
let value = BIGINT_0
for (let i = 0; i < nChunks; i++) {
Expand Down Expand Up @@ -644,7 +644,7 @@ export class Synthesizer {


/**
@todo: newDataPt size 변수 검증 필요
@todo: Validation needed for newDataPt size variable
*/
private static readonly REQUIRED_INPUTS: Partial<Record<string, number>> = {
ADDMOD: 3,
Expand All @@ -655,7 +655,7 @@ export class Synthesizer {
SubEXP: 3,
} as const
private validateOperation(name: ArithmeticOperator, inPts: DataPt[]): void {
// 기본값은 2, 예외적인 경우만 REQUIRED_INPUTS에서 확인
// Default is 2, check REQUIRED_INPUTS only for exceptional cases
const requiredInputs = Synthesizer.REQUIRED_INPUTS[name] ?? 2
SynthesizerValidator.validateInputCount(name, inPts.length, requiredInputs)
SynthesizerValidator.validateInputs(inPts)
Expand All @@ -678,20 +678,20 @@ export class Synthesizer {

private handleBinaryOp(name: ArithmeticOperator, inPts: DataPt[]): DataPt[] {
try {
// 1. 입력값 검증
// 1. Validate inputs
this.validateOperation(name, inPts)

// 2. 연산 실행
// 2. Execute operation
const values = inPts.map((pt) => pt.value)
const outValue = this.executeOperation(name, values)

// 3. 출력값 생성
// 3. Generate output
let wireIndex = 0
const outPts = Array.isArray(outValue)
? outValue.map((value) => this.createOutputPoint(value, wireIndex++))
: [this.createOutputPoint(outValue)]

// 4. 배치 추가
// 4. Add placement
this._place(name, inPts, outPts)

return outPts
Expand Down Expand Up @@ -826,7 +826,7 @@ export class Synthesizer {
const { shift, dataPt } = info
let outPts = [dataPt]
if (Math.abs(shift) > 0) {
// shift 값과 shift 방향과의 관계는 MemoryPt에서 정의하였음
// The relationship between shift value and shift direction is defined in MemoryPt
const subcircuitName: ArithmeticOperator = shift > 0 ? 'SHL' : 'SHR'
const absShift = Math.abs(shift)
const inPts: DataPt[] = [this.loadAuxin(BigInt(absShift)), dataPt]
Expand Down
23 changes: 11 additions & 12 deletions packages/frontend/synthesizer/src/tokamak/operations/arithmetic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,17 @@ import type { ArithmeticOperator } from '../types/index.js'
export type ArithmeticFunction = (...args: bigint[]) => bigint | bigint[]

/**
/**
* Synthesizer 산술 연산을 처리하는 유틸리티 클래스
* Utility class for handling Synthesizer arithmetic operations
*/
export class ArithmeticOperations {
private static readonly MAX_UINT256 = (1n << 256n) - 1n
private static readonly SIGN_BIT = 1n << 255n
// const N은 opcodes/utils.ts 에서 복사해왔습니다. EXP에서 사용하는 모듈로인데, 왜 이 숫자를 사용하는지는 모르겠네요...
// N is 2^256, copied from opcodes/utils.ts. Used as modulo in EXP operations
private static readonly N =
BigInt(115792089237316195423570985008687907853269984665640564039457584007913129639936)

/**
* 기본 산술 연산
* Basic arithmetic operations
*/
static add(a: bigint, b: bigint): bigint {
return (a + b) & ArithmeticOperations.MAX_UINT256
Expand All @@ -43,7 +42,7 @@ export class ArithmeticOperations {
}

/**
* 모듈로 연산
* Modulo operations
*/
static mod(a: bigint, b: bigint): bigint {
return b === 0n ? 0n : a % b
Expand All @@ -69,7 +68,7 @@ export class ArithmeticOperations {

/**
* @deprecated
* 지수 연산
* Exponentiation operation
*/
static exp(base: bigint, exponent: bigint): bigint {
if (exponent === 0n) return 1n
Expand All @@ -90,7 +89,7 @@ export class ArithmeticOperations {
}

/**
* 비교 연산
* Comparison operations
*/
static lt(a: bigint, b: bigint): bigint {
return a < b ? 1n : 0n
Expand All @@ -117,7 +116,7 @@ export class ArithmeticOperations {
}

/**
* 비트 연산
* Bit operations
*/
static and(a: bigint, b: bigint): bigint {
return a & b
Expand All @@ -136,7 +135,7 @@ export class ArithmeticOperations {
}

/**
* 시프트 연산
* Shift operations
*/
static shl(shift: bigint, value: bigint): bigint {
return shift >= 256n ? 0n : (value << shift) & ArithmeticOperations.MAX_UINT256
Expand All @@ -162,7 +161,7 @@ export class ArithmeticOperations {
}

/**
* 바이트 연산
* Byte operations
*/
static byte(index: bigint, value: bigint): bigint {
if (index >= 32n) return 0n
Expand All @@ -171,7 +170,7 @@ export class ArithmeticOperations {
}

/**
* 부호 확장
* Sign extension
*/
static signextend(k: bigint, value: bigint): bigint {
if (k > 31n) return value
Expand Down Expand Up @@ -211,7 +210,7 @@ export class ArithmeticOperations {
}
}

// 연산자와 함수 매핑
// Operator and function mapping
export const OPERATION_MAPPING: Record<ArithmeticOperator, ArithmeticFunction> = {
ADD: ArithmeticOperations.add,
MUL: ArithmeticOperations.mul,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,12 +175,13 @@ export class MemoryPt {
}

/**
* Cleans up memory pointers when new data is written.
* If the newly written data completely overlaps existing data,
* delete the existing key-value pair.
*/
private _memPtCleanUp(newOffset: number, newSize: number) {
for (const [key, { memOffset: _offset, containerSize: _size }] of this._storePt) {
//새 데이터가 기존 데이터를 완전히 오버랩 하는 조건
// Condition where new data completely overlaps existing data
const _endOffset = _offset + _size - 1
const newEndOffset = newOffset + newSize - 1
if (_endOffset <= newEndOffset && _offset >= newOffset) {
Expand Down Expand Up @@ -267,9 +268,6 @@ export class MemoryPt {
* @returns {DataAliasInfos}
*/
getDataAlias(offset: number, size: number): DataAliasInfos {
// if (size > 32) {
// throw new Error(`The range of memory view exceeds 32 bytes. Try to chunk it in the Handlers.`)
// }
const dataAliasInfos: DataAliasInfos = []
const dataFragments = this._viewMemoryConflict(offset, size)

Expand All @@ -281,7 +279,7 @@ export class MemoryPt {
const viewEndOffset = offset + size - 1
dataAliasInfos.push({
dataPt: this._storePt.get(timeStamp)!.dataPt,
// shift가 양의 값이면 SHL, 음의 값이면 SHR
// shift is positive for SHL, negative for SHR
shift: (viewEndOffset - dataEndOffset) * 8,
masker: this._generateMasker(offset, size, _value.validRange),
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Synthesizer 관련 에러들을 정의하는 클래스들
* Classes defining Synthesizer-related errors
*/

export class SynthesizerError extends Error {
Expand Down

0 comments on commit a4a2be9

Please sign in to comment.