Introduction

POD2 is a cryptographic standard that lets users share data together with proofs of relations about that data, while choosing what to reveal in a privacy-preserving way.

A POD is a set of statements together with a proof that they are valid. PODs can bring external data into the system (Introduction PODs), or be derived from other PODs and signed data (MainPODs). A POD2 proof can consume statements from other PODs and derive new, logically valid statements. The statements themselves express relations between units of data. When deriving a new POD, a user chooses which statements to expose as public and which to keep private, allowing fine-grained control over their privacy.

The POD2 stack consists of the following layers, from highest to lowest level:

ConceptImplementation
predicate languagePodlang
statement derivation kernelMainPOD plonky2 circuit
ZK proving systemplonky2
  • The predicate language allows the definition of the set of relations that a statement fulfills, and is the user-programmable part of the system.
  • The statement derivation kernel verifies that new statements are derived from other existing valid statements following logical rules.
  • The ZK proving system is the underlying mechanism used to obtain proofs of correct statement derivation that are succinct (small and fast to verify) and zero-knowledge (they hide private statements and intermediate results).

The Specification section describes the data model, statements and operations in detail, and the Architecture section describes how the implementation is organized.

Frontend and backend

The POD2 system consists of a frontend and a backend, connected by a middleware. This page outlines some design principles for deciding which components go where.

user -- frontend -- middleware -- backend -- ZK circuit

The frontend is what we want the user to see; the backend is what we want the circuit to see.

Circuit and proving system

The first implementation of POD2 uses Plonky2 as its proving system. In principle, a future implementation could use some other proving system. The frontend and middleware should not be aware of what proving system is in use: anything specific to the proving system belongs to the backend.

User-facing types versus in-circuit types

The frontend type system exposes human-readable types to POD developers: strings, ints, bools, and so forth. On the backend, all types are built out of field elements. The middleware should handle the conversion.

POD value types

From the frontend perspective, POD values may be one of the following types: atomic types

  • Int
  • Bool
  • String
  • PublicKey
  • SecretKey
  • Predicate
  • Untyped

and three compound types

  • Dictionary
  • Array
  • Set.

From the backend perspective, however, these types are all encoded as a fixed number of field elements (4 in the Plonky2 backend); the encodings are described in Backend types.

Int

A signed 64-bit integer (i64).

Bool

A boolean. It has the same encoding as an Int 0 (for false) or 1 (for true).

String

A UTF-8 string. Strings can only be compared for equality.

PublicKey and SecretKey

A public key (a point of the elliptic curve) and a secret key (a scalar) of the signature scheme.

Predicate

A predicate used as a value. This allows custom predicates to take other predicates as arguments.

Untyped

An untyped raw value, which exposes a backend Value on the frontend.

Dictionary, array, set

The array, set and dictionary types are similar types. While all of them use a merkletree under the hood, each of them uses it in a specific way:

  • dictionary: the keys are strings, which are hashed to be used as the leaf key; the leaf value is the backend value of the original value.
    • leaf.key=hash(original_key)
    • leaf.value=original_value
  • array: the elements are placed at the value field of each leaf, and the key field is just the array index (integer)
    • leaf.key=i
    • leaf.value=original_value
  • set: both the key and the value are set to the value.
    • leaf.key=original_value
    • leaf.value=original_value

In the three types, the merkletree under the hood allows to prove inclusion & non-inclusion of the particular entry of the {dictionary/array/set} element.

Since the backend only sees the Merkle root, a container may be interpreted as more than one type. For example, Dictionary{"a": "a"} and Set{"a"} have the same root, and so do Array[0] and Set{0}. All empty containers share the same root.

A concrete implementation of dictionary, array, set can be found at pod2/src/middleware/containers.rs.

Anchored keys

Rather than dealing with just keys, we introduce the notion of an anchored key, which is a pair consisting of a container (identified by its Merkle root) and a key, i.e.

type AnchoredKey = (Root, Key)
type Key = String | Int

String keys are used for dictionaries, and integer keys for arrays.

Statements can use anchored keys or literal values as arguments. Since our system uses constructive logic, if a statement that uses an anchored key in some of its arguments is proved, it means that a valid Merkle proof of the value behind it exists and was used at some point to construct a Contains statement that introduced that anchored key.

In PODLang, anchored key indexing can use subscript syntax foo["bar"] which allows any string key, or dot syntax foo.bar if the key is a valid identifier.

For example:

0: None
1: Contains(foo, "bar", 42) <- ContainsFromEntries 0 0 0 mt_proof
2: Lt(foo["bar"], 100) <- LtFromEntries 1 0
3: NotEqual(foo.bar, 100) <- LtToNotEqual 2

A statement with literal arguments can also be converted into one that uses anchored keys with the ReplaceValueWithEntry operation, given the Contains statements that introduce those anchored keys.

Backend types

On the backend, there is only a single type: Value.

A Value is simply a tuple of field elements. With the plonky2 backend, a Value is a tuple of 4 field elements. In general, the backend will expose a constant VALUE_SIZE, and a Value will be a tuple of VALUE_SIZE field elements.

Integers and booleans

The backend encoding stores integers in such a way that arithmetic operations (addition, multiplication, comparison) are inexpensive to verify in-circuit.

In the case of the Plonky2 backend, an integer (an i64) is first interpreted as a u64 via its two's complement representation, which is then decomposed as with and represented as where is the canonical projection.

We use -1 as a tag in the last limb in order to distinguish the encoding of 0 from an empty value with zeroes. -1 in the GoldilocksField has the canonical projection of 18446744069414584320 = 0xffffffff00000000.

On the backend, a boolean is stored as an integer, either 0 or 1; so logical operations on booleans are also inexpensive.

Strings

The backend encoding stores strings as hashes. For this reason, string operations (substrings, accessing individual characters) are hard to verify in-circuit. The POD2 system does not provide methods for manipulating strings.

In other words: As POD2 sees it, two strings are either equal or not equal. There are no other relationships between strings.

In the case of the Plonky2 backend, a string is converted to a sequence of bytes with the byte 0x01 appended as padding, then the bytes are split into 7-byte chunks starting from the left, these chunks then being interpreted as integers in little-endian form, each of which is naturally an element of GoldilocksField, whence the resulting sequence may be hashed via the Poseidon hash function. Symbolically, given a string , its hash is defined by

where poseidon is the Poseidon instance used by Plonky2, is as above, is defined such that1

the mapping is given by

and is the canonical mapping of a string to its UTF-8 representation.

Keys and predicates

A PublicKey (an elliptic curve point) and a SecretKey (a scalar) are represented by the Poseidon hash of their field element representation. A Predicate is represented by the hash of the predicate (see custom predicates).

Compound types

The three front-end compound types (Dictionary, Array, Set) are all represented as Merkle roots on the backend. The details of the representation are explained on a separate Merkle tree page.

1

Definitions of drop and take may be found here and here.

MerkleTree

In the POD2 backend, a MerkleTree is used to store an unordered set of key-value pairs. The frontend compound types Array, Set, and Dictionary are all represented as MerkleTrees on the backend.

From the high level, we can think of a MerkleTree as a 'hashmap' storage, that allows us to generate proofs of inclusion and non-inclusion of the key-values stored into it, as well as proofs of correct insertion, update and deletion.

A MerkleTree is represented in-circuit as its Merkle root; in the Plonky2 backend, this root is a tuple of four field elements. This makes a MerkleTree the same size in-circuit as the atomic types Int and String. (In general, regardless of the proof system used on the backend, all three types are represented in-circuit by the same number of field elements; this number is determined by the security requirement of the hash function.)

The encoding of the MerkleTree is a recursive process:

  • Encode all keys and values in the MerkleTree.
  • Put all keys and values into a sparse Merkle tree.
  • The MerkleTree is encoded in-circuit as the root of this sparse Merkle tree.

This document explains the construction of the sparse Merkle tree.

The branching rule

A sparse Merkle tree is implemented as a binary tree. The insertion path of any key is given by a deterministic rule: given key and a nonnegative integer depth, the rule determines that key belongs to either the left or right branch at depth depth.

The precise rule is as follows. The key is a backend value, which is a 4-tuple of field elements

key = (k_0, k_1, k_2, k_3).

Write the field elements in binary (in little-endian order):

k_0 = b_0 b_1 ... b_63
k_1 = b_64 b_65 ... b_127
....

At the root, key goes to the left subtree if b_0 = 0, otherwise the right subtree. At depth 1, key goes to the left subtree if b_1 = 0, otherwise the right subtree, and similarly for higher depth.

The key bits are used directly, without hashing. Dictionary keys are already hashes (of the key strings) and set keys are hashes for any non-integer value, so their paths are pseudo-random. Array keys are small integers, so arrays fill the tree densely from the left.

The tree structure

A Merkle tree with no entry at all is represented by the empty hash root = (0, 0, 0, 0).

A Merkle tree with a single entry (key, value) is called a "leaf". It is represented by the hash value root = hash(1, (key, value)), where 1 is a flag indicating that it is a leaf, and it's used as the initial state of the hash (Poseidon) permutation.

A Merkle tree tree with more than one entry is required to have two subtrees, left and right. It is then represented by the hash value root = hash(2, (left_root, right_root)), where 2 is a flag indicating that it is an intermediate node, and it's used as the initial state of the hash (Poseidon) permutation.

The flags are used as the initial state of the Poseidon permutation so that they don't account for extra inputs in the Poseidon gadget, needing only 1 gate for each node/leaf hash.

(The role of the constants 1 and 2 is to prevent collisions between leaves and non-leaf Merkle roots. If the constants were omitted, a large Merkle tree could be dishonestly interpreted as a leaf, leading to security vulnerabilities.)

Example 1

Suppose we want to build a Merkle tree from the following key-value pairs, where the keys are integers:

{
    4: "even",
    5: "odd",
    6: "even"
}

The keys are integers, so they are represented in-circuit by themselves. In little-endian order, the first three bits of the keys are:

4 = 001...
5 = 101...
6 = 011...

The resulting tree looks like:

                        root
                         /\
                        /  \
                       /    \
                      /      \
                   L_root   R_root = hash(1, (5, "odd"))
                     /\
                    /  \
                   /    \
                  /      \
               LL_root  LR_root = hash(1, (6, "even"))
                 ||
         hash(1, (4, "even"))

The intermediate roots are computed as hashes of their subroots:

L_root = hash(2, (LL_root, LR_root))
root = hash(2, (L_root, R_root)).

The full set of key-value pairs is then represented in the backend as root (four field elements in the Plonky2 backend).

Example 2

So for example, imagine we have 8 key-pairs, where the keys are just an enumeration from 0 to 7, then the tree leaves positions would look like:

Now let's replace the leaf key=1 by a leaf with key=13. Since 5 and 13 share their first three bits, their respective leaf paths will be the same until they diverge in the 4-th bit:

Example 3

Suppose we have 4 key-values, where the first four bits of the keys are 0000, 0100, 1010 and 1011. The tree would look like:

To iterate this example, suppose we have the following Dictionary:

{
	idNumber: "424242",
	dateOfBirth: 1169909384,
	userPk: 9876543210, // target user of this dictionary
	_signerPk: 1234567890, // signer of the dictionary
}

Suppose that the binary representation of the hash of the key userPk is 1011.... This uniquely defines the leaf position that contains the public key of the authenticated user. Similarly for the other key-values:

Proofs of inclusion and non-inclusion

Merkle proofs contain the siblings along the path from the leaf to the root, where the leaf position is determined by the key binary representation.

Since leaf positions are deterministic based on the key, the same approach is used for non-inclusion proofs, where it can be proven that a key is not in the tree, and furthermore, that a value is not in the tree (although the key exists):

  1. Proving that the key does not exist in the tree is achieved by generating the merkle-proof for the specific key, and showing that the (virtual) leaf is empty - this is, showing that going down the path of the non-existing key, there is a leaf with a different key, meaning that the non-existing key has not been inserted in the tree.
  2. Proving that a value is not in the tree (although the key exists) is achieved by generating the merkle-proof for the specific key, and showing that the leaf exists but it has a different value than the one being proved.

For the current use cases, we don't need to prove that the key exists but the value is different on that leaf, so we only use the option 1.

There are 2 cases to have into account when dealing with non-inclusion proofs:

  • case i) the expected leaf does not exist.
  • case ii) the expected leaf does exist in the tree, but it has a different key.

In case ii) the proof includes the key-value pair of the other leaf found on the path.

State transition proofs

A state transition proof shows that a tree with root new_root is obtained from a tree with root old_root by one operation on the entry (key, value):

  • insert: key does not exist under old_root (non-inclusion proof), and (key, value) exists under new_root.
  • update: key exists under old_root with some value, and under new_root it maps to value instead.
  • delete: (key, value) exists under old_root, and key does not exist under new_root.

In all cases the circuit checks that the rest of the tree is unchanged. These proofs back the ContainerInsert, ContainerUpdate and ContainerDelete statements.

Proof depth

Out of circuit the tree can have up to 256 levels (one per key bit). In-circuit, Merkle proofs are verified with a fixed maximum depth. The MainPOD supports two sizes of Merkle proof gadgets: small proofs (8 levels by default) and medium proofs (32 levels by default), with the number of each configured by the circuit parameters.

Interface

#![allow(unused)]
fn main() {
impl MerkleTree {
    /// builds a new `MerkleTree` where the leaves contain the given key-values
    fn new(kvs: &HashMap<RawValue, RawValue>) -> Self;

    /// returns the root of the tree
    fn root(&self) -> Hash;

    /// returns the value at the given key
    fn get(&self, key: &RawValue) -> Result<Option<RawValue>>;

    /// returns a boolean indicating whether the key exists in the tree
    fn contains(&self, key: &RawValue) -> Result<bool>;

    /// inserts / updates / deletes an entry, returning a proof of the state transition
    fn insert(&mut self, key: &RawValue, value: &RawValue) -> Result<MerkleTreeStateTransitionProof>;
    fn update(&mut self, key: &RawValue, value: &RawValue) -> Result<MerkleTreeStateTransitionProof>;
    fn delete(&mut self, key: &RawValue) -> Result<MerkleTreeStateTransitionProof>;

    /// returns a proof of existence, which proves that the given key exists in
    /// the tree. It returns the `value` of the leaf at the given `key`, and the
    /// `MerkleProof`.
    fn prove(&self, key: &RawValue) -> Result<(RawValue, MerkleProof)>;

    /// returns a proof of non-existence, which proves that the given
    /// `key` does not exist in the tree.
    fn prove_nonexistence(&self, key: &RawValue) -> Result<MerkleProof>;

    /// returns an iterator over the leaves of the tree
    fn iter(&self) -> Iter;
}

/// verifies an inclusion proof for the given `key` and `value`
fn verify(root: Hash, proof: &MerkleProof, key: &RawValue, value: &RawValue) -> Result<()>;

/// verifies a non-inclusion proof for the given `key`, that is, the given
/// `key` does not exist in the tree
fn verify_nonexistence(root: Hash, proof: &MerkleProof, key: &RawValue) -> Result<()>;

/// verifies a state transition proof (insert, update or delete)
fn verify_state_transition(proof: &MerkleTreeStateTransitionProof) -> Result<()>;
}

Resources

Signature

For POD2 signatures, we use Schnorr signature over the EcGFp5 curve, with Poseidon as the hash function.

The message is a single backend Value. To sign a dictionary, the signer signs its Merkle root; the frontend SignedDict bundles a Dictionary, the signer's public key and the signature. A SignedBy(msg, pk) statement is proved in a MainPOD by verifying the signature in-circuit.

Let be the generator of the curve group, of order , and let be the Poseidon hash, whose output is interpreted as an integer.

keygen()

secret key:
public key:
return

sign(sk, m)





return

verify(pk, m, sig)



return

Here is the -coordinate of the point , which uniquely identifies the point in the EcGFp5 group.

Older version

The previously used signature scheme was proof-based signatures using Plonky2 proofs, following https://eprint.iacr.org/2024/1553 and https://jdodinh.io/assets/files/m-thesis.pdf, where the public key is and a signature is a Plonky2 proof of knowledge of for the given and message. It was replaced by the elliptic curve Schnorr signature presented above.

Deductions

A POD proves a list of statements. Each statement is deduced from previously proved statements by an operation (a deduction rule), so that a POD contains a "two-column proof": a table where each row has a statement and the operation that justifies it. The operation (the "reason") is everything the circuit needs to verify that the statement is true.

| STATEMENT                                    | REASON                                    |
| -------------------------------------------- | ----------------------------------------- |
| Equal(olddict["name"], otherdict["field"])   | OpenInputStatement (from an input POD)    |
| Equal(otherdict["field"], newdict["result"]) | OpenInputStatement (from an input POD)    |
| Equal(olddict["name"], newdict["result"])    | TransitiveEqualFromStatements(row 1, row 2) |

Statements can come from three sources:

  • statements derived directly from values (e.g. Contains from a Merkle proof, or SignedBy from a signature);
  • public statements of input PODs, imported with OpenInputStatement;
  • statements derived from previous rows of the table, by native operations or by custom operations.

Each statement is marked as public or private. Only the public statements are exposed by the resulting POD.

The table has a fixed maximum length, given by the circuit parameters (see MainPOD).

Predicates, statements and operations

When working with statements and operations, it might be useful to see them from another perspective:

  • A predicate is a relation formula, which when filled with values becomes a statement.
  • A statement can be seen as the constraints of a traditional zk-circuit, which can be true or false.
  • An operation comprises the deduction rules, which are rules used to deduce new statements from previous statements or used to construct new statements from values.

For example,

  • Equal for integers is a predicate
  • st_1 = Equal(A, B) is a statement
  • st_2 = Equal(B, C) is a statement
  • st_3 = TransitiveEqualFromStatements(st_1, st_2) is an operation, which yields the statement st_3 = Equal(A, C)

So, for example, for the given predicate:

is_composite(n, private: a, b) = AND(
  Product(a, b, n)
  Gt(a, 1)
  Gt(b, 1)
)

We can view it as:

The statement is_composite(n) is true if and only if a, b such that the following statements hold:

Statements

A statement is any sort of claim about values: for example, that two values are equal, or that one entry is contained in a dictionary.

Statements come in three types: built-in (native), custom and introduction. There is a short list of built-in statements (see below). In addition, users can freely define custom statements, and Introduction PODs can output their own introduction statements.

From the user (front-end) perspective, a statement represents a claim about some values -- the statement can only be proved if the claim is true. On the front end, a statement is identified by its name (Equal, Contains, etc.).

From the circuit (back-end) perspective, a statement can be proved either:

  • by direct in-circuit verification, or
  • by an operation (aka deduction rule). On the back end, a statement is identified by the hash of its predicate.

Built-in statements

The POD system has several builtin statements. These statements are associated to a reserved set of statement IDs.

Backend statements

A statement is a code (or, in the frontend, string identifier) followed by 0 or more arguments, up to a maximum of 5. Each argument is either a literal value or an anchored key.

The following table summarises the natively-supported statements, where we write value_of(a) for the value of the argument a: the literal value itself, or the value that the anchored key a maps to.

CodeIdentifierArgsMeaning
0Noneno statement, always true (useful for padding)
1Falsealways false (useful for padding disjunctions)
2Equala1, a2value_of(a1) = value_of(a2)
3NotEquala1, a2value_of(a1) != value_of(a2)
4LtEqa1, a2value_of(a1) <= value_of(a2)
5Lta1, a2value_of(a1) < value_of(a2)
6Containsa1, a2, a3(value_of(a2), value_of(a3)) ∈ value_of(a1) (Merkle inclusion)
7NotContainsa1, a2(value_of(a2), _) ∉ value_of(a1) (Merkle exclusion)
8Suma1, a2, a3value_of(a3) = value_of(a1) + value_of(a2)
9Producta1, a2, a3value_of(a3) = value_of(a1) * value_of(a2)
10Maxa1, a2, a3value_of(a3) = max(value_of(a1), value_of(a2))
11Hasha1, a2, a3value_of(a3) = hash(value_of(a1), value_of(a2))
12PublicKeya1, a2value_of(a2) = derive_public_key(value_of(a1))
13SignedBya1, a2value_of(a1) is signed by value_of(a2)
14ContainerInserta1, a2, a3, a4(value_of(a2), _) ∉ value_of(a1) ∧ value_of(a4) = value_of(a1) ∪ {(value_of(a2), value_of(a3))} (Merkle insert)
15ContainerUpdatea1, a2, a3, a4(value_of(a2), v) ∈ value_of(a1) ∧ value_of(a4) = (value_of(a1) - {(value_of(a2), v)}) ∪ {(value_of(a2), value_of(a3))} (Merkle update)
16ContainerDeletea1, a2, a3(value_of(a2), v) ∈ value_of(a1) ∧ value_of(a3) = value_of(a1) - {(value_of(a2), v)} (Merkle delete)

Frontend statements

The frontend also exposes the following syntactic sugar predicates. These predicates are not supported by the backend. The frontend compiler is responsible for translating these predicates into the predicates above.

CodeIdentifierArgs and desugaring
1000DictContainsDictContains(root, key, val) -> Contains(root, key, val)
1001DictNotContainsDictNotContains(root, key) -> NotContains(root, key)
1002SetContainsSetContains(root, val) -> Contains(root, val, val)
1003SetNotContainsSetNotContains(root, val) -> NotContains(root, val)
1004ArrayContainsArrayContains(root, idx, val) -> Contains(root, idx, val)
1005GtEqGtEq(a, b) -> LtEq(b, a)
1006GtGt(a, b) -> Lt(b, a)
1009DictInsertDictInsert(old_root, key, val, new_root) -> ContainerInsert(old_root, key, val, new_root)
1010DictUpdateDictUpdate(old_root, key, val, new_root) -> ContainerUpdate(old_root, key, val, new_root)
1011DictDeleteDictDelete(old_root, key, new_root) -> ContainerDelete(old_root, key, new_root)
1012SetInsertSetInsert(old_root, val, new_root) -> ContainerInsert(old_root, val, val, new_root)
1013SetDeleteSetDelete(old_root, val, new_root) -> ContainerDelete(old_root, val, new_root)
1014ArrayUpdateArrayUpdate(old_root, idx, val, new_root) -> ContainerUpdate(old_root, idx, val, new_root)

Notes on the built-in statements

A Contains statement asserts that an entry has a certain value.

Contains(A, "name", "Arthur")

Implies that the entry A["name"] exists with the value "Arthur".

An Equal statement asserts that two values are the same. (Technical note: The circuit only proves equality of field elements; no type checking is performed. For strings or Merkle roots, collision-resistance of the hash gives a cryptographic guarantee of equality. However, note both Arrays and Sets are implemented as Merkle trees in the backend, like Dictionaries; the backend cannot type-check, so it is possible to prove an equality between an Array or Set and a Dictionary.)

Equal(A["name"], B["name"])

A NotEqual statement asserts that two values are different, for arbitrary types.

The comparison and arithmetic statements (Lt, LtEq, Sum, Product, Max) only hold for values of type Int. Each argument can be an anchored key or a literal.

Lt(100, A["price"])
Lt(A["price"], B["balance"])
Sum(A["price"], A["fee"], B["total"])

Hash(a, b, c) asserts that c is the Poseidon hash of a and b.

PublicKey(sk, pk) asserts that pk is the public key corresponding to the secret key sk, and SignedBy(msg, pk) asserts that msg is signed by pk.

Operations

The mechanism by which statements are derived is furnished by operations. Roughly speaking, with few exceptions, an operation deduces a statement from one or more existing statements according to some relation that must be satisfied between these statements. For example, if Equal(a1, a2) and Equal(a2, a3) hold true, then the operation TransitiveEqualFromStatements applied to these statements yields Equal(a1, a3).

More precisely, an operation is a code (or, in the frontend, string identifier) followed by 0 or more arguments. These arguments are previously proved statements (up to 6) and, depending on the operation, an auxiliary witness: a Merkle proof, a Merkle state transition proof or a signature.

Most operations are of the form XFromEntries. Each of their statement arguments s_i corresponds to the argument a_i of the output statement, and determines its value value_i:

  • if a_i is a literal value v, then s_i = None and value_i = v;
  • if a_i is the anchored key root[key], then s_i = Contains(root, key, v) (with literal arguments) and value_i = v.

This is how anchored keys are introduced in statements: from a Contains statement, which is itself backed by a Merkle proof.

The following table summarises the natively-supported operations:

CodeIdentifierArgsConditionOutput
0NoneNone
2EqualFromEntriess1, s2value1 = value2Equal(a1, a2)
3NotEqualFromEntriess1, s2value1 != value2NotEqual(a1, a2)
4LtEqFromEntriess1, s2value1 <= value2LtEq(a1, a2)
5LtFromEntriess1, s2value1 < value2Lt(a1, a2)
6TransitiveEqualFromStatementss1, s2s1 = Equal(a1, a2), s2 = Equal(a3, a4), a2 = a3Equal(a1, a4)
7LtToNotEqualss = Lt(a1, a2)NotEqual(a1, a2)
8ContainsFromEntriess1, s2, s3, proofmerkle_includes(value1, value2, value3, proof) = trueContains(a1, a2, a3)
9NotContainsFromEntriess1, s2, proofmerkle_excludes(value1, value2, proof) = trueNotContains(a1, a2)
10SumFromEntriess1, s2, s3value1 + value2 = value3Sum(a1, a2, a3)
11ProductFromEntriess1, s2, s3value1 * value2 = value3Product(a1, a2, a3)
12MaxFromEntriess1, s2, s3max(value1, value2) = value3Max(a1, a2, a3)
13HashFromEntriess1, s2, s3hash(value1, value2) = value3Hash(a1, a2, a3)
14PublicKeyFromEntriess1, s2derive_public_key(value1) = value2 PublicKey(a1, a2)
15SignedByFromEntriess1, s2, sigverify_signature(msg: value1, pk: value2, sig) = trueSignedBy(a1, a2)
16ContainerInsertFromEntriess1, s2, s3, s4, proofmerkle_insert(value1, value2, value3, value4, proof) = trueContainerInsert(a1, a2, a3, a4)
17ContainerUpdateFromEntriess1, s2, s3, s4, proofmerkle_update(value1, value2, value3, value4, proof) = trueContainerUpdate(a1, a2, a3, a4)
18ContainerDeleteFromEntriess1, s2, s3, proofmerkle_delete(value1, value2, value3, proof) = trueContainerDelete(a1, a2, a3)
19ReplaceValueWithEntry[args] sargs[i] = None | Contains, s' = s with literal arguments replaced by entries following argss'
20OpenInputStatements is a public statement of an input POD, proved by a Merkle proof against the input POD's statements roots

In addition, a statement of a custom predicate is proved by a custom operation, which takes as arguments the statements that satisfy the predicate definition (see custom predicates). Custom operations output statements with literal arguments; these can then be converted to use anchored keys with ReplaceValueWithEntry.



The following table summarizes "syntactic sugar" operations. These operations are not supported by the backend. The frontend compiler is responsible for translating these operations into the operations above.

CodeIdentifierArgs and desugaring
1001DictContainsFromEntriesDictContainsFromEntries(dict_st, key_st, value_st, proof) -> ContainsFromEntries(dict_st, key_st, value_st, proof)
1002DictNotContainsFromEntriesDictNotContainsFromEntries(dict_st, key_st, proof) -> NotContainsFromEntries(dict_st, key_st, proof)
1003SetContainsFromEntriesSetContainsFromEntries(set_st, value_st, proof) -> ContainsFromEntries(set_st, value_st, value_st, proof)
1004SetNotContainsFromEntriesSetNotContainsFromEntries(set_st, value_st, proof) -> NotContainsFromEntries(set_st, value_st, proof)
1005ArrayContainsFromEntriesArrayContainsFromEntries(array_st, index_st, value_st, proof) -> ContainsFromEntries(array_st, index_st, value_st, proof)
1006GtEqFromEntriesGtEqFromEntries(s1, s2) -> LtEqFromEntries(s2, s1)
1007GtFromEntriesGtFromEntries(s1, s2) -> LtFromEntries(s2, s1)
1008GtToNotEqualGtToNotEqual(s) -> LtToNotEqual(s)
1009DictInsertFromEntriesDictInsertFromEntries(old_dict_st, key_st, value_st, new_dict_st, proof) -> ContainerInsertFromEntries(old_dict_st, key_st, value_st, new_dict_st, proof)
1010DictUpdateFromEntriesDictUpdateFromEntries(old_dict_st, key_st, value_st, new_dict_st, proof) -> ContainerUpdateFromEntries(old_dict_st, key_st, value_st, new_dict_st, proof)
1011DictDeleteFromEntriesDictDeleteFromEntries(old_dict_st, key_st, new_dict_st, proof) -> ContainerDeleteFromEntries(old_dict_st, key_st, new_dict_st, proof)
1012SetInsertFromEntriesSetInsertFromEntries(old_set_st, value_st, new_set_st, proof) -> ContainerInsertFromEntries(old_set_st, value_st, value_st, new_set_st, proof)
1013SetDeleteFromEntriesSetDeleteFromEntries(old_set_st, value_st, new_set_st, proof) -> ContainerDeleteFromEntries(old_set_st, value_st, new_set_st, proof)
1014ArrayUpdateFromEntriesArrayUpdateFromEntries(old_array_st, index_st, value_st, new_array_st, proof) -> ContainerUpdateFromEntries(old_array_st, index_st, value_st, new_array_st, proof)

Simple example

This page shows how the circuit verifies a deduction rule, using the last row of the two-column proof example:

STATEMENT1 = Equal(olddict["name"], otherdict["field"])
STATEMENT2 = Equal(otherdict["field"], newdict["result"])
STATEMENT3 = Equal(olddict["name"], newdict["result"])  <- transitive property on STATEMENT1 and STATEMENT2

A simple example of a deduction rule

Here is the transitive property of equality, in human-readable form.

if
Equal(a, b) and Equal(b, c)
then
Equal(a, c)

In-circuit, all these identifiers are replaced with wildcards, which come in numerical order (because they will be used as array indices). So the backend representation is:

IF
Equal( ?0, ?1 ) and Equal( ?1, ?2 )
THEN
Equal( ?0, ?2 )

What does the reason look like in-circuit?

Native operations such as TransitiveEqualFromStatements are implemented directly in the circuit, but custom operations are verified following exactly these steps.

  • Repeat deduction rule
IF
Equal( ?0, ?1 ) and Equal( ?1, ?2 )
THEN
Equal( ?0, ?2 )
  • Say what the wildcards are
?0 -- olddict["name"]
?1 -- otherdict["field"]
?2 -- newdict["result"]
  • Substitute the wildcards into the deduction rule
IF
Equal( olddict["name"], otherdict["field"] ) and
Equal( otherdict["field"], newdict["result"] )
THEN
Equal( olddict["name"], newdict["result"] )
  • Say where to find the previous statements (indices in the list), and check that they are above this one.
Statement1
Statement2
  • Check that the input statements match (for an OR, at least one of them). Check that the output statement matches.

Anchored keys in deduction rules

Sometimes a deduction rule requires different anchored keys to come from the same dictionary. Here's an example from the GoodBoy predicate.

The wildcard system handles this very naturally, since the dictionary of an anchored key is itself a wildcard.

good_boy(receiver, good_boy_issuers, private: signed_dict, signer) = AND(
    // the dict is signed by signer
    SignedBy(signed_dict, signer)
    SetContains(good_boy_issuers, signer)
    // that same dict has a "friend" entry equal to receiver
    Equal(signed_dict["friend"], receiver)
)

The dictionary signed_dict shows up twice: once as a value and once as the root of the anchored key signed_dict["friend"]. Both uses must refer to the same dictionary.

WILDCARD matching takes care of it.

good_boy(?0, ?1, private: ?2, ?3) = AND(
    SignedBy(?2, ?3)
    Contains(?1, ?3, ?3)
    Equal(?2["friend"], ?0)
)

Custom statements and custom operations

Users of the POD system can introduce custom predicates to express complex logical relations not available in the built-in predicates. Every custom predicate is defined as the conjunction (AND) or disjunction (OR) of a small number of other statements.

On the frontend, a custom predicate is defined in Podlang as a conjunction or disjunction of statements. The definition can be recursive: the definition of a predicate can involve the predicate itself, or the definitions of several predicates can depend on each other.

At the backend level, every definition of a predicate is either a conjunction or a disjunction of at most 5 statements. To convert a larger frontend custom predicate to the backend, the frontend automatically splits it into a chain of sub-predicates.

On the backend, custom predicates are defined in batches (called modules in Podlang). A batch can contain one or more custom predicates and their associated sub-predicates. Recursive definition is only possible within a batch: the definition of a predicate in a batch can only depend on previously existing predicates, itself, and other predicates in the same batch.

A custom predicate is identified by the batch ID (the root of a Merkle tree of the hashes of the predicate definitions in the batch) and its index in the batch, so it can be used in any MainPOD. See how to hash a custom predicate.

Arguments of custom predicates

The definition of a custom predicate might also be called an operation or deduction rule. It includes up to 5 statement templates as conditions. The arguments of the predicate are wildcards, which are either public (they appear as arguments of the output statement, up to 5) or private (they only appear in the statement templates). In the backend, the wildcards are identified by their index: ?0, ?1, ?2, ....

Each argument to a statement template is one of:

  • a literal value;
  • a wildcard ?i, which is bound to a value;
  • an anchored key ?i["key"], where the root is a wildcard and the key is a literal.

The predicate of a statement template can also be a wildcard, which allows a custom predicate to take another predicate as an argument.

How to prove an application of an operation

A custom statement is proved by a custom operation, which the circuit verifies following the steps described in the simple example: the prover provides the predicate definition and a value for each wildcard, and the circuit substitutes the values into the statement templates and checks that the resulting statements appear in previous rows of the table. In addition, the prover provides the definition of the full batch, and the circuit verifies that it hashes to the batch ID.

Defining custom predicates

A custom operation is a rule that allows one to deduce a custom statement from one or more existing statements according to a logical rule. A custom operation is exactly the same thing as the definition of a custom predicate.

Note: Unlike built-in operations, it is not possible to perform arbitrary calculations inside a custom operation.

The syntax of a custom operation is best explained with an example, written in Podlang:

good_boy(receiver, good_boy_issuers, private: signed_dict, signer) = AND(
    SignedBy(signed_dict, signer)
    SetContains(good_boy_issuers, signer)
    Equal(signed_dict["friend"], receiver)
)

In the example above, signed_dict["friend"] is an anchored key. The purpose of using it, in this case, is to use an entry of a dictionary that has been signed.

In order to apply the operation, the user who wants to create a POD must give acceptable values for all the arguments. If all the conditions, with these values substituted, previously appear in the POD, the output statement is a valid statement.

What applying the operation looks like on the back end

On the back end the deduction rule is converted to a sort of "template", where sugar predicates have been desugared and identifiers are replaced by numbered wildcards:

ArgsConditionOutput
?0 (receiver),
?1 (good_boy_issuers),
?2 (signed_dict),
?3 (signer)
SignedBy(?2, ?3),
Contains(?1, ?3, ?3),
Equal(?2["friend"], ?0)
good_boy(?0, ?1)

To apply it in-circuit, the prover provides the template, the values for ?0, ?1, ?2, ?3 and the indices of the three condition statements, and the circuit verifies them as described in the simple example.

How to hash a custom predicate

Every predicate, native or custom, is identified on the backend by a predicate ID.

The native predicates are numbered with small integers, sequentially. The ID of a custom predicate is derived from a hash of its definition; this guarantees that two different predicates cannot have the same ID (aside from the miniscule probability of a hash collision).

This document explains how the definition of a custom predicate is serialized and hashed.

Custom predicates are defined in batches. The definition of a custom predicate in a batch involves other predicates, which may include:

  • native predicates
  • previously-defined custom predicates
  • introduction predicates
  • other predicates in the same batch.

Predicate hashing is recursive: in order to hash a batch of custom predicates, we need to know IDs for all the previously-defined custom predicates it depends on. Predicates in the same batch are referenced by their index in the batch, which avoids the circular dependency.

Each predicate in the batch is serialized (as explained below) and hashed (using a zk-friendly hash -- in the case of the plonky2 backend, Poseidon). These hashes are put in a Merkle tree with the predicate index as key, and its root is the batch ID. Each predicate in the batch is then referenced by

predicate_ID = (batch_ID, idx)

(here idx is simply the index of the predicate in the batch).

Example

The EthDos batch contains four predicates, which reference each other. When the batch is serialized, references to predicates in the same batch are replaced by their index: self.0, self.1, self.2, self.3. With this renaming and the wildcards, the last of the four definitions becomes:

self.3(?0, ?1, ?2) = OR(
    self.1(?0, ?1, ?2)
    self.2(?0, ?1, ?2)
)

and similarly for the other definitions. The predicates in the batch are then identified as:

eth_friend = (batchID, 0)
eth_dos_base = (batchID, 1)
eth_dos_ind = (batchID, 2)
eth_dos = (batchID, 3)

Serialization

A predicate is serialized into field elements as follows:

Native(id)          => (1, id, 0, ...)
BatchSelf(idx)      => (2, idx, 0, ...)
Custom(batch_ID, i) => (3, [batch_ID], i, 0, ...)
Intro(vd_hash)      => (4, [vd_hash], 0, ...)

and in statements and statement templates the predicate is represented by the hash of this serialization.

A custom predicate definition is serialized as

(conjunction, args_len, [st_tmpl_1], ..., [st_tmpl_n])

where conjunction is 1 for AND and 0 for OR, args_len is the number of public arguments, and the list of statement templates is padded to the maximum arity (5) with None templates for an AND and False templates for an OR.

A statement template is serialized as its predicate ((0, [predicate hash]), or (1, wildcard_index, 0, ...) for a wildcard predicate) followed by its arguments, each padded to 9 field elements:

None                     => (0, 0, ...)
Literal(v)               => (1, [v], 0, ...)
AnchoredKey(?i, key)     => (2, i, 0, 0, 0, [key])
Wildcard(?i)             => (3, i, 0, ...)
SelfPredicateHash(idx)   => (4, idx, 0, ...)

Podlang

Podlang is the language used to define custom predicates and to describe proof requests. The grammar can be found at pod2/src/lang/grammar.pest.

There are two kinds of Podlang documents:

  • modules, which contain predicate definitions (and imports), and are compiled into a batch of custom predicates;
  • requests, which contain a REQUEST block (and imports), describing the statements that a POD must expose.

Predicate definitions

over_18(person, private: age) = AND(
    Contains(person, "age", age)
    Lt(18, age)
)

A predicate definition has a name, a list of public arguments, an optional list of private arguments after private:, and a body which is either AND or OR of a list of statements. Statements are separated by whitespace. Comments use // or /* ... */.

The arguments of a statement can be:

  • an argument of the predicate (a wildcard);
  • a literal value;
  • an anchored key, written dict["key"] or dict.key.

The predicate of a statement can be a native predicate, a predicate defined in the same module (in any order, which allows recursion), a predicate from an imported module, an imported introduction predicate, or an argument of the predicate (a wildcard predicate, which is bound to a Predicate value).

Large predicates are automatically split into a chain of smaller predicates to fit the backend limits.

Literals

TypeSyntax
Int42, -1
Booltrue, false
String"hello"
UntypedUntyped(0x0000...0001) (64 hex digits)
PublicKeyPublicKey(<base58>)
SecretKeySecretKey(<base64>)
Array[1, 2, 3]
Set#[1, 2, 3]
Dictionary{"name": "Alice", "age": 30}
Predicate@native_predicate(Equal), @external_predicate(module, pred), @self_predicate(pred)

Imports

use module 0x<batch_id> as identity
use intro ecdsa_verified(pk, msg) from 0x<verifier_data_hash>

A module is imported by its batch ID, and its predicates are referenced as identity::pred. An introduction predicate is imported by the hash of the verifier data of the Introduction POD circuit.

Records

A record declares named entries of an Array:

record Person = (name, age)

adult(p Person) = AND(
    Lt(17, p.age)
)

p.age is lowered to the anchored key p[1]. Record literals are written Person(name: "Alice", age: 30), and Person::age evaluates to the entry index.

Requests

A request lists the statements that a POD must expose:

use module 0x<batch_id> as eth_dos

REQUEST(
    eth_dos::eth_dos(src, dst, distance)
)

The identifiers in the request are wildcards that are matched against the arguments of the public statements of the POD.

MainPOD

The MainPOD is the recursive POD of the system: a Plonky2 proof that verifies a two-column proof of statements, together with the proofs of its input PODs.

Inputs

A MainPOD takes as inputs:

  • up to max_input_pods input PODs, which are recursively verified in-circuit. These can be other MainPODs or Introduction PODs. Unused slots are padded with an EmptyPod.
  • the list of statements and operations to verify, each statement marked as public or private.
  • the definitions of the custom predicate batches used by the custom operations.

Statement table

The circuit lays out the statements in a table with the following regions:

  1. a None statement at index 0, used for padding operation arguments;
  2. max_open_input_statement_ops rows of statements imported from the input PODs with OpenInputStatement;
  3. max_statements rows of statements derived by operations.

An operation can only use as arguments statements that appear in a previous row of the table.

Public statements

The public statements of a POD are put in an Array (a Merkle tree with the statement index as key and the statement hash as value). Its root is the statements root of the POD, which identifies the POD's claims: two PODs that expose the same public statements have the same statements root.

A statement of an input POD is imported by providing a Merkle proof of its hash against the input POD's statements root. This way, a POD can use any public statement of its input PODs without the circuit having to process all of them.

Optionally, a MainPOD can extend the public statements of its first input POD (if it's a MainPOD) instead of starting from an empty list, which allows building a long list of public statements across several PODs.

Verifier data set

To support recursion with more than one circuit, each MainPOD commits to a verifier data set (VDSet): a Merkle tree of the hashes of the verifier data of the allowed circuits. The MainPOD verifies that each input MainPOD was proved with one of the circuits in the set, and that it uses the same set.

Introduction PODs are not checked against the set; instead, their verifier data hash is embedded in the introduction statements they output.

Public inputs

The public inputs of the MainPOD proof are:

  • the statements root (4 field elements);
  • the root of the verifier data set (4 field elements);
  • an is_main flag, which distinguishes MainPODs from Introduction PODs.

Parameters

The size of the circuit is defined by a set of parameters (Params), such as max_input_pods, max_statements, max_public_statements, max_open_input_statement_ops, the maximum number of custom predicates and custom predicate operations, the number of Merkle proofs of each size, and the maximum number of signature verifications and public key derivations. If a proof needs more resources than one MainPOD provides, the frontend can split it into several chained MainPODs automatically.

Introduction PODs

Introduction PODs are a kind of POD used to introduce any cryptographic data structure into the POD system. This allows the POD system to reason about cryptographic data and cryptographic primitives that are not part of the POD system itself.

Examples of Introduction PODs are the Ed25519Pod and the EcdsaPod, both of them allowing to incorporate their respective kind of signature schemes that are not supported in the core of the POD system. This allows the POD system to incorporate data validated by those Introduction PODs, and recursively use it in future proofs combining them with any logical reasoning together with other PODs.

For example, we could have a scenario where we use 3 different Introduction PODs (Ed25519Pod, RSAPod, EcdsaPod), to prove that a user controls an Ethereum wallet AND a GitHub account. To do so, the user would produce a new MainPod which proves that the user has signed a certain message with the given ECDSA key (Ethereum wallet) AND with either the given Ed25519 key OR the RSA key (from a GitHub account).

Interface

The interface of an IntroductionPod is just the one of the Pod trait, and by definition the IntroductionPod is expected to only output Introduction statements (or None statements for padding).

An Introduction Statement is a Statement that uses an Introduction predicate which embeds the hash of the verifier data of the circuit that generates it. This way the statements generated by an IntroductionPod are self-describing. When a MainPod imports a statement from an IntroductionPod, the circuit sets the predicate of the statement to the Introduction predicate of that POD's verifier data, so an IntroductionPod can't output statements of any other predicate.

This means that as long as we fit into the Pod interface, the IntroductionPod will fit into the recursive verification chain of the MainPods.

Introduction predicates can be used in custom predicates; in Podlang they are imported with use intro name(args) from 0x<verifier_data_hash>.

Different configurations

There are some cases, where the operations needed for the IntroductionPod require a different circuit configuration than the standard recursive circuit configuration that is used for the MainPods.

In those cases, we do a previous recursive step, where we verify the logic of the intended IntroductionPod, and then the proof of this circuit is the one verified in the real IntroductionPod.

This is done in order to be able to converge the different circuit configuration shape (and thus different common_data) into a new proof that can be verified with the standard configuration (used for the MainPods).

Notice that this is not a requirement for implementing a new IntroductionPod, and if the IntroductionPod logic can be directly verified with the standard recursion configuration, we don't need this previous recursive step.

As examples of the two-recursive steps approach, we have the EcdsaPod and the Ed25519Pod. Both of them require different circuit configurations that would not match the one used for the standard recursion with MainPods. Therefore we first generate a circuit proof of correct signature verification, and then this proof is the one actually verified in the EcdsaPod/Ed25519Pod respectively, not the original signature itself.

Examples of IntroductionPods can be found at the git repository github.com/0xPARC/introduction-pods.

Examples

Examples of POD2 use cases, written in Podlang. Names in uppercase (ZOO_GOV, SANCTION_LIST, ...) stand for literal values.

EthDos

An EthDos POD exposes a single custom statement with two custom deduction rules, the inductive case and the base case. The four predicates form a recursive batch (see how it is hashed).

// src, dst: PublicKey, attestation: Dictionary
eth_friend(src, dst, private: attestation) = AND(
    SignedBy(attestation, src)
    Contains(attestation, "attestation", dst)
)

// src, intermed, dst: PublicKey, distance, shorter_distance: Int
eth_dos_base(src, dst, distance) = AND(
    Equal(src, dst)
    Equal(distance, 0)
)

eth_dos_ind(src, dst, distance, private: shorter_distance, intermed) = AND(
    eth_dos(src, intermed, shorter_distance)
    // distance == shorter_distance + 1
    Sum(shorter_distance, 1, distance)
    // intermed is a friend of dst
    eth_friend(intermed, dst)
)

eth_dos(src, dst, distance) = OR(
    eth_dos_base(src, dst, distance)
    eth_dos_ind(src, dst, distance)
)

ZuKYC

Original using GPC https://github.com/proofcarryingdata/zukyc

Authority public keys:

  • ZOO_GOV: PublicKey, issues IDs
  • ZOO_DEEL: PublicKey, issues bank statements

Authority lists:

  • SANCTION_LIST: Set of sanctioned ID numbers
    • values: #["G2345678", "G1987654", "G1657678"]

Date values:

  • NOW_MINUS_18Y: Int, 18 years ago
  • NOW_MINUS_1Y: Int, 1 year ago
  • NOW_MINUS_7D: Int, 7 days ago

A ZuKYC POD exposes a single custom statement with one custom deduction rule.

// receiver: PublicKey, gov_id, paystub: Dictionary, sk: SecretKey, nullifier: Untyped
loan_check(receiver, nullifier, private: gov_id, paystub, sk) = AND(
    Equal(gov_id["pk"], receiver)
    // Not in the sanction list
    SetNotContains(SANCTION_LIST, gov_id["id_number"])
    // Valid government-issued ID
    SignedBy(gov_id, ZOO_GOV)
    // At least 18 years old
    Lt(gov_id["date_of_birth"], NOW_MINUS_18Y)
    // Valid paystub for the same person
    SignedBy(paystub, ZOO_DEEL)
    Equal(paystub["ssn"], gov_id["ssn"])
    // At least one year of consistent employment with your current employer
    Lt(paystub["start_date"], NOW_MINUS_1Y)
    Gt(paystub["issue_date"], NOW_MINUS_7D)
    // Annual salary is at least $20,000
    Gt(paystub["annual_salary"], 20000)
    // Private key knowledge
    PublicKey(sk, receiver)
    // Nullifier
    Hash("ZUKYC_V1_NULLIFIER", sk, nullifier)
)

GreatBoy

A Good Boy POD exposes one custom statement with one custom deduction rule.

// user: PublicKey, good_boy_issuers: Set, attestation: Dictionary, issuer: PublicKey
is_good_boy(user, good_boy_issuers, private: attestation, issuer) = AND(
    SetContains(good_boy_issuers, issuer)
    // A good boy issuer says this user is a good boy
    SignedBy(attestation, issuer)
    Equal(attestation["user"], user)
)

A Friend POD exposes one custom statement with one custom deduction rule.

// good_boy, friend: PublicKey, good_boy_issuers: Set, attestation: Dictionary
is_friend(good_boy, friend, good_boy_issuers, private: attestation) = AND(
    // The issuer is a good boy
    is_good_boy(good_boy, good_boy_issuers)
    // A good boy says this is their friend
    SignedBy(attestation, good_boy)
    Equal(attestation["friend"], friend)
)

A Great Boy POD exposes (in addition to the above) one new custom statement with one custom deduction rule.

// great_boy: PublicKey, good_boy_issuers: Set, friend_0, friend_1: PublicKey
is_great_boy(great_boy, good_boy_issuers, private: friend_0, friend_1) = AND(
    // Two good boys consider this user their friend
    is_friend(friend_0, great_boy, good_boy_issuers)
    is_friend(friend_1, great_boy, good_boy_issuers)
    // good boy 0 != good boy 1
    NotEqual(friend_0, friend_1)
)

Attested GreatBoy

An Attested Great Boy POD is like a Great Boy POD, but the friends are revealed.

// great_boy, friend_0, friend_1: PublicKey, good_boy_issuers: Set
is_attested_great_boy(great_boy, friend_0, friend_1, good_boy_issuers) = AND(
    // Two good boys consider this user their friend
    is_friend(friend_0, great_boy, good_boy_issuers)
    is_friend(friend_1, great_boy, good_boy_issuers)
    // good boy 0 != good boy 1
    NotEqual(friend_0, friend_1)
)

Posts and comments

The goal of this example is to model a social network, where posts and comments are signed dictionaries.

A Post is a signed dictionary with the following fields:

content: String
poster: String
timestamp: Int

A Comment is a signed dictionary with the following fields:

content: String
referenced_post: Dictionary (the root of the post)
timestamp: Int

A post is popular if it has at least two comments from different signers.

// post, comment1, comment2: Dictionary, signer1, signer2: PublicKey
is_popular(post, private: comment1, comment2, signer1, signer2) = AND(
    SignedBy(comment1, signer1)
    SignedBy(comment2, signer2)
    Equal(comment1["referenced_post"], post)
    Equal(comment2["referenced_post"], post)
    NotEqual(signer1, signer2)
)

Multiple people over 18

Suppose I want to prove that two different people are over 18, and a third person is under 18, using the custom predicates over_18 and under_18.

// age: Int
over_18(age) = AND(
    GtEq(age, 18)
)
// age: Int
under_18(age) = AND(
    Lt(age, 18)
)

With wildcards:

over_18(?0) = AND(
    LtEq(18, ?0)
)

Maybe I have three dictionaries gov_id1, gov_id2 and gov_id3, and I want to prove that the first two refer to two different people, both of whom are over 18; and the third one refers to someone under 18. So in my public output statements, I want to have:

NotEqual(gov_id1["name"], gov_id2["name"])
over_18(gov_id1["age"])
over_18(gov_id2["age"])
under_18(gov_id3["age"]).

I would prove this with the following sequence of deductions:

StatementReason
over_18(gov_id1["age"])over_18,
?0 = gov_id1["age"]
over_18(gov_id2["age"])over_18,
?0 = gov_id2["age"]
under_18(gov_id3["age"])under_18,
?0 = gov_id3["age"]
NotEqual(gov_id1["name"], gov_id2["name"])NotEqualFromEntries

Each custom operation outputs a statement with the literal value of the age; it is then converted to use the anchored key with ReplaceValueWithEntry.

Architecture

This document explains the architecture of the current implementation.

The main logic of the POD2 implementation is divided into three modules:

  • frontend
    • compiles user-friendly pod declarations into intermediate representations to be consumed by the backend
    • internally connects to the backend to get pods built (proved).
    • presents pods to the user
  • middleware
    • defines the intermediate representation of Statements, Operations and interfaces of PODs
    • Statements and Operations are strongly typed here
    • Both frontend and backend use types defined in the middleware
    • Does not import types from frontend nor backend
  • backend
    • takes a middleware POD request representation, signs/proves it and returns a generic POD object

In addition:

  • lang: parses Podlang modules and requests, and lowers them into middleware custom predicate batches and statement templates.
  • frontend multi_pod: when a proof doesn't fit in a single MainPOD, partitions the statements into a chain of MainPODs.

If this was the Rust language compiler:

  • frontend: takes a Rust code and compiles it to LLVM-IR
  • middleware: defines LLVM-IR instructions and blocks
  • backend: Takes LLVM-IR instructions and emits assembly code for a particular CPU

The following diagram shows visually how the components interact with each other:

In this organization, the middleware could be defined at arbitrary points:

  • closer to the user would be more high level
  • closer to the target would be more low level

For example in the middleware we could define Value = 4 x Goldilock (making it slightly low level); or Value = BigUint and letting the backend choose the maximum representable value, the field encoding, etc. (making it slightly higher level).

In the current iteration we choose Value = 4 x Goldilock, but we can revisit it in a future iteration (eg. if we want to support plonky3) by either moving the middleware to a higher level, or by keeping it the same and replacing the Value definition.

The diagram above includes an arrow that would show the typical flow followed by a user making a POD. This is a simplified description of the process.

  1. The user interacts with the frontend API (MainPodBuilder) and passes a list of Operations. The frontend takes those operations and generates the corresponding Statements. The list of Operations and Statements are transformed into middleware types. This process can be seen as a compilation step. The frontend sends this middleware data as a request to the Backend.
  2. The backend receives a request to build a POD from a list of Statements and Operations. It takes that bundle of data and lays it out in the appropriate format to be proved by a circuit, padding unused slots, etc. Then it calls a proof system API to generate a proof.
  3. The target (proof system) generates a proof from some circuit description and witness data and gives it back to the backend.
  4. The backend receives the proof and encapsulates it in an object that adheres to the Pod trait and passes it to the frontend
  5. The frontend receives a "blackbox" Pod object and wraps it in a presentation layer in order to show it to the user.

The backend also provides a mock prover, which checks the operations without generating proofs, useful for testing.