Skip to content

Commit

Permalink
PRO-344: update contract ABI to match audit changes (#632)
Browse files Browse the repository at this point in the history
* update contract abi to match audit changes

* small fix

tests still fail

* update ABIs

* Fix tests

---------

Co-authored-by: Dzejkop <jakubtrad@gmail.com>
  • Loading branch information
dcbuild3r and Dzejkop authored Oct 13, 2023
1 parent 9a71483 commit 96ffb71
Show file tree
Hide file tree
Showing 14 changed files with 28,365 additions and 29,289 deletions.
10 changes: 8 additions & 2 deletions crates/micro-oz/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use ethers::prelude::SignerMiddleware;
use ethers::providers::{Http, Middleware, Provider};
use ethers::signers::{LocalWallet, Signer};
use ethers::types::transaction::eip2718::TypedTransaction;
use ethers::types::Eip1559TransactionRequest;
use ethers::types::{Eip1559TransactionRequest, U64};
use oz_api::data::transactions::{RelayerTransactionBase, SendBaseTransactionRequestOwned, Status};
use tokio::sync::{mpsc, Mutex};

Expand Down Expand Up @@ -101,9 +101,15 @@ async fn runner_inner(inner: &Arc<PinheadInner>, tx_id: String) -> Result<(), an

let mut tx_guard = tx.lock().await;

if let Some(_receipt) = receipt {
if let Some(receipt) = receipt {
if let Some(U64([0])) = receipt.status {
tracing::error!("Receipt: {:?}", receipt);
} else {
tracing::info!("Receipt: {:?}", receipt);
}
tx_guard.status = Status::Mined;
} else {
tracing::error!("Receipt not found");
tx_guard.status = Status::Failed;
}

Expand Down
12,646 changes: 0 additions & 12,646 deletions sol/SemaphoreVerifier.json

This file was deleted.

21,272 changes: 21,272 additions & 0 deletions sol/SemaphoreVerifier20.json

Large diffs are not rendered by default.

1,522 changes: 659 additions & 863 deletions sol/SequencerVerifier.json

Large diffs are not rendered by default.

18,585 changes: 4,661 additions & 13,924 deletions sol/WorldIDIdentityManagerImplV1.json

Large diffs are not rendered by default.

3,434 changes: 1,682 additions & 1,752 deletions sol/WorldIDIdentityManagerImplV2.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/contracts/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ abigen!(
struct RootInfo { uint256 root; uint128 supersededTimestamp; bool isValid }
event TreeChanged(uint256 indexed preRoot, uint8 indexed kind, uint256 indexed postRoot)
function registerIdentities(uint256[8] calldata insertionProof, uint256 preRoot, uint32 startIndex, uint256[] calldata identityCommitments, uint256 postRoot) public virtual
function deleteIdentities(uint256[8] calldata deletionProof, uint32 batchSize, bytes calldata packedDeletionIndices, uint256 preRoot, uint256 postRoot) public virtual
function deleteIdentities(uint256[8] calldata deletionProof, bytes calldata packedDeletionIndices, uint256 preRoot, uint256 postRoot) public virtual
function latestRoot() public view virtual returns (uint256 root)
function owner() public view virtual returns (address)
function queryRoot(uint256 root) public view virtual returns (RootInfo memory)
Expand Down
2 changes: 0 additions & 2 deletions src/contracts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,6 @@ impl IdentityManager {
pub async fn delete_identities(
&self,
deletion_proof: Proof,
batch_size: u32,
packed_deletion_indices: Vec<u8>,
pre_root: U256,
post_root: U256,
Expand All @@ -311,7 +310,6 @@ impl IdentityManager {
.abi
.delete_identities(
proof_points_array,
batch_size,
packed_deletion_indices.into(),
pre_root,
post_root,
Expand Down
8 changes: 1 addition & 7 deletions src/task_monitor/tasks/process_identities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,13 +548,7 @@ pub async fn delete_identities(
// With all the data prepared we can submit the identities to the on-chain
// identity manager and wait for that transaction to be mined.
let transaction_id = identity_manager
.delete_identities(
proof,
batch_size as u32,
packed_deletion_indices,
pre_root,
post_root,
)
.delete_identities(proof, packed_deletion_indices, pre_root, post_root)
.await
.map_err(|e| {
error!(?e, "Failed to insert identity to contract.");
Expand Down
37 changes: 1 addition & 36 deletions tests/common/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,45 +5,10 @@ use ethers::prelude::abigen;
abigen!(
BatchingContract,
r#"[
struct RootInfo { uint256 root; uint128 supersededTimestamp; bool isValid }
function NO_SUCH_ROOT() public pure returns (RootInfo memory rootInfo)
error UnreducedElement(uint8 elementType, uint256 element)
error Unauthorized(address user)
error InvalidCommitment(uint256 commitment)
error ProofValidationFailure()
error NotLatestRoot(uint256 providedRoot, uint256 latestRoot)
error ExpiredRoot()
error NonExistentRoot()
error ImplementationNotInitalized()
error NoSuchVerifier()
error MismatchedInputLengths()
constructor(address _logic, bytes memory data) payable
function initialize(uint8 treeDepth, uint256 initialRoot, address _batchInsertionVerifiers, address _batchUpdateVerifiers, address _semaphoreVerifier) public virtual
function initializeV2(address _batchDeletionVerifiers) public virtual
function deleteIdentities(uint256[8] calldata deletionProof, uint256 preRoot, bytes calldata deletionIndices, uint256 postRoot) public virtual
function registerIdentities(uint256[8] calldata insertionProof, uint256 preRoot, uint32 startIndex, uint256[] calldata identityCommitments, uint256 postRoot) public virtual
function updateIdentities(uint256[8] calldata updateProof, uint256 preRoot, uint32[] calldata leafIndices, uint256[] calldata oldIdentities, uint256[] calldata newIdentities, uint256 postRoot) public virtual
function calculateIdentityRegistrationInputHash(uint32 startIndex, uint256 preRoot, uint256 postRoot, uint256[] identityCommitments) public view virtual returns (bytes32 hash)
function calculateIdentityUpdateInputHash(uint256 preRoot, uint256 postRoot, uint32[] calldata leafIndices, uint256[] calldata oldIdentities, uint256[] calldata newIdentities) public view virtual returns (bytes32 hash)
function latestRoot() public view virtual returns (uint256 root)
function queryRoot(uint256 root) public view virtual returns (RootInfo memory rootInfo)
function isInputInReducedForm(uint256 input) public view virtual returns (bool isInReducedForm)
function checkValidRoot(uint256 root) public view virtual returns (bool)
function getRegisterIdentitiesVerifierLookupTableAddress() public view virtual returns (address addr)
function setRegisterIdentitiesVerifierLookupTable(address newVerifier) public virtual
function getIdentityUpdateVerifierLookupTableAddress() public view virtual returns (address addr)
function setIdentityUpdateVerifierLookupTable(address newVerifier) public virtual
function getSemaphoreVerifierAddress() public view virtual returns (address addr)
function setSemaphoreVerifier(address newVerifier) public virtual
function getRootHistoryExpiry() public view virtual returns (uint256 expiryTime)
function setRootHistoryExpiry(uint256 newExpiryTime) public virtual
function verifyProof(uint256 root, uint256 signalHash, uint256 nullifierHash, uint256 externalNullifierHash, uint256[8] calldata proof) public view virtual
function owner() public view virtual returns (address)
function renounceOwnership() public virtual
function transferOwnership(address newOwner) public virtual
function proxiableUUID() external view virtual override returns (bytes32)
function upgradeTo(address newImplementation) external virtual
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual
function setRootHistoryExpiry(uint256 newExpiryTime) public virtual
]"#,
event_derives(serde::Deserialize, serde::Serialize)
);
2 changes: 1 addition & 1 deletion tests/common/chain_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub async fn spawn_mock_chain(
.send()
.await?;

let verifier_path = "./sol/SemaphoreVerifier.json";
let verifier_path = "./sol/SemaphoreVerifier20.json";
let verifier_file =
File::open(verifier_path).unwrap_or_else(|_| panic!("Failed to open `{verifier_path}`"));

Expand Down
76 changes: 44 additions & 32 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ use self::chain_mock::{spawn_mock_chain, MockChain, SpecialisedContract};
use self::prelude::*;
use self::prover_mock::ProverType;

const NUM_ATTEMPTS_FOR_INCLUSION_PROOF: usize = 20;

#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn test_verify_proof(
Expand Down Expand Up @@ -223,7 +225,7 @@ pub async fn test_inclusion_proof(
leaf: &Hash,
expect_failure: bool,
) {
for i in 1..21 {
for i in 0..NUM_ATTEMPTS_FOR_INCLUSION_PROOF {
let body = construct_inclusion_proof_body(leaf);
info!(?uri, "Contacting");
let req = Request::builder()
Expand Down Expand Up @@ -262,16 +264,23 @@ pub async fn test_inclusion_proof(
generate_reference_proof_json(ref_tree, leaf_index, "pending")
);
assert_eq!(response.status(), StatusCode::ACCEPTED);
info!("Got pending, waiting 1 second, iteration {}", i);
tokio::time::sleep(Duration::from_secs(1)).await;
info!("Got pending, waiting 5 seconds, iteration {}", i);
tokio::time::sleep(Duration::from_secs(5)).await;
} else if status == "mined" {
// We don't differentiate between these 2 states in tests
let proof_json = generate_reference_proof_json(ref_tree, leaf_index, status);
assert_eq!(result_json, proof_json);

return;
} else {
panic!("Unexpected status: {}", status);
}
}

panic!(
"Failed to get an inclusion proof after {} attempts!",
NUM_ATTEMPTS_FOR_INCLUSION_PROOF
);
}

#[instrument(skip_all)]
Expand All @@ -281,37 +290,40 @@ pub async fn test_inclusion_status(
leaf: &Hash,
expected_status: Status,
) {
for _i in 1..21 {
let body = construct_inclusion_proof_body(leaf);
info!(?uri, "Contacting");
let req = Request::builder()
.method("POST")
.uri(uri.to_owned() + "/inclusionProof")
.header("Content-Type", "application/json")
.body(body)
.expect("Failed to create inclusion proof hyper::Body");

let mut response = client
.request(req)
.await
.expect("Failed to execute request.");
let body = construct_inclusion_proof_body(leaf);
info!(?uri, "Contacting");
let req = Request::builder()
.method("POST")
.uri(uri.to_owned() + "/inclusionProof")
.header("Content-Type", "application/json")
.body(body)
.expect("Failed to create inclusion proof hyper::Body");

let bytes = hyper::body::to_bytes(response.body_mut())
.await
.expect("Failed to convert response body to bytes");
let result = String::from_utf8(bytes.into_iter().collect())
.expect("Could not parse response bytes to utf-8");
let result_json = serde_json::from_str::<serde_json::Value>(&result)
.expect("Failed to parse response as json");
let status = result_json["status"]
.as_str()
.expect("Failed to get status");
let mut response = client
.request(req)
.await
.expect("Failed to execute request.");

assert_eq!(
expected_status,
Status::from_str(status).expect("Could not convert str to Status")
);
}
let bytes = hyper::body::to_bytes(response.body_mut())
.await
.expect("Failed to convert response body to bytes");
let result = String::from_utf8(bytes.into_iter().collect())
.expect("Could not parse response bytes to utf-8");
println!(
"########################################################## \n
result: {:?}",
result
);
let result_json = serde_json::from_str::<serde_json::Value>(&result)
.expect("Failed to parse response as json");
let status = result_json["status"]
.as_str()
.expect("Failed to get status");

assert_eq!(
expected_status,
Status::from_str(status).expect("Could not convert str to Status")
);
}

#[instrument(skip_all)]
Expand Down
35 changes: 20 additions & 15 deletions tests/dynamic_batch_sizes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,33 @@ use hyper::Uri;
use crate::common::{test_add_batch_size, test_remove_batch_size};

const SUPPORTED_DEPTH: usize = 20;
const IDLE_TIME: u64 = 7;
const IDLE_TIME: u64 = 10;

#[tokio::test]
async fn dynamic_batch_sizes() -> anyhow::Result<()> {
// Initialize logging for the test.
init_tracing_subscriber();
info!("Starting integration test");

let batch_size: usize = 3;
let first_batch_size: usize = 3;
let second_batch_size: usize = 2;

#[allow(clippy::cast_possible_truncation)]
let tree_depth: u8 = SUPPORTED_DEPTH as u8;

let mut ref_tree = PoseidonTree::new(SUPPORTED_DEPTH + 1, ruint::Uint::ZERO);
let initial_root: U256 = ref_tree.root().into();

let (mock_chain, db_container, insertion_prover_map, _, micro_oz) =
spawn_deps(initial_root, &[batch_size], &[], tree_depth).await?;
let (mock_chain, db_container, insertion_prover_map, _, micro_oz) = spawn_deps(
initial_root,
&[first_batch_size, second_batch_size],
&[],
tree_depth,
)
.await?;

let prover_mock = &insertion_prover_map[&batch_size];
let first_prover = &insertion_prover_map[&first_batch_size];
let second_prover = &insertion_prover_map[&second_batch_size];

let port = db_container.port();
let db_url = format!("postgres://postgres:postgres@localhost:{port}/database");
Expand All @@ -45,7 +52,7 @@ async fn dynamic_batch_sizes() -> anyhow::Result<()> {
"--tree-depth",
&format!("{tree_depth}"),
"--prover-urls",
&prover_mock.arg_string(),
&first_prover.arg_string(),
"--batch-timeout-seconds",
"3",
"--dense-tree-prefix-depth",
Expand Down Expand Up @@ -75,7 +82,7 @@ async fn dynamic_batch_sizes() -> anyhow::Result<()> {
.await
.expect("Failed to spawn app.");

let test_identities = generate_test_identities(batch_size * 5);
let test_identities = generate_test_identities(first_batch_size * 5);
let identities_ref: Vec<Field> = test_identities
.iter()
.map(|i| Hash::from_str_radix(i, 16).unwrap())
Expand Down Expand Up @@ -125,9 +132,6 @@ async fn dynamic_batch_sizes() -> anyhow::Result<()> {
)
.await;

// Add a new prover for batch sizes of two.
let second_prover = spawn_mock_insertion_prover(second_batch_size, tree_depth).await?;

test_add_batch_size(
&uri,
second_prover.url(),
Expand Down Expand Up @@ -162,17 +166,17 @@ async fn dynamic_batch_sizes() -> anyhow::Result<()> {
"prover_type": "insertion",
},
{
"url": prover_mock.url() + "/",
"url": first_prover.url() + "/",
"timeout_s": 30,
"batch_size": batch_size,
"batch_size": first_batch_size,
"prover_type": "insertion",

}
])
);

// Insert enough identities to trigger the lower batch size.
prover_mock.set_availability(false).await;
first_prover.set_availability(false).await;
test_insert_identity(&uri, &client, &mut ref_tree, &identities_ref, 3).await;
test_insert_identity(&uri, &client, &mut ref_tree, &identities_ref, 4).await;

Expand All @@ -181,6 +185,7 @@ async fn dynamic_batch_sizes() -> anyhow::Result<()> {
tokio::time::resume();

tokio::time::sleep(Duration::from_secs(IDLE_TIME)).await;

// Check that we can also get these inclusion proofs back.
test_inclusion_proof(
&uri,
Expand All @@ -206,9 +211,9 @@ async fn dynamic_batch_sizes() -> anyhow::Result<()> {
// Now if we remove the original prover, things should still work.
test_remove_batch_size(
&uri,
batch_size as u64,
first_batch_size as u64,
&client,
prover_mock.prover_type(),
first_prover.prover_type(),
false,
)
.await?;
Expand Down
23 changes: 15 additions & 8 deletions tests/validate_proofs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,17 +92,24 @@ async fn validate_proofs() -> anyhow::Result<()> {
let (merkle_proof, root) =
test_insert_identity(&uri, &client, &mut ref_tree, &TEST_LEAVES, 0).await;

tokio::time::sleep(Duration::from_secs(5 + batch_timeout_seconds)).await;
// simulate client generating a proof
let nullifier_hash = generate_nullifier_hash(&IDENTITIES[0], external_nullifier_hash);

let proof = generate_proof(
&IDENTITIES[0],
&merkle_proof,
external_nullifier_hash,
signal_hash,
)
.unwrap();
// Generates proof in the background
let merkle_proof_for_task = merkle_proof.clone();
let proof_task = tokio::task::spawn_blocking(move || {
generate_proof(
&IDENTITIES[0],
&merkle_proof_for_task,
external_nullifier_hash,
signal_hash,
)
.unwrap()
});

tokio::time::sleep(Duration::from_secs(15 + batch_timeout_seconds)).await;

let proof = proof_task.await.unwrap();

test_verify_proof(
&uri,
Expand Down

0 comments on commit 96ffb71

Please sign in to comment.