Skip to content

Commit dd4a986

Browse files
authored
docs(zkquiz): build your first Aligned application (#1185)
1 parent 3f839ac commit dd4a986

6 files changed

Lines changed: 305 additions & 279 deletions

File tree

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Getting started!
1+
# Try Aligned
22

33
In this tutorial, you will learn how to send your first SP1 proofs to get verified in Aligned in under 3 minutes.
44

docs/1_introduction/2_zkquiz.md

Lines changed: 0 additions & 59 deletions
This file was deleted.
Lines changed: 302 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,302 @@
1+
# Build your first Application
2+
3+
In this guide you will learn how to build applications on top of Aligned. It provides a few simple steps to help you verify ZK proofs generated within your system.
4+
5+
First we will show you an example of a trivia application, called ZkQuiz. We'll show you the different components and how they interact with each other to be able to submit the proof to aligned and verify that was correctly included in a batch.
6+
7+
## ZkQuiz
8+
9+
ZkQuiz is an application that leverages Aligned's ZK verification infrastructure to run a small trivia. The proof allows any party to check that the quiz was answered right or wrong. If answered correctly, the user receives an NFT.
10+
11+
{% hint style="warning" %}
12+
Received NFTs from ZkQuiz do not have any value. It is just a test application
13+
{% endhint %}
14+
15+
The process is as follows:
16+
17+
1. The user runs ZKQuiz and answers the questions.
18+
2. ZKQuiz generates a ZK Proof of correct answers.
19+
3. The proof is posted on Aligned.
20+
4. Upon verification, ZKQuiz mints an NFT via a Smart Contract.
21+
22+
The NFT is only granted if the user's answers correctly.
23+
Incorrect answers or tampering with the ZKQuiz code will result in proof generation failure or mismatched checksums,
24+
preventing NFT minting.
25+
26+
Next, we will see how to execute ZKQuiz to get your own ZKQuiz NFT!
27+
28+
### Requirements
29+
30+
1. [Rust](https://www.rust-lang.org/tools/install)
31+
2. [Foundry](https://getfoundry.sh)
32+
33+
### Usage
34+
35+
#### 1. Create a Keystore
36+
37+
You need a keystore to pay for the proof verification, you can use cast to create a local keystore.
38+
If you already have one, you can skip this step.
39+
40+
```bash
41+
cast wallet new-mnemonic
42+
```
43+
44+
Then you can import your created keystore using:
45+
46+
```bash
47+
cast wallet import --interactive <keystore_name>
48+
```
49+
50+
The keystores are saved in `~/.foundry/keystores`. You can find more information about keystores in the [cast documentation](https://book.getfoundry.sh/reference/cast/wallet-commands).
51+
52+
Then you need to get some funds to pay for gas and proof verification.
53+
You can do this by using one of the following faucets:
54+
55+
- [Google Faucet](https://cloud.google.com/application/web3/faucet/ethereum/holesky)
56+
- [Stakely Faucet](https://stakely.io/faucet/ethereum-holesky-testnet-eth)
57+
- [Quicknode Faucet](https://faucet.quicknode.com/ethereum/holesky)
58+
59+
#### 2. Answer Quiz
60+
61+
To answer quiz questions run:
62+
63+
```bash
64+
cd examples/zkquiz
65+
make answer_quiz KEYSTORE_PATH=<path_to_keystore>
66+
```
67+
68+
This will:
69+
70+
1. Ask quiz questions
71+
2. Generate ZK proof
72+
3. Pay & submit proof to aligned for verification
73+
4. Wait for proof to be verified in aligned
74+
5. Claim NFT if proof is verified
75+
76+
## Deep dive
77+
78+
The ZkQuiz source coude is available [here](../../examples/zkquiz).
79+
80+
ZkQuiz has three main components:
81+
- App/script
82+
- Program
83+
- Verifier contract
84+
85+
The user interacts with ZkQuiz App to solve a trivia challenge answering questions. Then, the App generates a Zk Proof with the Program generated using SP1.
86+
87+
{% hint style="info" %}
88+
The ZkQuiz Program is built using SP1 following the [quickstart guide](https://docs.succinct.xyz/getting-started/quickstart.html#project-overview). For your projects, you can user any of the [prooving systems supported by Aligned](../2_architecture/0_supported_verifiers.md).
89+
{% endhint %}
90+
91+
Once the proof is generated, the App sends the proof to Aligned, and once it is verified, the App calls to the ZkQuiz Verifier Contract to check the proof verification and send an NFT to the user is the proof was verified in Aligned.
92+
93+
![ZkQuiz](../images/zkquiz.png)
94+
95+
Now, lets build ZkQuiz from scratch.
96+
97+
### Program
98+
99+
First you need to write the code you want to prove; in this case it looks like this:
100+
101+
```rust
102+
// program/src/main.rs
103+
104+
#![no_main]
105+
106+
use tiny_keccak::{Hasher, Sha3};
107+
sp1_zkvm::entrypoint!(main);
108+
109+
pub fn main() {
110+
let answers = sp1_zkvm::io::read::<String>();
111+
let mut sha3 = Sha3::v256();
112+
let mut output = [0u8; 32];
113+
114+
sha3.update(answers.as_bytes());
115+
116+
sha3.finalize(&mut output);
117+
118+
if output
119+
!= [
120+
232, 202, 155, 157, 82, 242, 126, 73, 75, 22, 197, 34, 41, 170, 163, 190, 22, 29, 192,
121+
5, 99, 134, 186, 25, 77, 128, 188, 154, 238, 70, 245, 229,
122+
]
123+
{
124+
panic!("Answers do not match");
125+
}
126+
}
127+
```
128+
129+
The program takes the user answers as inputs and checks that the hash of the inputs matches with the expected output. This is the program that will be compiled generati ng a binary file that will be ran by the zkVm and used later in the application side. In our case this file is already generated and is located on `/quiz/program/elf/riscv32im-succinct-zkvm-elf`.
130+
131+
### Verifier Contract
132+
133+
To check if a proof was verified in Aligned, you can create your own smart contract in order to make a call to the `AlignedServiceManager` contract.
134+
135+
ZkQuiz uses a Smart Contract to check if aligned verified the proof and gives an NFT to the user.
136+
137+
{% hint style="info" %}
138+
It is not mandatory to create an Smart Contract. You can make off-chain apps that interact with the Aligned contract directly.
139+
{% endhint %}
140+
141+
**Program Identifier Validation**
142+
143+
The contract first checks that the commitment of the program matches with the one that we expect.
144+
145+
In our zkquiz example, we get the following elf_commitment:
146+
147+
```solidity
148+
// contracts/src/VerifierContract.sol
149+
150+
bytes32 public elfCommitment = 0x3f99615fdf3b67a01e41b38eee75a32c778ee2fa631bd74e01c89afc2f70f5de;
151+
152+
if (elfCommitment != provingSystemAuxDataCommitment) {
153+
revert InvalidElf(provingSystemAuxDataCommitment);
154+
}
155+
```
156+
157+
You can generate the expected commitment without actually generating and submitting a proof using the Aligned CLI tool running:
158+
159+
```bash
160+
aligned get-vk-commitment --verification_key_file <path_to_input_file> --proving_system <proving_system_id>
161+
```
162+
where the `path_to_input_file` is the path to the `elf` file generated with the program compilation and the `proving_system_id` the name of the proving system used for compilation, in this case `SP1`.
163+
164+
Then, the contract validates if the provided commitment of the program identifier matches the expected one.
165+
166+
```solidity
167+
// contracts/src/VerifierContract.sol
168+
if (elfCommitment != provingSystemAuxDataCommitment) {
169+
revert InvalidElf(provingSystemAuxDataCommitment);
170+
}
171+
```
172+
173+
The contract makes a call to the `AlignedServiceManager` contract to check if the proof was verified in Aligned.
174+
175+
```solidity
176+
// contracts/src/VerifierContract.sol
177+
(
178+
bool callWasSuccessfull,
179+
bytes memory proofIsIncluded
180+
) = alignedServiceManager.staticcall(
181+
abi.encodeWithSignature(
182+
"verifyBatchInclusion(bytes32,bytes32,bytes32,bytes20,bytes32,bytes,uint256,address)",
183+
proofCommitment,
184+
pubInputCommitment,
185+
provingSystemAuxDataCommitment,
186+
proofGeneratorAddr,
187+
batchMerkleRoot,
188+
merkleProof,
189+
verificationDataBatchIndex,
190+
paymentServiceAddr
191+
)
192+
);
193+
194+
require(callWasSuccessfull, "static_call failed");
195+
196+
bool proofIsIncludedBool = abi.decode(proofIsIncluded, (bool));
197+
198+
require(proofIsIncludedBool, "proof not included in batch");
199+
```
200+
201+
Finally, if the proof was verified, the contract sends a NFT to the user
202+
203+
```solidity
204+
// contracts/src/VerifierContract.sol
205+
206+
_mint(msg.sender, tokenId);
207+
_setTokenURI(
208+
tokenId,
209+
"ipfs://QmUKviny9x2oQUegyJFFBAUU2q5rvu5CsPzrUaBSDukpHQ"
210+
);
211+
```
212+
213+
### App
214+
215+
The first part of the app takes the answers of the user via CLI.
216+
Once the user answer the questions, we prepare them and initiate the prover, as follows:
217+
218+
```rust
219+
// script/src/main.rs
220+
221+
// Include the bytes of the compiled program.
222+
const ELF: &[u8] = include_bytes!("../../program/elf/riscv32im-succinct-zkvm-elf");
223+
224+
// Generate proof.
225+
let mut stdin = SP1Stdin::new();
226+
227+
stdin.write(&user_awnsers);
228+
229+
println!("Generating Proof ");
230+
231+
let client = ProverClient::new();
232+
let (pk, vk) = client.setup(ELF);
233+
234+
let Ok(proof) = client.prove(&pk, stdin).run() else {
235+
println!("Incorrect answers!");
236+
return;
237+
};
238+
239+
println!("Proof generated successfully. Verifying proof...");
240+
client.verify(&proof, &vk).expect("verification failed");
241+
println!("Proof verified successfully.");
242+
```
243+
244+
Now we can send the generated proof to Aligned using the SDK.
245+
246+
```rust
247+
// script/src/main.rs
248+
249+
// Serialize the proof to later save in a file.
250+
let proof = bincode::serialize(&proof).expect("Failed to serialize proof");
251+
252+
// Preparing the data needed for verification in Aligned
253+
let verification_data = VerificationData {
254+
proving_system: ProvingSystemId::SP1,
255+
proof,
256+
proof_generator_addr: wallet.address(),
257+
vm_program_code: Some(ELF.to_vec()),
258+
verification_key: None,
259+
pub_input: None,
260+
};
261+
262+
let max_fee = estimate_fee(&rpc_url, PriceEstimate::Default)
263+
.await
264+
.expect("failed to fetch gas price from the blockchain");
265+
266+
let max_fee_string = ethers::utils::format_units(max_fee, 18).unwrap();
267+
268+
let nonce = get_next_nonce(&rpc_url, wallet.address(), NETWORK)
269+
.await
270+
.expect("Failed to get next nonce");
271+
272+
// Submit to Aligned.
273+
let aligned_verification_data = submit_and_wait_verification(
274+
BATCHER_URL,
275+
&rpc_url,
276+
NETWORK,
277+
&verification_data,
278+
max_fee,
279+
wallet.clone(),
280+
nonce,
281+
)
282+
.await
283+
.unwrap();
284+
```
285+
286+
Finally, if the proof was sent to Aligned correctly, we can interact with our verifier Smart Contract to verify that the proof was correctly posted in aligned and claim the NFT.
287+
288+
```rust
289+
// script/src/main.rs
290+
291+
// Sends a transaction to the verifier contract with the
292+
// verification data provided by aligned
293+
claim_nft_with_verified_proof(
294+
&aligned_verification_data,
295+
signer,
296+
&args.verifier_contract_address,
297+
)
298+
.await
299+
.expect("Claiming of NFT failed ...");
300+
```
301+
302+
You can find the full code of the proof submission and verification in the [ZKQuiz App](../../examples/zkquiz/quiz/script/src/main.rs).

0 commit comments

Comments
 (0)