Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 39 additions & 6 deletions client/rpc-v2/src/orbinum/ORBINUM_RPC_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,70 @@ Method names use the `privacy_` prefix.

- **Params:** none
- **Returns:** `string`
- Current Merkle root as a hex string (typically `0x`-prefixed).
- Current Merkle root as a `0x`-prefixed 32-byte little-endian hex string.

### 2) `privacy_getMerkleProof`

- **Params:**
- `leaf_index` (`u32`): zero-based index of the commitment leaf.
- **Returns:** object (`MerkleProofResponse`)
- `path`: `string[]` (sibling hashes in hex)
- `root`: `string` — Merkle root read from the **same block** as the proof (0x-prefixed LE hex).
- `path`: `string[]` — sibling hashes in 0x-prefixed LE hex, from leaf level to root.
- `leaf_index`: `u32`
- `tree_depth`: `u32`

### 3) `privacy_getNullifierStatus`
> **Atomicity:** `root` and `path` are always read under the same `best_block` reference,
> eliminating any race condition between a separate `getMerkleRoot` call.

### 3) `privacy_getMerkleProofByCommitment`

- **Params:**
- `commitment` (`string`): commitment hash as a `0x`-prefixed 32-byte hex string.
- **Returns:** object (`MerkleProofResponse`)
- `root`: `string` — Merkle root read from the **same block** as the proof (0x-prefixed LE hex).
- `path`: `string[]` — sibling hashes in 0x-prefixed LE hex, from leaf level to root.
- `leaf_index`: `u32`
- `tree_depth`: `u32`

> **Atomicity:** same guarantee as `privacy_getMerkleProof` — root and path share one block snapshot.

### 4) `privacy_getNullifierStatus`

- **Params:**
- `nullifier` (`string`): nullifier hash in hex (with or without `0x` prefix).
- **Returns:** object (`NullifierStatusResponse`)
- `nullifier`: `string`
- `is_spent`: `bool`

### 4) `privacy_getPoolStats`
### 5) `privacy_getPoolStats`

- **Params:** none
- **Returns:** object (`PoolStatsResponse`)
- `merkle_root`: `string`
- `commitment_count`: `u32`
- `total_balance`: `u128` (minimum units)
- `asset_balances`: `Array<{ asset_id: u32, balance: u128 }>` (solo balances no-cero)
- `asset_balances`: `Array<{ asset_id: u32, balance: u128 }>` (non-zero balances only)
- `tree_depth`: `u32`

## MerkleProofResponse shape

```json
{
"root": "0x1a2b3c...",
"path": ["0xaabb...", "0xccdd...", "..."],
"leaf_index": 0,
"tree_depth": 20
}
```

All hex strings are **0x-prefixed 32-byte values encoded in little-endian byte order**,
matching the internal Poseidon hash representation used by the shielded-pool pallet.

## Usage Notes

- All methods are query-only and intended for wallets, indexers, and clients.
- Hex values are returned as strings.
- `leaf_index` is expected to be within current tree size.
- `leaf_index` is expected to be within current tree size.
- Clients should prefer `privacy_getMerkleProofByCommitment` over calling
`privacy_getMerkleRoot` + `privacy_getMerkleProof` separately, since the combined
endpoint guarantees root/path consistency within a single block.
14 changes: 11 additions & 3 deletions client/rpc-v2/src/orbinum/application/dto/merkle_proof_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use serde::{Deserialize, Serialize};
/// It maps from `domain::MerkleProofPath`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MerkleProofResponse {
/// Current Merkle root (0x-prefixed hex), read from the same block as the proof.
pub root: String,
/// Sibling hash path (hex strings).
pub path: Vec<String>,
/// Leaf index.
Expand All @@ -18,8 +20,9 @@ pub struct MerkleProofResponse {

impl MerkleProofResponse {
/// Creates a new `MerkleProofResponse`.
pub fn new(path: Vec<String>, leaf_index: u32, tree_depth: u32) -> Self {
pub fn new(root: String, path: Vec<String>, leaf_index: u32, tree_depth: u32) -> Self {
Self {
root,
path,
leaf_index,
tree_depth,
Expand All @@ -33,9 +36,14 @@ mod tests {

#[test]
fn should_create_merkle_proof_response() {
let response =
MerkleProofResponse::new(vec!["0xaaaa".to_string(), "0xbbbb".to_string()], 7, 20);
let response = MerkleProofResponse::new(
"0x0000".to_string(),
vec!["0xaaaa".to_string(), "0xbbbb".to_string()],
7,
20,
);

assert_eq!(response.root, "0x0000");
assert_eq!(response.path, vec!["0xaaaa", "0xbbbb"]);
assert_eq!(response.leaf_index, 7);
assert_eq!(response.tree_depth, 20);
Expand Down
257 changes: 257 additions & 0 deletions client/rpc-v2/src/orbinum/application/services/merkle_proof_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,110 @@ where

Ok((root, size, depth))
}

/// Generates a Merkle proof by leaf index and returns the Merkle root, both
/// read under the **same `best_block`** (atomic — no risk of root/path mismatch).
///
/// # Errors
/// - `InvalidLeafIndex`: If `leaf_index >= tree_size`
/// - `TreeNotInitialized`: If the tree is empty
pub fn generate_proof_with_root(
&self,
leaf_index: u32,
) -> ApplicationResult<(MerkleProofPath, Commitment)> {
let block_hash = self.query.best_hash()?;
let tree_size = self.query.get_tree_size(block_hash)?;

if tree_size.value() == 0 {
return Err(ApplicationError::TreeNotInitialized);
}
if leaf_index >= tree_size.value() {
return Err(ApplicationError::InvalidLeafIndex {
index: leaf_index,
tree_size: tree_size.value(),
});
}

let root = self.query.get_merkle_root(block_hash)?;
let path = self.collect_sibling_path(block_hash, leaf_index)?;
let tree_depth = TreeDepth::new(20);

Ok((MerkleProofPath::new(path, leaf_index, tree_depth), root))
}

/// Generates a Merkle proof by commitment and returns the Merkle root, both
/// read under the **same `best_block`** (atomic — no risk of root/path mismatch).
///
/// # Errors
/// - `CalculationError`: If the commitment is not found in the tree
/// - `TreeNotInitialized`: If the tree is empty
pub fn generate_proof_by_commitment_with_root(
&self,
target: Commitment,
) -> ApplicationResult<(MerkleProofPath, Commitment)> {
let block_hash = self.query.best_hash()?;
let tree_size = self.query.get_tree_size(block_hash)?;

if tree_size.value() == 0 {
return Err(ApplicationError::TreeNotInitialized);
}

let mut found_index: Option<u32> = None;
for i in 0..tree_size.value() {
if self.query.get_leaf(block_hash, i)? == target {
found_index = Some(i);
break;
}
}

let leaf_index = found_index.ok_or_else(|| {
ApplicationError::CalculationError("Commitment not found in Merkle tree".to_string())
})?;

let root = self.query.get_merkle_root(block_hash)?;
let path = self.collect_sibling_path(block_hash, leaf_index)?;
let tree_depth = TreeDepth::new(20);

Ok((MerkleProofPath::new(path, leaf_index, tree_depth), root))
}

/// Generates a Merkle proof by scanning for a matching commitment in the tree leaves.
///
/// # Parameters
/// - `target`: Commitment to search for
///
/// # Returns
/// - `MerkleProofPath`: Sibling path with leaf index
///
/// # Errors
/// - `InvalidLeafIndex`: If the commitment is not found in the tree
/// - `TreeNotInitialized`: If the tree is empty
/// - `Domain`: Storage query errors
pub fn generate_proof_by_commitment(
&self,
target: Commitment,
) -> ApplicationResult<MerkleProofPath> {
let block_hash = self.query.best_hash()?;
let tree_size = self.query.get_tree_size(block_hash)?;

if tree_size.value() == 0 {
return Err(ApplicationError::TreeNotInitialized);
}

let mut found_index: Option<u32> = None;
for i in 0..tree_size.value() {
if self.query.get_leaf(block_hash, i)? == target {
found_index = Some(i);
break;
}
}

let leaf_index = found_index.ok_or_else(|| {
ApplicationError::CalculationError("Commitment not found in Merkle tree".to_string())
})?;

self.generate_proof(leaf_index)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -215,6 +319,49 @@ mod tests {
}
}

/// Mock that returns known commitments for all leaf indices (needed for by-commitment tests).
#[derive(Clone, Copy)]
struct MockQueryWithLeaves {
root: Commitment,
leaf_0: Commitment,
leaf_1: Commitment,
}

impl BlockchainQuery for MockQueryWithLeaves {
fn best_hash(&self) -> DomainResult<BlockHash> {
Ok(BlockHash::new([9u8; 32]))
}

fn storage_at(
&self,
_block_hash: BlockHash,
_storage_key: &[u8],
) -> DomainResult<Option<Vec<u8>>> {
Ok(None)
}
}

impl MerkleTreeQuery for MockQueryWithLeaves {
fn get_merkle_root(&self, _block_hash: BlockHash) -> DomainResult<Commitment> {
Ok(self.root)
}

fn get_tree_size(&self, _block_hash: BlockHash) -> DomainResult<TreeSize> {
Ok(TreeSize::new(2))
}

fn get_leaf(&self, _block_hash: BlockHash, leaf_index: u32) -> DomainResult<Commitment> {
match leaf_index {
0 => Ok(self.leaf_0),
1 => Ok(self.leaf_1),
_ => Err(DomainError::LeafIndexOutOfBounds {
index: leaf_index,
tree_size: 2,
}),
}
}
}

#[test]
fn should_return_tree_not_initialized_when_tree_is_empty() {
let query = MockQuery {
Expand Down Expand Up @@ -284,4 +431,114 @@ mod tests {
assert_eq!(size.value(), 5);
assert_eq!(depth.value(), DEFAULT_TREE_DEPTH as u32);
}

// --- generate_proof_with_root ---

#[test]
fn should_generate_proof_with_root() {
let expected_root = Commitment::new([5u8; 32]);
let sibling = Commitment::new([7u8; 32]);
let query = MockQuery {
root: expected_root,
tree_size: 2,
sibling,
};
let service = MerkleProofService::new(query);

let (proof, root) = service
.generate_proof_with_root(0)
.expect("generate_proof_with_root must succeed");

assert_eq!(root, expected_root);
assert_eq!(proof.leaf_index(), 0);
assert_eq!(proof.tree_depth().value(), 20);
assert_eq!(proof.path().len(), 20);
assert_eq!(proof.path()[0], sibling);
}

#[test]
fn should_return_tree_not_initialized_for_generate_proof_with_root() {
let query = MockQuery {
root: Commitment::new([1u8; 32]),
tree_size: 0,
sibling: Commitment::new([2u8; 32]),
};
let service = MerkleProofService::new(query);

let result = service.generate_proof_with_root(0);

assert!(matches!(result, Err(ApplicationError::TreeNotInitialized)));
}

#[test]
fn should_return_invalid_leaf_index_for_generate_proof_with_root() {
let query = MockQuery {
root: Commitment::new([1u8; 32]),
tree_size: 1,
sibling: Commitment::new([2u8; 32]),
};
let service = MerkleProofService::new(query);

let result = service.generate_proof_with_root(1);

assert!(matches!(
result,
Err(ApplicationError::InvalidLeafIndex {
index: 1,
tree_size: 1
})
));
}

// --- generate_proof_by_commitment_with_root ---

#[test]
fn should_generate_proof_by_commitment_with_root() {
let target = Commitment::new([0xAAu8; 32]);
let expected_root = Commitment::new([5u8; 32]);
let query = MockQueryWithLeaves {
root: expected_root,
leaf_0: Commitment::new([0x11u8; 32]),
leaf_1: target,
};
let service = MerkleProofService::new(query);

let (proof, root) = service
.generate_proof_by_commitment_with_root(target)
.expect("generate_proof_by_commitment_with_root must succeed");

assert_eq!(root, expected_root);
assert_eq!(proof.leaf_index(), 1);
assert_eq!(proof.tree_depth().value(), 20);
assert_eq!(proof.path().len(), 20);
}

#[test]
fn should_return_tree_not_initialized_for_generate_proof_by_commitment_with_root() {
let query = MockQuery {
root: Commitment::new([1u8; 32]),
tree_size: 0,
sibling: Commitment::new([2u8; 32]),
};
let service = MerkleProofService::new(query);

let result = service.generate_proof_by_commitment_with_root(Commitment::new([0xAAu8; 32]));

assert!(matches!(result, Err(ApplicationError::TreeNotInitialized)));
}

#[test]
fn should_return_calculation_error_when_commitment_not_found() {
let absent = Commitment::new([0xFFu8; 32]);
let query = MockQueryWithLeaves {
root: Commitment::new([1u8; 32]),
leaf_0: Commitment::new([0x11u8; 32]),
leaf_1: Commitment::new([0x22u8; 32]),
};
let service = MerkleProofService::new(query);

let result = service.generate_proof_by_commitment_with_root(absent);

assert!(matches!(result, Err(ApplicationError::CalculationError(_))));
}
}
Loading
Loading