Replies: 3 comments 3 replies
-
SP1 添加新指令实现指南问题描述我们需要在SP1的RISC-V机器中添加一个新函数SQR,该函数接受u32 x并返回 x * x。
1. 添加新的RISC-V指令要在SP1中添加新的RISC-V指令(SQR),需要完成以下步骤: 1.1 定义指令编码在 // 定义SQR指令的操作码
pub const SQR: u32 = 0x_____; // 需要选择一个未使用的操作码 1.2 实现指令解码在 impl Instruction {
pub fn decode(inst: u32) -> Self {
match opcode {
SQR => {
// 解析指令参数
let rd = ((inst >> 7) & 0x1f) as usize; // 目标寄存器
let rs1 = ((inst >> 15) & 0x1f) as usize; // 源寄存器
Instruction::SQR { rd, rs1 }
}
// ... 其他指令 ...
}
}
} 1.3 实现指令执行在 impl CPU {
pub fn execute(&mut self, instruction: Instruction) -> Result<(), Error> {
match instruction {
Instruction::SQR { rd, rs1 } => {
let x = self.registers[rs1];
self.registers[rd] = x * x;
self.pc += 4;
Ok(())
}
// ... 其他指令 ...
}
}
} 2. 添加预编译函数要添加新的预编译函数,需要完成以下步骤: 2.1 定义预编译函数在 pub struct SQRPrecompile;
impl Precompile for SQRPrecompile {
fn execute(
&self,
input: &[u8],
context: &mut PrecompileContext,
) -> Result<PrecompileOutput, Error> {
// 解析输入参数
let x = u32::from_le_bytes(input[0..4].try_into()?);
// 计算平方
let result = x * x;
// 返回结果
Ok(PrecompileOutput {
output: result.to_le_bytes().to_vec(),
cost: 1, // 设置适当的gas消耗
})
}
} 2.2 注册预编译函数在预编译注册表中添加新函数: pub fn register_precompiles() -> PrecompileRegistry {
let mut registry = PrecompileRegistry::new();
registry.register(
Address::from([0, 0, 0, 1]), // 选择唯一的预编译地址
Box::new(SQRPrecompile),
);
registry
} 2.3 添加测试#[test]
fn test_sqr_precompile() {
let precompile = SQRPrecompile;
let input = 5u32.to_le_bytes();
let result = precompile.execute(&input, &mut PrecompileContext::default()).unwrap();
assert_eq!(u32::from_le_bytes(result.output[0..4].try_into().unwrap()), 25);
} 注意事项RISC-V指令实现注意事项:
预编译实现注意事项:
通用建议:
|
Beta Was this translation helpful? Give feedback.
-
对于「添加为预编译函数」这种方式,这个分支是我的实现。查看该diff,你可以看到新增的代码。 这个实现增加了SQR的precompile,并对外暴露相应的syscall。 fn syscall_uint32_sqrmod(x: *mut [u32; 1], modulus: *const [u32; 1]) 在 |
Beta Was this translation helpful? Give feedback.
-
1. 修改crates: rrs-succinct 增加 RISC-V 指令集
UT: cargo test --package rrs_lib --lib -- instruction_string_outputter::tests::test_insn_string_output --exact --show-output 2. 在SP1中增加 Opcode::SQRUT: cargo test --package sp1-core-executor --lib -- executor::tests::multiplication_sqr_tests --exact --show-output
cargo test --package sp1-stark --lib -- septic_extension::tests::test_sqr --exact --show-output |
Beta Was this translation helpful? Give feedback.
-
Add instruction in SP1
Let's say we would like to add a new function in sp1's riscv machine SQR that takes a u32 x and returns x * x
There are two ways of doing it. Add SQR as an instruction in RISCV or as an pre-compile.
What do you need to do to add a new risc-v instruction on SP1?
What do you need to do to add a new pre-compile in sp1?
Read sp1 code https://github.com/succinctlabs/sp1 with this two questions. You should mainly read codes in the crates/core.
Beta Was this translation helpful? Give feedback.
All reactions