This commit is contained in:
2026-07-23 16:37:12 +02:00
parent 99c345f2f2
commit 0da75c1311
2159 changed files with 230833 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
# file: kb_executor_spl_elgamal_registry/Cargo.toml
# version: 3
[package]
name = "kb_executor_spl_elgamal_registry"
version.workspace = true
edition.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
base64.workspace = true
bytemuck.workspace = true
kb_core = { path = "../kb_core" }
kb_execution_api = { path = "../kb_execution_api" }
kb_model = { path = "../kb_model" }
kb_program_ids = { path = "../kb_program_ids" }
serde.workspace = true
serde_json.workspace = true
solana-instruction.workspace = true
solana-pubkey.workspace = true
solana-zk-elgamal-proof-interface.workspace = true
spl-elgamal-registry-interface.workspace = true
spl-token-confidential-transfer-proof-extraction.workspace = true
tracing.workspace = true
ts-rs.workspace = true
[lints]
workspace = true

View File

@@ -0,0 +1,6 @@
<!-- file: kb_executor_spl_elgamal_registry/README.md -->
<!-- version: 1 -->
# kb_executor_spl_elgamal_registry
Exécuteur typé du registre ElGamal SPL. Il construit `create_registry` et `update_registry` au moyen de l'interface officielle, avec preuve `PubkeyValidity` inline ou compte de contexte prévalidé. Toute exécution exige une simulation, une limite de frais positive et la validation canonique après envoi.

View File

@@ -0,0 +1,279 @@
// file: kb_executor_spl_elgamal_registry/src/builder.rs
// version: 4
//! Official registry builders and conservative plan validation.
use base64::Engine; // rust-rules: trait-import
use std::str::FromStr; // rust-rules: trait-import
pub(crate) fn build_prepared_plan(
intent: &crate::SplElgamalRegistryExecutionIntent,
) -> kb_core::Result<kb_execution_api::PreparedExecutionPlan> {
if intent.intent_id.trim().is_empty() {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_intent_id_empty",
"ElGamal registry execution intent id must not be empty",
));
}
if intent.policy.simulation != kb_execution_api::ExecutionSimulationPolicy::Required {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_simulation_required",
"ElGamal registry execution requires simulation",
));
}
match intent.policy.cost_limit.max_fee_lamports {
std::option::Option::Some(value) if value > 0 => {},
std::option::Option::Some(_) | std::option::Option::None => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_fee_limit_missing",
"ElGamal registry execution requires a positive fee ceiling",
));
},
}
let validation = &intent.policy.post_execution_validation;
if !validation.canonical_insert_required
|| !validation.core_extraction_required
|| !validation.decode_replay_required
|| !validation.materialization_required
{
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_post_validation_required",
"ElGamal registry execution requires canonical insert, core extraction, decode replay and materialization",
));
}
let fee_payer = match parse_address(&intent.fee_payer, "fee_payer") {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let (owner_model, proof, operation_code, create) = match &intent.operation {
crate::SplElgamalRegistryOperation::CreateRegistry { owner, proof } => {
(owner, proof, crate::CREATE_REGISTRY_OPERATION, true)
},
crate::SplElgamalRegistryOperation::UpdateRegistry { owner, proof } => {
(owner, proof, crate::UPDATE_REGISTRY_OPERATION, false)
},
};
let owner = match parse_address(owner_model, "owner") {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let instructions = match proof {
crate::SplElgamalRegistryProofLocation::ContextStateAccount { account } => {
let context = match parse_address(account, "context_state_account") {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let location = spl_token_confidential_transfer_proof_extraction::instruction::ProofLocation::ContextStateAccount(&context);
build_official(create, &owner, location)
},
crate::SplElgamalRegistryProofLocation::Inline { proof_data_base64 } => {
let bytes = match base64::engine::general_purpose::STANDARD
.decode(proof_data_base64.as_bytes())
{
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_proof_base64_invalid",
error.to_string(),
));
},
};
let expected = std::mem::size_of::<
solana_zk_elgamal_proof_interface::proof_data::PubkeyValidityProofData,
>();
if bytes.len() != expected {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_proof_size_invalid",
format!(
"PubkeyValidityProofData requires {expected} bytes, received {}",
bytes.len()
),
));
}
let proof_data = bytemuck::pod_read_unaligned::<
solana_zk_elgamal_proof_interface::proof_data::PubkeyValidityProofData,
>(bytes.as_slice());
let offset = match std::num::NonZeroI8::new(1) {
std::option::Option::Some(value) => value,
std::option::Option::None => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_internal_offset_invalid",
"inline proof offset must be one",
));
},
};
let location = spl_token_confidential_transfer_proof_extraction::instruction::ProofLocation::InstructionOffset(offset, &proof_data);
build_official(create, &owner, location)
},
};
let instructions: Vec<solana_instruction::Instruction> = match instructions {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let planned: Vec<kb_execution_api::PlannedInstruction> = instructions
.iter()
.map(|instruction| return planned_instruction(operation_code, instruction))
.collect();
let mut required_signers = vec![kb_execution_api::RequiredSigner {
pubkey: intent.fee_payer.clone(),
role: std::string::String::from("fee_payer"),
}];
if intent.fee_payer != *owner_model {
required_signers.push(kb_execution_api::RequiredSigner {
pubkey: owner_model.clone(),
role: std::string::String::from("registry_owner"),
});
}
tracing::debug!(
target: crate::TRACING_TARGET,
action = "build_prepared_plan",
intent_id = %intent.intent_id,
operation_code,
owner = %owner_model.0,
instruction_count = planned.len(),
"built SPL ElGamal registry execution plan"
);
return std::result::Result::Ok(kb_execution_api::PreparedExecutionPlan {
executor_name: std::string::String::from("kb_executor_spl_elgamal_registry"),
executor_version: std::string::String::from(env!("CARGO_PKG_VERSION")),
intent_id: intent.intent_id.clone(),
operation_code: std::string::String::from(operation_code),
fee_payer: kb_model::Pubkey(fee_payer.to_string()),
instructions: planned,
required_signers,
policy: intent.policy.clone(),
requested_spend_lamports: 0,
requested_compute_unit_price_micro_lamports: std::option::Option::None,
});
}
fn build_official(
create: bool,
owner: &solana_pubkey::Pubkey,
location: spl_token_confidential_transfer_proof_extraction::instruction::ProofLocation<
solana_zk_elgamal_proof_interface::proof_data::PubkeyValidityProofData,
>,
) -> kb_core::Result<std::vec::Vec<solana_instruction::Instruction>> {
let result = if create {
spl_elgamal_registry_interface::instruction::create_registry(owner, location)
} else {
spl_elgamal_registry_interface::instruction::update_registry(owner, location)
};
return match result {
std::result::Result::Ok(value) => std::result::Result::Ok(value),
std::result::Result::Err(error) => std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_builder_failed",
error.to_string(),
)),
};
}
fn parse_address(value: &kb_model::Pubkey, field: &str) -> kb_core::Result<solana_pubkey::Pubkey> {
return match solana_pubkey::Pubkey::from_str(value.0.as_str()) {
std::result::Result::Ok(address) => std::result::Result::Ok(address),
std::result::Result::Err(error) => std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_pubkey_invalid",
format!("{field}: {error}"),
)),
};
}
fn planned_instruction(
operation_code: &str,
instruction: &solana_instruction::Instruction,
) -> kb_execution_api::PlannedInstruction {
return kb_execution_api::PlannedInstruction {
program_id: kb_model::ProgramId(instruction.program_id.to_string()),
operation_code: std::string::String::from(operation_code),
accounts: instruction
.accounts
.iter()
.map(|account| {
return kb_execution_api::PlannedAccount {
pubkey: kb_model::Pubkey(account.pubkey.to_string()),
is_signer: account.is_signer,
is_writable: account.is_writable,
};
})
.collect(),
data: instruction.data.clone(),
};
}
#[cfg(test)]
mod tests {
fn pubkey(value: &str) -> kb_model::Pubkey {
return kb_model::Pubkey(std::string::String::from(value));
}
fn intent(create: bool) -> crate::SplElgamalRegistryExecutionIntent {
let owner = pubkey(kb_program_ids::SYSTEM_PROGRAM_ID);
return crate::SplElgamalRegistryExecutionIntent {
intent_id: std::string::String::from("registry-intent"),
fee_payer: owner.clone(),
policy: kb_execution_api::ExecutionPolicy {
cost_limit: kb_execution_api::ExecutionCostLimit {
max_spend_lamports: std::option::Option::Some(0),
max_fee_lamports: std::option::Option::Some(20_000),
max_compute_unit_price_micro_lamports: std::option::Option::None,
},
authorized_signers: vec![owner.clone()],
dry_run: true,
post_execution_validation: kb_execution_api::PostExecutionValidationPolicy {
canonical_insert_required: true,
core_extraction_required: true,
decode_replay_required: true,
materialization_required: true,
},
..kb_execution_api::ExecutionPolicy::default()
},
operation: if create {
crate::SplElgamalRegistryOperation::CreateRegistry {
owner,
proof: crate::SplElgamalRegistryProofLocation::ContextStateAccount {
account: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
},
}
} else {
crate::SplElgamalRegistryOperation::UpdateRegistry {
owner,
proof: crate::SplElgamalRegistryProofLocation::ContextStateAccount {
account: pubkey(kb_program_ids::VOTE_PROGRAM_ID),
},
}
},
};
}
#[test]
fn create_and_update_use_official_registry_wire_and_accounts() {
for create in [true, false] {
let plan = crate::build_prepared_plan(&intent(create))
.unwrap_or_else(|error| panic!("registry plan failed: {error}"));
assert_eq!(plan.instructions.len(), 1);
assert_eq!(
plan.instructions[0].program_id.0,
kb_program_ids::SPL_TOKEN_2022_ELGAMAL_REGISTRY_PROGRAM_ID
);
assert_eq!(plan.instructions[0].data, if create { vec![0, 0] } else { vec![1, 0] });
assert_eq!(plan.required_signers.len(), 1);
}
}
#[test]
fn optional_simulation_and_invalid_inline_proof_fail_closed() {
let mut value = intent(true);
value.policy.simulation = kb_execution_api::ExecutionSimulationPolicy::Optional;
let error = crate::build_prepared_plan(&value).expect_err("optional simulation must fail");
assert_eq!(error.code(), "execution_spl_elgamal_registry_simulation_required");
value = intent(true);
value.operation = crate::SplElgamalRegistryOperation::CreateRegistry {
owner: pubkey(kb_program_ids::SYSTEM_PROGRAM_ID),
proof: crate::SplElgamalRegistryProofLocation::Inline {
proof_data_base64: std::string::String::from("AA=="),
},
};
let error = crate::build_prepared_plan(&value).expect_err("invalid proof size must fail");
assert_eq!(error.code(), "execution_spl_elgamal_registry_proof_size_invalid");
}
}

View File

@@ -0,0 +1,7 @@
// file: kb_executor_spl_elgamal_registry/src/constants.rs
// version: 2
//! Executor-local constants.
/// Canonical tracing target for this crate.
pub(crate) const TRACING_TARGET: &str = "kb_executor_spl_elgamal_registry";

View File

@@ -0,0 +1,163 @@
// file: kb_executor_spl_elgamal_registry/src/executor.rs
// version: 2
//! Exact capability dispatch for the SPL ElGamal registry.
/// Typed SPL ElGamal registry executor.
#[derive(Clone, Debug, Default)]
pub struct SplElgamalRegistryExecutor;
impl crate::SplElgamalRegistryExecutor {
fn exact_capability(
&self,
program_id: &kb_model::ProgramId,
operation_code: &str,
) -> kb_execution_api::ExecutionCapability {
if program_id.0 != kb_program_ids::SPL_TOKEN_2022_ELGAMAL_REGISTRY_PROGRAM_ID {
return kb_execution_api::ExecutionCapability::unsupported(
"execution_spl_elgamal_registry_program_not_owned",
format!("program {} is not the SPL ElGamal registry", program_id.0),
);
}
return match operation_code {
crate::CREATE_REGISTRY_OPERATION | crate::UPDATE_REGISTRY_OPERATION => {
kb_execution_api::ExecutionCapability::supported(operation_code)
},
_ => kb_execution_api::ExecutionCapability::unsupported(
"execution_spl_elgamal_registry_operation_unsupported",
format!("ElGamal registry operation {operation_code} is not implemented"),
),
};
}
}
impl kb_execution_api::TypedInstructionExecutor for crate::SplElgamalRegistryExecutor {
type Intent = crate::SplElgamalRegistryExecutionIntent;
fn capability(
&self,
program_id: &kb_model::ProgramId,
operation_code: &str,
) -> kb_execution_api::ExecutionCapability {
return self.exact_capability(program_id, operation_code);
}
fn build_prepared_plan(
&self,
intent: &Self::Intent,
) -> kb_core::Result<kb_execution_api::PreparedExecutionPlan> {
let program_id = kb_model::ProgramId(std::string::String::from(
kb_program_ids::SPL_TOKEN_2022_ELGAMAL_REGISTRY_PROGRAM_ID,
));
return match self.exact_capability(&program_id, intent.operation.operation_code()) {
kb_execution_api::ExecutionCapability::Supported { operation_code: _ } => {
crate::build_prepared_plan(intent)
},
kb_execution_api::ExecutionCapability::Unsupported { reason_code, reason } => {
std::result::Result::Err(kb_core::Error::new(reason_code, reason))
},
};
}
}
impl kb_execution_api::InstructionExecutor for crate::SplElgamalRegistryExecutor {
fn executor_name(&self) -> &'static str {
return "kb_executor_spl_elgamal_registry";
}
fn executor_version(&self) -> &'static str {
return env!("CARGO_PKG_VERSION");
}
fn program_ids(&self) -> &'static [&'static str] {
return &[kb_program_ids::SPL_TOKEN_2022_ELGAMAL_REGISTRY_PROGRAM_ID];
}
fn supports_request(
&self,
request: &kb_execution_api::ExecutionRequest,
) -> kb_execution_api::ExecutionSupport {
return if self
.exact_capability(&request.program_id, &request.operation_code)
.is_supported()
{
kb_execution_api::ExecutionSupport::Yes
} else {
kb_execution_api::ExecutionSupport::No
};
}
fn build_plan(
&self,
request: &kb_execution_api::ExecutionRequest,
) -> kb_core::Result<kb_execution_api::ExecutionPlan> {
match self.exact_capability(&request.program_id, &request.operation_code) {
kb_execution_api::ExecutionCapability::Supported { operation_code: _ } => {},
kb_execution_api::ExecutionCapability::Unsupported { reason_code, reason } => {
return std::result::Result::Err(kb_core::Error::new(reason_code, reason));
},
}
let intent = match serde_json::from_str::<crate::SplElgamalRegistryExecutionIntent>(
&request.payload_json,
) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_intent_deserialize_failed",
error.to_string(),
));
},
};
if intent.operation.operation_code() != request.operation_code {
return std::result::Result::Err(kb_core::Error::new(
"execution_operation_code_mismatch",
"request and typed intent operations differ",
));
}
let prepared =
match kb_execution_api::TypedInstructionExecutor::build_prepared_plan(self, &intent) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
let payload = match serde_json::to_value(&prepared) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => {
return std::result::Result::Err(kb_core::Error::new(
"execution_spl_elgamal_registry_plan_serialize_failed",
error.to_string(),
));
},
};
let payload_json = match kb_execution_api::serialize_payload_json(&payload) {
std::result::Result::Ok(value) => value,
std::result::Result::Err(error) => return std::result::Result::Err(error),
};
return std::result::Result::Ok(kb_execution_api::ExecutionPlan {
executor_name: std::string::String::from("kb_executor_spl_elgamal_registry"),
instruction_count: prepared.instructions.len(),
payload_json,
});
}
}
#[cfg(test)]
mod tests {
#[test]
fn program_and_operation_dispatch_are_exact() {
let executor = crate::SplElgamalRegistryExecutor;
for operation in [crate::CREATE_REGISTRY_OPERATION, crate::UPDATE_REGISTRY_OPERATION] {
let capability = kb_execution_api::TypedInstructionExecutor::capability(
&executor,
&kb_model::ProgramId(std::string::String::from(
kb_program_ids::SPL_TOKEN_2022_ELGAMAL_REGISTRY_PROGRAM_ID,
)),
operation,
);
assert!(capability.is_supported());
}
let foreign = kb_execution_api::TypedInstructionExecutor::capability(
&executor,
&kb_model::ProgramId(std::string::String::from(
kb_program_ids::SPL_TOKEN_2022_PROGRAM_ID,
)),
crate::CREATE_REGISTRY_OPERATION,
);
assert!(!foreign.is_supported());
}
}

View File

@@ -0,0 +1,82 @@
// file: kb_executor_spl_elgamal_registry/src/intent.rs
// version: 2
//! Typed intents for the SPL ElGamal public-key registry.
use ts_rs::TS; // rust-rules: derive-import
/// Stable operation code for registry creation.
pub const CREATE_REGISTRY_OPERATION: &str = "spl_elgamal_registry.create_registry";
/// Stable operation code for registry update.
pub const UPDATE_REGISTRY_OPERATION: &str = "spl_elgamal_registry.update_registry";
/// Exact location of the public-key validity proof.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
#[serde(tag = "location", rename_all = "snake_case")]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_executor_spl_elgamal_registry/intent/SplElgamalRegistryProofLocation.ts"
)]
pub enum SplElgamalRegistryProofLocation {
/// A pre-verified proof context-state account.
ContextStateAccount {
/// Context-state account owned by the native ZK ElGamal proof program.
account: kb_model::Pubkey,
},
/// Inline `PubkeyValidity` proof placed immediately after the registry instruction.
Inline {
/// Canonical raw `PubkeyValidityProofData` bytes encoded as base64.
proof_data_base64: std::string::String,
},
}
/// Typed registry operation.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
#[serde(tag = "operation", rename_all = "snake_case")]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_executor_spl_elgamal_registry/intent/SplElgamalRegistryOperation.ts"
)]
pub enum SplElgamalRegistryOperation {
/// Create the deterministic registry PDA for one owner.
CreateRegistry {
/// Wallet that owns and signs for the registry.
owner: kb_model::Pubkey,
/// Proof location.
proof: crate::SplElgamalRegistryProofLocation,
},
/// Update the registry with a newly proven ElGamal public key.
UpdateRegistry {
/// Wallet that owns and signs for the registry.
owner: kb_model::Pubkey,
/// Proof location.
proof: crate::SplElgamalRegistryProofLocation,
},
}
impl crate::SplElgamalRegistryOperation {
/// Returns the stable operation code.
pub fn operation_code(&self) -> &'static str {
return match self {
Self::CreateRegistry { owner: _, proof: _ } => crate::CREATE_REGISTRY_OPERATION,
Self::UpdateRegistry { owner: _, proof: _ } => crate::UPDATE_REGISTRY_OPERATION,
};
}
}
/// Complete typed execution intent.
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, TS)]
#[ts(
export,
export_to = "../frontend/ts/bindings/kb_executor_spl_elgamal_registry/intent/SplElgamalRegistryExecutionIntent.ts"
)]
pub struct SplElgamalRegistryExecutionIntent {
/// Caller-provided correlation identifier.
pub intent_id: std::string::String,
/// Transaction fee payer.
pub fee_payer: kb_model::Pubkey,
/// Conservative common execution policy.
pub policy: kb_execution_api::ExecutionPolicy,
/// Registry operation.
pub operation: crate::SplElgamalRegistryOperation,
}

View File

@@ -0,0 +1,30 @@
// file: kb_executor_spl_elgamal_registry/src/lib.rs
// version: 5
//! Typed executor for the SPL ElGamal public-key registry.
#![warn(missing_docs)]
#![deny(unreachable_pub)]
#![forbid(unsafe_code)]
mod builder;
mod constants;
mod executor;
mod intent;
/// Crate-root access to `build_prepared_plan` from `builder`.
pub(crate) use crate::builder::build_prepared_plan;
/// Canonical tracing target for this crate.
pub(crate) use crate::constants::TRACING_TARGET;
/// Exposes the typed ElGamal registry executor.
pub use crate::executor::SplElgamalRegistryExecutor;
/// Stable operation code for registry creation.
pub use crate::intent::CREATE_REGISTRY_OPERATION;
/// Exposes the complete typed execution intent.
pub use crate::intent::SplElgamalRegistryExecutionIntent;
/// Exposes one exact registry operation.
pub use crate::intent::SplElgamalRegistryOperation;
/// Exposes the proof-location contract.
pub use crate::intent::SplElgamalRegistryProofLocation;
/// Stable operation code for registry update.
pub use crate::intent::UPDATE_REGISTRY_OPERATION;