### Install Go Merkle Tree SQL Dependency Source: https://docs.iden3.io/getting-started/mt This snippet shows the command to install the `go-merkletree-sql` library, which is a required dependency for working with Sparse Merkle Trees in Go. It uses the `go get` command to fetch the package from GitHub. ```Go go get github.com/iden3/go-merkletree-sql ``` -------------------------------- ### Go: Install Iden3 Authentication Library Source: https://docs.iden3.io/protocol/zklogin Provides the `go get` command to install the official `go-iden3-auth` library. This library is essential for interacting with the Iden3 protocol, enabling the generation and verification of authentication requests and proofs. ```Go go get https://github.com/iden3/go-iden3-auth ``` -------------------------------- ### Install Go-Iden3-Core Dependency Source: https://docs.iden3.io/getting-started/claim/generic-claim This command updates the required Go dependencies by fetching the `go-iden3-core` library. This library is essential for interacting with the iden3 protocol and programmatically creating claims. ```go go get github.com/iden3/go-iden3-core ``` -------------------------------- ### Clone Identity Tutorial Examples Repository Source: https://docs.iden3.io/getting-started/state-transition/state-transition-proof This command clones the `tutorial-examples` GitHub repository, which contains the pre-compiled `stateTransition` circuit necessary for generating the proof. This repository is essential for proceeding with the proof generation steps. ```bash git clone https://github.com/iden3/tutorial-examples.git ``` -------------------------------- ### Example DID for Ethereum Mainnet (iden3) Source: https://docs.iden3.io/getting-started/identity/identifier Provides a concrete example of a Decentralized Identifier (DID) using the `iden3` method, specifically for the Ethereum Mainnet, demonstrating the full DID structure with a base58-encoded ID. ```text did:iden3:eth:mainnet:11AbuG9EKnWVXK1tooT2NyStQod2EnLhfccSajkwJA ``` -------------------------------- ### Example Solidity Calldata Output for ZK-Proof Verification Source: https://docs.iden3.io/getting-started/state-transition/state-transition-proof This is an example of the output generated by the `snarkjs generatecall` command. It's a JSON-formatted string array containing the proof components (`a`, `b`, `c`) and the public inputs, structured for direct use in a Solidity smart contract's verification function. This data enables on-chain verification of the zero-knowledge proof. ```json ["0x0c98dbb5bcdc4810a976b9804972c6086e855532740ab2c611fbcf4a5d939f91", "0x1f3b6aa1cfe69a2a3f5e8e7db5ccae0d269fc66be6d0c364469486d5718431ee"],[["0x21f67821a25f3b0eb008e8aa840706c6dd9c1cff16ec6f138d7745aff350dbbb", "0x255b9f12a90b1f1089af5edcda19fb6d592096f6ba7ce2438ce4ecc48399687d"],["0x1568f9a5a84d72a31b90d26b5035030b0b02544dcba18f0a3740f80b9632942d", "0x28dcba6dd58878a3383fd556d27118a3e905f424d23afa30b71de3ac000822de"]],["0x15adbb5f1abe4418a7ea7f876164b57bf70f88183fa7d85406be4cb5f8fee261", "0x04466d6e7131a89fdcf5136b52ed2b52e00755ad77c97bb87e8afa690eeef5e4"],["0x000a501c057d28c0c50f91062730531a247474274ff6204a4f7da6d4bcb70000","0x1c057d28c0c50f91062730531a247474274ff6204a4f7da6d4bcb7d23be4d605","0x203034fdafe4563e84962f2b16fefe8ebedb1be5c05b7d5e5e30898d799192fd","0x0000000000000000000000000000000000000000000000000000000000000001"] ``` -------------------------------- ### Import State Contract from Mumbai Testnet Address Source: https://docs.iden3.io/getting-started/state-transition/on-chain-state-transition This code demonstrates how to get an instance of the `State` contract using `hre.ethers.getContractAt`. It connects to an existing deployment of the contract on the Mumbai testnet at the specified address, allowing subsequent interactions with its functions. ```JavaScript const contract = await hre.ethers.getContractAt("State", "0xEA9aF2088B4a9770fC32A12fD42E61BDD317E655"); ``` -------------------------------- ### Example DID for Polygon Mumbai Testnet (polygonid) Source: https://docs.iden3.io/getting-started/identity/identifier Presents another concrete example of a Decentralized Identifier (DID), this time using the `polygonid` method for the Polygon Mumbai testnet, illustrating the DID structure with a different network and ID. ```text did:polygonid:polygon:mumbai:2qCU58EJgrEMAMwdTehMoxtopwP1gKXCEt9GGeVDaG ``` -------------------------------- ### AuthBJJCredential Claim Entry Structure Example Source: https://docs.iden3.io/protocol/bjjkey This example illustrates the detailed structure of an AuthBJJCredential claim entry, showing the allocation of bits for various fields within the Index and Value data slots. It specifies how the auth schema, header flags, Baby Jubjub public key components (X and Y parts), revocation nonce, and expiration timestamp are represented. ```Schema Index: i_0: [ 128 bits] 269270088098491255471307608775043319525 // auth schema (big integer from ca938857241db9451ea329256b9c06e5) [ 32 bits ] 00010000000000000000 // header flags: first 000 - self claim 1 - expiration is set. [ 32 bits ] 0 [ 61 bits ] 0 i_1: [ 253 bits] 0 i_2: [ 253 bits] 15730379921066174438220083697399546667862601297001890929936158339406931652649 // x part of BJJ pubkey i_3: [ 253 bits] 5635420193976628435572861747946801377895543276711153351053385881432935772762 // y part of BJJ pubkey Value: v_0: [ 64 bits ] 2484496687 // revocation nonce [ 64 bits ] 1679670808 // expiration timestamp [ 125 bits] 0 v_1: [ 253 bits] 0 v_2: [ 253 bits] 0 v_3: [ 253 bits] 0 ``` -------------------------------- ### Example: Iden3 AuthClaim JSON Output Source: https://docs.iden3.io/getting-started/claim/auth-claim This snippet shows an example of the raw JSON array output for a generated Iden3 `AuthClaim`. It represents the serialized form of the claim, containing various numerical components including the schema hash, public key coordinates, and revocation nonce. ```Text Claim: ["304427537360709784173770334266246861770","0","123600313554666674016417539553803069640123059319318064423431939497447916655340","7208907202894542671711125895887320665787554014901011121180092863817137691080","1","0","0","0"] ``` -------------------------------- ### Example JSON Representation of a Generic Claim Source: https://docs.iden3.io/getting-started/claim/generic-claim This snippet shows the JSON array representation of a generic claim generated by the Go code. It illustrates the compact format of the claim data, where the first four values represent the 'Index' part and the last four represent the 'Value' part, as defined by the iden3 protocol. ```json ["3613283249068442770038516118105710406958","86645363564555144061174553487309804257148595648980197130928167920533372928","19960424","1","227737944108667786680629310498","0","0","0"] ``` -------------------------------- ### Example Merkle Tree Entry Mapping Source: https://docs.iden3.io/w3c/merklization Provides a concrete example of how a specific JSON-LD field, such as 'expirationDate', is mapped to a key-value pair for inclusion in the Merkle Tree. The URL acts as the path (key) and the timestamp as the value. ```Conceptual map[https://www.w3.org/2018/credentials#expirationDate] = 1890994792000000000 ``` -------------------------------- ### Sparse Merkle Tree Entry for Inclusion Proof Source: https://docs.iden3.io/w3c/merklization This example demonstrates how a JSON-LD entry, such as 'birthCountry->Spain', is represented as a key-value pair for inclusion in a Sparse Merkle Tree. This mapping is used to generate a proof of inclusion for the element within the tree. ```Pseudocode map["http://schema.org/credentialSubject", "https://w3id.org/citizenship#birthCountry"] = "Spain" ``` -------------------------------- ### Example: Destructured Iden3 AuthClaim Components Source: https://docs.iden3.io/getting-started/claim/auth-claim This snippet provides a detailed breakdown of the components within the `AuthClaim` output, clarifying which parts of the claim array correspond to the schema hash, public key coordinates (X and Y), and the revocation nonce. It distinguishes between the 'Index' and 'Value' sections of the claim data. ```Text Index: { "304427537360709784173770334266246861770", // Schema hash "0", "12360031355466667401641753955380306964012305931931806442343193949747916655340", // X coordinate of the pubkey "7208907202894542671711125895887320665787554014901011121180092863817137691080" // Y coordinate of the pubkey } Value: { "1", // revocation nonce "0", "0", // first value data slot "0" // second value data slot } ``` -------------------------------- ### JSON-LD Document Compact Format Example Source: https://docs.iden3.io/w3c/merklization Illustrates a JSON-LD document in its compact form, using shorthand terms for IRIs. This format is typically converted to an expanded format before merklization to ensure predictable ordering. ```JSON { "@context": [ "http://schema.org/", "https://w3id.org/citizenship/v1", "https://www.w3.org/2018/credentials/v1"], "@type": "Person", "name": "Jane Doe", "jobTitle": "Professor", "credentialSubject": { "@type": "PermanentResident", "birthCountry": "Spain" } } ``` -------------------------------- ### Example JSON-LD Document for Merklization Source: https://docs.iden3.io/w3c/merklization A sample JSON-LD document representing a 'Person' with various attributes like name, job title, and telephone. This document serves as a typical input for the Merkle Tree conversion process, demonstrating the structure that will be transformed into RDF Quads and then key-value pairs. ```JSON { "@context": "http://schema.org/", "@type": "Person", "name": "Jane Doe", "jobTitle": "Professor", "telephone": "(425) 123-4567"} ``` -------------------------------- ### Example of Ethereum-controlled Identity ID (Bytes & Base58) Source: https://docs.iden3.io/getting-started/identity/identity-types This example demonstrates the construction of an Ethereum-controlled identity ID, showing the concatenation of ID type, Ethereum address, and checksum. It also provides the resulting ID in both byte and Base58 representations. ```Text idType: 0212 // DID method: PolygonID; Network: Polygon Mumbai + ethAddress: 0x0dcd1bf9a1b36ce34237eeafef220932846bcd82 + // uint16 sum of bytes of the byte string: idType + zeroPadding + ethAddress. // Note that the bytes of the uint16 are in reversed order, e.g. if sum is 0x0a45 then checksum is 0x450a checksum: 450a === id: 0212000000000000000dcd1bf9a1b36ce34237eeafef220932846bcd82450a (bytes) id: 2qCU58EJgrELSJT6EzT27Rw9DhvwamAdbMLpePztYq (base58) ``` -------------------------------- ### Install Go Iden3 Baby Jubjub Cryptography Dependency Source: https://docs.iden3.io/getting-started/babyjubjub This command fetches and adds the `github.com/iden3/go-iden3-crypto/babyjub` package to the Go module's dependencies. This package provides the necessary cryptographic primitives for working with Baby Jubjub elliptic curves within the Iden3 ecosystem. ```Go go get github.com/iden3/go-iden3-crypto/babyjub ``` -------------------------------- ### JSON Query with Multiple Requests for Atomic Circuit Source: https://docs.iden3.io/protocol/querylanguage This JSON example demonstrates how to construct a single query that includes multiple verification requests for an atomic circuit. It allows for the verification of different claim types (e.g., KYC Age Credential and KYC Country of Residence Credential) from potentially different schemas and with varying query conditions within one transaction. ```JSON { "circuit_id": "atomicQueryMTP", "type": "zkp", "rules": { "query": [ { "allowedIssuers": [ "115zTGHKvFeFLPu3vF9Wx2gBqnxGnzvTpmkHPM2LCe" ], "schema": [ { "url": "https://raw.githubusercontent.com/iden3/claim-schema-vocab/main/schemas/json-ld/kyc-v2.json-ld", "type": "KYCAgeCredential" } ], "challenge": 12345678, "req": { "birthdate": { "$lt": 20000101 } } }, { "allowedIssuers": [ "115zTGHKvFeFLPu3vF9Wx2gBqnxGnzvTpmkHPM2LCe" ], "schema": [ { "type": "KYCCountryOfResidenceCredential", "url": "ipfs://QmP8NrKqoBKjmKwMsC8pwBCBxXR2PhwSepwXx31gnJxAbP" } ], "challenge": 12345678, "req": { "country": { "$nin": [ 840, 123 ] } } } ] } } ``` -------------------------------- ### Go Example: Calculate Schema Hash for Claim Schema Source: https://docs.iden3.io/protocol/claim-schema Illustrates how to compute a unique schema hash for a claim schema's identifier in Go. It uses the Keccak256 hash function on the schema's @id string and then extracts a specific portion of the hash to form the SchemaHash. ```Go var sHash core.SchemaHash h := Keccak256([]byte("https://raw.githubusercontent.com/iden3/claim-schema-vocab/main/schemas/json-ld/kyc-v4.jsonld#KYCAgeCredential")) copy(sHash[:], h[len(h)-16:]) sHashHex, _ := sHash.MarshalText() fmt.Println(string(sHashHex)) ``` -------------------------------- ### Example JSON-LD Document for Normalization Source: https://docs.iden3.io/w3c/merklization This JSON-LD document illustrates a scenario with a 'verifiableCredential' array containing multiple graph objects. It is used to demonstrate how normalization processes multigraph documents and reorders elements based on canonical sorting rules, leading to changes in path indexing. ```JSON { "@context":[ "https://www.w3.org/2018/credentials/v1", "https://raw.githubusercontent.com/iden3/claim-schema-vocab/main/schemas/json-ld/kyc-v3.json-ld", "https://raw.githubusercontent.com/iden3/claim-schema-vocab/main/schemas/json-ld/iden3credential-v2.json-ld" ], "@type":"VerifiablePresentation", "verifiableCredential":[ { "@id": "http://example.com/vc1", "@type":"KYCAgeCredential", "birthday":19960424 }, { "@id": "http://example.com/vc3", "@type": "Iden3SparseMerkleTreeProof", "issuerData": { "state": { "blockTimestamp": 123 } } } ] } ``` -------------------------------- ### Sequence Diagram for Non-Revocation Proof Construction Source: https://docs.iden3.io/services/rhs This sequence diagram illustrates the step-by-step interaction flow required to construct a non-revocation proof. It shows how a user interacts with the State Smart Contract to get the latest identity state, then with the RHS Storage to fetch tree roots and traverse the revocation tree, ultimately calculating the proof. ```Mermaid sequenceDiagram participant User participant SmartContract as State Smart Contract participant RHS as RHS Storage User->>SmartContract: Request latest identity state SmartContract->>User: Return latest identity state User->>RHS: Fetch roots of trees using identity state RHS->>User: Return roots of trees [ClR, ReR, RoR] User->>RHS: Request children of revocation root(ReR) RHS->>User: Return [left,right] nodes loop until leaf node is found or max depth is reached User->>RHS: Request children of node RHS->>User: Return [left,right] nodes end User->>User: Calculate Proof ``` -------------------------------- ### Go Example for Off-Chain RHS Storage Interaction Source: https://docs.iden3.io/services/rhs This Go code snippet demonstrates how to interact with an off-chain Reverse Hash Service (RHS) to fetch identity state roots and generate non-revocation proofs. It utilizes the `go-merkletree-sql` and `merkletree-proof/http` libraries, connecting to a specified RHS URL to retrieve and process Merkle tree nodes and proofs for a given identity state and revocation nonce. ```Go package main import ( "context" "encoding/json" "fmt" "math/big" "github.com/iden3/go-merkletree-sql/v2" proof "github.com/iden3/merkletree-proof/http" ) func main() { ctx := context.Background() rhsURL := "https://rhs-staging.polygonid.me" state := "e12084d0d72c492c703a2053b371026bceda40afb9089c325652dfd2e5e11223" revocationNonce, _ := merkletree.NewHashFromBigInt(big.NewInt(670966937)) cli := &proof.ReverseHashCli{URL: rhsURL} // get identity state roots (ClT root, ReT root, RoT root) node := getIdentityStateRoots(cli, ctx, state) json, err := json.Marshal(node) if err != nil { panic(err) } fmt.Println(string(json)) // get non-revocation proof by ReT root and revocation nonce proof, err := cli.GenerateProof(ctx, node.Children[1], revocationNonce) if err != nil { panic(err) } jsonProof, err := proof.MarshalJSON() if err != nil { panic(err) } fmt.Println(string(jsonProof)) } func getIdentityStateRoots(cli *proof.HTTPReverseHashCli, ctx context.Context, state string) proof.Node { s, err := merkletree.NewHashFromHex(state) if err != nil { panic(err) } stateValues, err := cli.GetNode(ctx, s) if err != nil { panic(err) } return stateValues } ``` -------------------------------- ### Initialize Go Module for Iden3 Tutorial Source: https://docs.iden3.io/getting-started/babyjubjub This command initializes a new Go module named `example/iden3-tutorial`, creating a `go.mod` file in the current directory. It's the foundational step for setting up a Go project to interact with Iden3 Protocol components. ```Go go mod init example/iden3-tutorial ``` -------------------------------- ### Configure Mumbai Network in Hardhat Source: https://docs.iden3.io/getting-started/state-transition/on-chain-state-transition This snippet shows how to add the Mumbai testnet configuration to your `hardhat.config.js` file. It requires environment variables for the RPC URL and a private key to connect to the network, enabling Hardhat to deploy and interact with contracts on Mumbai. ```JavaScript networks: { mumbai: { url: `${process.env.MUMBAI_RPC_URL}`, accounts: [`${process.env.MUMBAI_PRIVATE_KEY}`] } } ``` -------------------------------- ### Generate State Transition Proof with SnarkJS Source: https://docs.iden3.io/getting-started/state-transition/state-transition-proof This command executes the `generate.sh` script from the compiled-circuits folder, initiating the proof generation process for the `stateTransition` circuit using SnarkJS. It requires the `input.json` file, created in a previous step, to be present in the `stateTransition/stateTransition_js` directory. ```bash ./generate.sh stateTransition ``` -------------------------------- ### Implement and Test Sparse Merkle Tree in Go Source: https://docs.iden3.io/getting-started/mt This Go program demonstrates the creation and basic operations of a Sparse Merkle Tree using the `go-merkletree-sql` library. It initializes a tree, adds two leaves with specific indices and values, and then generates and prints proofs for both membership (an existing leaf) and non-membership (a non-existent leaf). ```Go package main import ( "context" "fmt" "math/big" merkletree "github.com/iden3/go-merkletree-sql" "github.com/iden3/go-merkletree-sql/db/memory" ) // Sparse MT func main() { ctx := context.Background() // Tree storage store := memory.NewMemoryStorage() // Generate a new MerkleTree with 32 levels mt, _ := merkletree.NewMerkleTree(ctx, store, 32) // Add a leaf to the tree with index 1 and value 10 index1 := big.NewInt(1) value1 := big.NewInt(10) mt.Add(ctx, index1, value1) // Add another leaf to the tree index2 := big.NewInt(2) value2 := big.NewInt(15) mt.Add(ctx, index2, value2) // Proof of membership of a leaf with index 1 proofExist, value, _ := mt.GenerateProof(ctx, index1, mt.Root()) fmt.Println("Proof of membership:", proofExist.Existence) fmt.Println("Value corresponding to the queried index:", value) // Proof of non-membership of a leaf with index 4 proofNotExist, _, _ := mt.GenerateProof(ctx, big.NewInt(4), mt.Root()) fmt.Println("Proof of membership:", proofNotExist.Existence) } ``` -------------------------------- ### Export ZK-Proof as Solidity Calldata Source: https://docs.iden3.io/getting-started/state-transition/state-transition-proof This command uses SnarkJS to convert the generated `proof.json` and `public.json` files into a format suitable for Solidity smart contracts. The output is a single string array representing the proof and public inputs, ready for direct use in an on-chain verification function. ```bash snarkjs generatecall ``` -------------------------------- ### Define Inputs for Identity State Transition Proof Source: https://docs.iden3.io/getting-started/state-transition/on-chain-state-transition This snippet defines the necessary input variables for executing a state transition on the `State` contract. These inputs, including `id`, `oldState`, `newState`, `isOldStateGenesis`, and proof components `a`, `b`, `c`, are derived from a previously generated ZK proof and are crucial for the `transitState` function. ```JavaScript const id = "0x000a501c057d28c0c50f91062730531a247474274ff6204a4f7da6d4bcb70000" const oldState = "0x1c057d28c0c50f91062730531a247474274ff6204a4f7da6d4bcb7d23be4d605" const newState = "0x203034fdafe4563e84962f2b16fefe8ebedb1be5c05b7d5e5e30898d799192fd" const isOldStateGenesis = "0x0000000000000000000000000000000000000000000000000000000000000001" const a = ["0x0c98dbb5bcdc4810a976b9804972c6086e855532740ab2c611fbcf4a5d939f91", "0x1f3b6aa1cfe69a2a3f5e8e7db5ccae0d269fc66be6d0c364469486d5718431ee"] const b = [["0x21f67821a25f3b0eb008e8aa840706c6dd9c1cff16ec6f138d7745aff350dbbb", "0x255b9f12a90b1f1089af5edcda19fb6d592096f6ba7ce2438ce4ecc48399687d"],["0x1568f9a5a84d72a31b90d26b5035030b0b02544dcba18f0a3740f80b9632942d", "0x28dcba6dd58878a3383fd556d27118a3e905f424d23afa30b71de3ac000822de"]] const c = ["0x15adbb5f1abe4418a7ea7f876164b57bf70f88183fa7d85406be4cb5f8fee261", "0x04466d6e7131a89fdcf5136b52ed2b52e00755ad77c97bb87e8afa690eeef5e4"] ``` -------------------------------- ### Go: Unpack Message and Verify Zero-Knowledge Proof Source: https://docs.iden3.io/protocol/zklogin Illustrates the initial steps of the `/call-back` handler, showing how to unpack the raw incoming message bytes into a structured Iden3 message using a `PlainMessagePacker`. Following this, it demonstrates calling `auth.VerifyProofs` to validate the embedded zero-knowledge proof. ```Go p := &packer.PlainMessagePacker{} // Unpack msg message, _ := p.Unpack(msgBytes) // verify zkp proofErr := auth.VerifyProofs(message) ``` -------------------------------- ### JSON-LD Document Expanded Format Example Source: https://docs.iden3.io/w3c/merklization Shows a JSON-LD document after expansion and normalization (URDNA2015 algorithm). This format uses full IRIs and ensures predictable ordering, making it suitable for Merkle tree processing. ```JSON [ { "@type": [ "http://schema.org/Person" ], "http://schema.org/credentialSubject": [ { "@type": [ "https://w3id.org/citizenship#PermanentResident" ], "https://w3id.org/citizenship#birthCountry": [ { "@value": "Spain" } ] } ], "http://schema.org/jobTitle": [ { "@value": "Professor" } ], "http://schema.org/name": [ { "@value": "Jane Doe" } ] } ] ``` -------------------------------- ### Go: Basic Web Server for Iden3 Authentication Source: https://docs.iden3.io/protocol/zklogin Sets up a simple Go HTTP server with two handlers: `/sign-in` for initiating the authentication flow and `/call-back` for receiving the mobile application's response. This forms the foundational structure for the Iden3 authentication backend. ```Go func main() { http.HandleFunc("/sign-in", signIn) http.HandleFunc("/call-back", callBack) http.ListenAndServe(":8001", nil) } func signIn(w http.ResponseWriter, req *http.Request) { } func callBack(w http.ResponseWriter, req *http.Request) { } ``` -------------------------------- ### Creating Iden3 Identity Trees and Adding AuthClaim in Go Source: https://docs.iden3.io/getting-started/identity/identity-state This Go snippet demonstrates how to initialize three empty Merkle trees: Claims, Revocation, and Roots, using `go-merkletree-sql`. It then shows how to create an `authClaim` with `go-iden3-core` and add its hash index and value to the Claims tree. The Revocation tree is for revoking claims, and the Roots tree tracks updates to the Claims tree. ```Go package main import ( "context" "fmt" core "github.com/iden3/go-iden3-core" "github.com/iden3/go-merkletree-sql/v2" "github.com/iden3/go-merkletree-sql/v2/db/memory" ) // Generate the three identity trees func main() { ctx := context.Background() // Create empty Claims tree clt, _ := merkletree.NewMerkleTree(ctx, memory.NewMemoryStorage(), 40) // Create empty Revocation tree ret, _ := merkletree.NewMerkleTree(ctx, memory.NewMemoryStorage(), 40) // Create empty Roots tree rot, _ := merkletree.NewMerkleTree(ctx, memory.NewMemoryStorage(), 40) authClaim := core.NewClaim(core.AuthSchemaHash, core.WithIndexDataInts(X, Y), core.WithRevocationNonce(0)) // Get the Index and the Value of the authClaim hIndex, hValue, _ := authClaim.HiHv() // add auth claim to claims tree with value hValue at index hIndex clt.Add(ctx, hIndex, hValue) // print the roots fmt.Println(clt.Root().BigInt(), ret.Root().BigInt(), rot.Root().BigInt()) } ``` -------------------------------- ### stateTransition Circuit API Reference Source: https://docs.iden3.io/protocol/main-circuits This section details the instantiation parameters and inputs required for the `stateTransition.circom` circuit. It outlines the public and private inputs necessary for executing an identity state transition, including user ID, old and new states, Merkle tree proofs, and signature components. ```APIDOC stateTransition Circuit: Purpose: Checks the execution of an identity state transition by taking old and new identity states as inputs. Instantiation Parameters: idOwnershipLevels: Merkle tree depth level for Identity Trees (claims Tree, revocation Tree and roots Tree) Inputs: userID: Prover's (Genesis) Identifier (Public) oldUserState: Prover's Identity State (before transition) (Public) newUserState: Prover's Identity State (after transition) (Public) isOldStateGenesis: "1" indicates that the old state is genesis: it means that this is the first State Transition, otherwise "0" (Public) claimsTreeRoot: Prover's Claims Tree Root (Private) authClaimMtp[idOwnershipLevels]: Merkle Tree Proof of Auth Claim inside Prover's Claims tree (Private) authClaim[8]: Prover's Auth Claim (Private) revTreeRoot: Prover's Revocation Tree Root (Private) authClaimNonRevMtp[idOwnershipLevels]: Merkle Tree Proof of non membership of Auth Claim inside Prover's Revocation Tree (Private) authClaimNonRevMtpNoAux: Flag that indicates whether to check the auxiliary Node (Private) authClaimNonRevMtpAuxHv: Auxiliary Node Value (Private) authClaimNonRevMtpAuxHi: Auxiliary Node Index (Private) rootsTreeRoot: Prover's Roots Tree Root (Private) signatureR8x: Signature of the challenge (Rx point) (Private) signatureR8y: Signature of the challenge (Ry point) (Private) signatureS: Signature of the challenge (S point) (Private) newClaimsTreeRoot: Claim Tree Root of the Prover after State Transtion is executed (Private) newAuthClaimMtp[IdOwnershipLevels]: Merkle Tree Proof of existance of the Prover's Auth Claim inside the Claims Tree after State Transtion is executed (Private) newRevTreeRoot: Revocation Tree Root of the Prover after State Transtion is executed (Private) newRootsTreeRoot: Roots Tree Root of the Prover after State Transtion is executed (Private) ``` -------------------------------- ### Update Go Dependencies for Iden3 Circuits Source: https://docs.iden3.io/getting-started/state-transition/new-identity-state This command updates the Go module dependencies, specifically fetching the `github.com/iden3/go-circuits` package. This is a prerequisite step to ensure all necessary libraries are available for building and running applications that interact with Iden3 identity circuits. ```Go go get github.com/iden3/go-circuits ``` -------------------------------- ### Go: Generate an Iden3 Key Authorization Claim Source: https://docs.iden3.io/getting-started/claim/auth-claim This Go code demonstrates how to create an `AuthClaim` using the `go-iden3-core` library. It initializes the claim with a pre-defined schema hash, includes the Baby Jubjub public key coordinates (X and Y) in the index data slots, and sets a revocation nonce. The resulting claim object is then marshaled to JSON and printed to the console. ```Go package main import ( "encoding/json" "fmt" "github.com/iden3/go-iden3-core" "github.com/iden3/go-iden3-crypto/babyjub" ) // Create auth claim func main() { authSchemaHash, _ := core.NewSchemaHashFromHex("ca938857241db9451ea329256b9c06e5") // Add revocation nonce. Used to invalidate the claim. This may be a random number in the real implementation. revNonce := uint64(1) // Create auth Claim authClaim, _ := core.NewClaim(authSchemaHash, core.WithIndexDataInts(babyJubjubPubKey.X, babyJubjubPubKey.Y), core.WithRevocationNonce(revNonce)) authClaimToMarshal, _ := json.Marshal(authClaim) fmt.Println(string(authClaimToMarshal)) } ``` -------------------------------- ### authV2 Circuit Instantiation Parameters Source: https://docs.iden3.io/protocol/main-circuits This section describes the parameters required to instantiate the `authV2` circuit. It includes `IdOwnershipLevels` for Merkle tree depths of identity trees (claims, revocation, roots) and `onChainLevels` for the Merkle tree depth of the GIST stored on-chain. ```APIDOC Instantiation Parameters: - IdOwnershipLevels: Merkle tree depth levels for Identity Trees (claims Tree, revocation Tree and roots Tree) - onChainLevels: Merkle tree depth of GIST stored on chain ``` -------------------------------- ### Add New Claim and Fetch Identity State in Go Source: https://docs.iden3.io/getting-started/state-transition/new-identity-state This Go program demonstrates the complete process of adding a new claim to an Iden3 Claims Tree and deriving the new identity state. It includes generating Merkle Tree proofs for existing claims, creating a new claim with a schema and index data, adding it to the claims tree, and then signing the state transition. Finally, it marshals the `StateTransitionInputs` into a JSON format, which can be directly used as inputs for a State Transition Circuit. ```Go package main import ( "encoding/hex" "fmt" "math/big" "github.com/iden3/go-circuits" core "github.com/iden3/go-iden3-core" "github.com/iden3/go-iden3-crypto/poseidon" "github.com/iden3/go-merkletree-sql" ) // Change Identity State func main() { // GENESIS STATE: // 1. Generate Merkle Tree Proof for authClaim at Genesis State authMTPProof, _, _ := clt.GenerateProof(ctx, hIndex, clt.Root()) // 2. Generate the Non-Revocation Merkle tree proof for the authClaim at Genesis State authNonRevMTPProof, _, _ := ret.GenerateProof(ctx, new(big.Int).SetUint64(revNonce), ret.Root()) // Snapshot of the Genesis State genesisTreeState := circuits.TreeState{ State: state, ClaimsRoot: clt.Root(), RevocationRoot: ret.Root(), RootOfRoots: rot.Root(), } // STATE 1: // Before updating the claims tree, add the claims tree root at Genesis state to the Roots tree. rot.Add(ctx, clt.Root().BigInt(), big.NewInt(0)) // Create a new random claim schemaHex := hex.EncodeToString([]byte("myAge_test_claim")) schema, _ := core.NewSchemaHashFromHex(schemaHex) code := big.NewInt(51) newClaim, _ := core.NewClaim(schema, core.WithIndexDataInts(code, nil)) // Get hash Index and hash Value of the new claim hi, hv, _ := newClaim.HiHv() // Add claim to the Claims tree clt.Add(ctx, hi, hv) // Fetch the new Identity State newState, _ := merkletree.HashElems( clt.Root().BigInt(), ret.Root().BigInt(), rot.Root().BigInt()) // Snapshot of the new tree State newTreeState := circuits.TreeState{ State: newState, ClaimsRoot: clt.Root(), RevocationRoot: ret.Root(), RootOfRoots: rot.Root(), } // Sign a message (hash of the genesis state + the new state) using your private key hashOldAndNewStates, _ := poseidon.Hash([]*big.Int{state.BigInt(), newState.BigInt()}) signature := babyJubjubPrivKey.SignPoseidon(hashOldAndNewStates) authClaimNewStateIncMtp, _, _ := clt.GenerateProof(ctx, hIndex, newTreeState.ClaimsRoot) // Generate state transition inputs stateTransitionInputs := circuits.StateTransitionInputs{ ID: id, OldTreeState: genesisTreeState, NewTreeState: newTreeState, IsOldStateGenesis: true, AuthClaim: authClaim, AuthClaimIncMtp: authMTPProof, AuthClaimNonRevMtp: authNonRevMTPProof, AuthClaimNewStateIncMtp: authClaimNewStateIncMtp, Signature: signature, } // Perform marshalling of the state transition inputs inputBytes, _ := stateTransitionInputs.InputsMarshal() fmt.Println(string(inputBytes)) } ``` -------------------------------- ### REST API Endpoints for Off-Chain RHS Storage Source: https://docs.iden3.io/services/rhs These API endpoints define the interaction for the off-chain Reverse Hash Service. The POST endpoint allows clients to save a node by providing its hash and children, while the GET endpoint enables retrieval of a node's preimage by its hash. This facilitates key-value storage over HTTP. ```APIDOC /POST {{server}}/node Content-Type: application/json { "hash":"2c32381aebce52c0c5c5a1fb92e726f66d977b58a1c8a0c14bb31ef968187325", "children":[ "658c7a65594ebb0815e1cc20f54284ccdb51bb1625f103c116ce58444145381e", "e809a4ed2cf98922910e456f1e56862bb958777f5ff0ea6799360113257f220f" ] } /GET {{server}}/node/{{hash}} ``` -------------------------------- ### Fetch Identity State After Transition Source: https://docs.iden3.io/getting-started/state-transition/on-chain-state-transition This snippet demonstrates how to retrieve the updated state information for a specific identity after a state transition. It uses the `getStateInfoById` function of the `State` contract and logs the identity's ID, confirming the successful update on-chain. ```JavaScript // Get state of identity without BigNumber let identityState = await contract.getStateInfoById(id); console.log("Identity State after state transition", identityState.id); // 18221365812082731933036101625854358571814024255404073202903829924181114880 ``` -------------------------------- ### Create a Generic Claim in Go Source: https://docs.iden3.io/getting-started/claim/generic-claim This Go program demonstrates how to construct a generic claim using the `go-iden3-core` library. It involves setting an expiration date, defining a schema hash (KYCAgeCredential), specifying data slots for birthday and document type, setting a revocation nonce, and assigning a subject ID, finally marshaling the claim to JSON. ```go package main import ( "encoding/json" "fmt" "math/big" "time" core "github.com/iden3/go-iden3-core" ) // create basic claim func main() { // set claim expriation date to 2361-03-22T00:44:48+05:30 t := time.Date(2361, 3, 22, 0, 44, 48, 0, time.UTC) // set schema ageSchema, _ := core.NewSchemaHashFromHex ("2e2d1c11ad3e500de68d7ce16a0a559e") // define data slots birthday := big.NewInt(19960424) documentType := big.NewInt(1) // set revocation nonce revocationNonce := uint64(1909830690) // set ID of the claim subject id, _ := core.IDFromString("113TCVw5KMeMp99Qdvub9Mssfz7krL9jWNvbdB7Fd2") // create claim claim, _ := core.NewClaim(ageSchema, core.WithExpirationDate(t), core.WithRevocationNonce(revocationNonce), core.WithIndexID(id), core.WithIndexDataInts(birthday, documentType)) // transform claim from bytes array to json claimToMarshal, _ := json.Marshal(claim) fmt.Println(string(claimToMarshal)) } ``` -------------------------------- ### Generate Identity Profile using Go-Iden3-Core Source: https://docs.iden3.io/getting-started/identity/identity-profile This Go code snippet demonstrates how to programmatically generate an Identity Profile using the `go-iden3-core` library. It initializes a `Genesis Identifier` and a `profileNonce`, then calls `core.ProfileID` to compute and print the resulting `ProfileID` string. ```Go package main import ( "fmt" "math/big" core "github.com/iden3/go-iden3-core" ) // Generate Identity Profile from Genesis Identifier func main() { id, _ := core.IDFromString("11BBCPZ6Zq9HX1JhHrHT3QKUFD9kFDEyJFoAVMptVs") profile, _ := core.ProfileID(id, big.NewInt(50)) fmt.Println(profile.String()) } ``` -------------------------------- ### Retrieve Claim Index and Value Hashes (Go) Source: https://docs.iden3.io/getting-started/signature-claim/signature This Go snippet demonstrates how to extract the raw slots (index and value) from a generic claim and then compute their respective Poseidon hashes. This is the first step in preparing a claim for signature issuance. ```Go claimIndex, claimValue := claim.RawSlots() indexHash, _ := poseidon.Hash(core.ElemBytesToInts(claimIndex[:])) valueHash, _ := poseidon.Hash(core.ElemBytesToInts(claimValue[:])) ``` -------------------------------- ### Execute Identity State Transition on Contract Source: https://docs.iden3.io/getting-started/state-transition/on-chain-state-transition This line of code calls the `transitState` function on the previously imported `State` contract instance. It passes all the prepared inputs (`id`, `oldState`, `newState`, `isOldStateGenesis`, `a`, `b`, `c`) to update the identity's state on the blockchain, marking a successful state transition. ```JavaScript await contract.transitState(id, oldState, newState, isOldStateGenesis, a, b, c); ```