vfhe.polycom¶
Polynomial commitments for the oracles of vfhe.piop: Basefold over a foldable Reed-Solomon code, FoldableRS over the ring or FieldFoldableRS over a field, with the evaluation protocols BasefoldEval and BatchFoldEval.
scheme.commit(f) returns a BasefoldCommitment, the root a statement
carries, and a BasefoldOpening, the prover’s data. BasefoldEval, registered
for Relation_Eval, proves an evaluation claim by a sumcheck interleaved with
folds of the codeword, then answers queries at query_positions. Fiat-Shamir
comes from IOP(fiat_shamir=True). Under development: the API changes
between releases.
- class vfhe.polycom.Basefold(code: FoldableRS | FieldFoldableRS, schedule: list[int] | None = None)¶
The basefold PCS [ZCF24, Def. 8] over the domain of its code — R_q (
FoldableRS) or a field (FieldFoldableRS): this object is the scheme (itscodeis the Setup output);commit/openbelow, and Eval is theBasefoldEvalprotocol, registered forRelation_Eval.commitreturns the committed oracle (piop.CommittedOracle: the commitment, the variables and this scheme, what a statement names) and the opening.openingsis the prover-side map (commitment ->BasefoldOpening)BasefoldEvalfalls back to, filled by the commits made without a prover; a verifier’s copy of a scheme simply never holds one, and the in-process sharing of this object is the same convention that lets a verifier hold table oracles it may only query.schedulegroups the code’sdfolds into layers:schedule[i]folds make layeri, and only the codeword each layer starts from is committed, by a Merkle tree whose leaves are its fibers of2^schedule[i]adjacent symbols (the symbols those folds reduce to one). The counts are positive and sum tod; the default[1] * dcommits every folded codeword over pair leaves. The commitment is the first layer’s tree, so it depends onschedule[0].- levels¶
The code level each layer starts from, top first, then the level the last layer ends at (0).
- property domain¶
The code’s ring or field, where the committed tables’ coefficients live.
- digest() bytes¶
A 32-byte digest of the scheme’s public parameters: the code (
FoldableRS.digest/FieldFoldableRS.digest) and the layer schedule.
- merkle_commit(word: Any, folds: int | None = None) Merkle¶
The Merkle tree commitment to a codeword — the vector-commitment step of the scheme, one leaf per fiber of
2^foldsadjacent symbols (digested by the code,leaf_digests),foldsthe first layer’s count by default; itsrootis what travels (as the polynomial commitment or as a round message).The digests reach the tree packed, which is why nothing here builds a Python object per leaf. A codeword has a leaf per pair, so an object per leaf would be one on the way in and another on the way back out when the builder rejoined them – at a large codeword more than either the hashing or the tree costs, and paid once per fold level as well as once per commit.
- commit(f: MLE, prover: Prover | None = None) tuple[CommittedOracle, BasefoldOpening]¶
Commit to f: encode, build the Merkle tree, return the committed oracle – the root as the commitment, with the variables and this scheme – and the codeword plus tree as the prover’s opening data.
Both costs are paid here, once. With
provergiven, the opening is installed on it and nowhere else:witnesses[commitment] = openingis what the evaluation protocol proves against, andwitnesses[oracle] = fis the table a sumcheck prover folds when the oracle is one of its factors (piop.resolve_table); both live as long as that prover. Without one, the opening is recorded on the scheme (openings), where the evaluation protocol of any prover finds it, for as long as the scheme lives – or store it yourself on whichever provers will run. Mutating the table after the commit breaks the binding.
- open(commitment: BasefoldCommitment, f) bool¶
The Open algorithm [ZCF24, Def. 8]: does
commitmentopen to f? Re-encode, rebuild the tree, compare roots — so it is exactly as binding as the hash is collision-resistant.
- class vfhe.polycom.BasefoldCommitment(variables: list, root: bytes)¶
A commitment to a multilinear polynomial: public instance data, created once by
Basefold.commitand referenced by any number ofRelation_Evalstatements (across IOP runs — it never touches a transcript).rootis the Merkle root of the level-d codeword’s pair leaves, andvariablesthe committed variables, whose order is the canonical order of evaluation points. Nothing else: the codeword itself is prover data (BasefoldOpening).- digest() bytes¶
The
piop.element_digesthook: what a Fiat-Shamir chain absorbs when this commitment sits in a statement (the root already binds the codeword; the variables fix the point order).
- class vfhe.polycom.BasefoldEval(scheme: Basefold, rep: int = 32)¶
Basefold’s Eval protocol: discharges
Relation_Evalstatements against the scheme’s code, replacing the terminal oracle query.Register with
iop.register(Relation_Eval, BasefoldEval(scheme)); the registry keys it byscheme, so it receives the evaluation claims on the oracles committed under that scheme (CommittedOracle`s, as `commitreturns them) and proves each against the commitment its oracle carries. A claim on any other oracle is aTypeError. This is [CHMMVW20]’s “queries become opening claims” done in place — no separate relation, since the commitment is just the oracle’s other form [ZCF24, §4].It is a bundle protocol, and its bundle is every pending claim on the oracles committed under its scheme (
bundle_key): the driver hands them over once no other statement can produce another. A single claim is opened by one basefold run; several, at any points and on any of the scheme’s commitments, are opened together by one sumcheck to a common point and one basefold run on a random linear combination (_prove_batch, [CCCFGS26, §7, Figs. 3-4]).The prover’s witness is the
BasefoldOpening, fromprover.witnesses[commitment](falling back to the scheme’s own records, which commit() filled); the verifier works from the root alone. The code’s dimension k_d must equal 2^num_vars of the commitment, and its depth d must not exceed num_vars (kappa = num_vars - d variables remain in the clear base table).- reduces_from¶
alias of
Relation_Eval
- domain¶
The ring or field of the committed tables’ coefficients, where every challenge of this protocol is drawn, whatever the IOP’s domain is.
- parameters() tuple¶
The public parameters of this protocol, in a fixed order; empty by default.
- soundness_error(statement: Statement, domain, gamma: float, delta: float, claims: int = 1, polynomials: int = 1) float | None¶
The information-theoretic part, 2d / (gamma^3
|A|) + (1 - delta + gamma * d)^rep [ZCF24], per RNS-prime component (|A|= the residue field size).gammaanddeltaare the caller’s, subject to the theorem’s conditions (polycom.md):deltais the proximity parameter, which must satisfy delta < J_gamma(J_gamma(Delta)) and 3 delta - d gamma < Delta for the code’s relative distance Delta (self.code.relative_distance());basefold_parametersgives the largest one. None if|A|is unknown.For a bundle of
claimsevaluation claims onpolynomialsdistinct polynomials, opened together, the batching adds (2l + claims - 1) /|A|for the common-point sumcheck when claims > 1 [CCCFGS26, §7.1] (l = the number of variables; the bound holds whether or not the points coincide) and (polynomials - 1) /|A|for the random linear combination [CCCFGS26, §7.2, Lemma 5].With Merkle commitments this is no longer the whole story: binding is computational, so the argument’s error also carries the hash’s collision term ([ZCF24, Thm. 4] reduces one to the other). That term is a property of BLAKE3 and the security parameter, not of these protocol parameters, so it is deliberately not folded in here.
The bound is stated for [ZCF24]’s protocol, which commits every folded codeword: the default schedule. Under a schedule that groups several folds into a layer, the codewords inside a layer are not committed; the same expression is returned, and that case is not covered by the cited theorem.
- query_positions(seed: bytes) tuple[int, ...]¶
The
repspot-check positions derived from a bit-string challenge: leaf indices of the commitment’s tree, in[0, n_d / 2^schedule[0])– pair indices at level d under the default schedule.This scheme’s geometry handed to
polycom.query_positions, which is where the sampler and its rejection rule are: a leaf index is a position of the codeword the first layer ends at, so a walk from it consumes that level’slevels[1]index bits to reach the level-0 codeword, and the positions are rejection-sampled to land there pairwise distinct. The constructor’srep < n0guarantees termination.Deterministic in the seed, so both parties derive the same positions from the published challenge — the prover to answer, the verifier to check.
- bundle_key(oracle) Any¶
Claims on every oracle committed under this protocol’s scheme form one bundle, which
proveopens together; any other oracle keeps a bundle of its own.
- class vfhe.polycom.BasefoldMessages(schemes: list[Basefold], sent: Iterable[int] = ())¶
Oracle messages compiled with basefold: a table a protocol sends is committed, and the message is the commitment’s Merkle root.
Built from one
Basefoldscheme per table size, since a scheme’s code has one dimension;sendcommits under the scheme whosek_dis the table’s size and installs the opening on the prover (Basefold.commit), andreceivereads the root and names theCommittedOracle. The evaluation claims on those oracles are discharged by each scheme’sBasefoldEval, which the caller registers forRelation_Eval.Tables of
2^nentries forninsentare not committed: their message is the entries, as inOracleMessages, and both parties name the table by a publicTableOracle, since the verifier holds it whole; an evaluation claim on it is then decided by the verifier’s own evaluation.basefold_messagessends the sizes that have no basefold parameters for a target soundness this way.- sent¶
The table sizes, as variable counts, whose entries are the message.
- classmethod from_code(code: FoldableRS | FieldFoldableRS, num_vars: list[int]) BasefoldMessages¶
One scheme per table size
2^n, forninnum_vars, each under the default schedule overcodetruncated to the depth that size needs (truncated): one code’s tables serve every size. Eachnis at leastlog2(k0) + 1and at mostlog2(k_d).
- digest() bytes¶
The schemes by table size and the sizes sent in the clear.
- class vfhe.polycom.BasefoldOpening(polynomial: MLE, word: Any, tree: Merkle)¶
The prover’s data for one commitment — the witness of the evaluation claim, stored as
prover.witnesses[commitment].Holds the polynomial plus what commit already paid for and every evaluation proof reuses: the level-d codeword and its Merkle tree. The shape mirrors the
commit -> (Commitment, ProverData)split of PCS implementations (arkworks’ poly-commit, plonky3’sPcs).
- class vfhe.polycom.BasefoldParameters(k0: int, c: int, d: int, rep: int, schedule: tuple[int, ...], distance: float, gamma: float, delta: float, soundness_error: float, proof_bits: float)¶
What
basefold_parameterschose.FieldFoldableRS(field, k0, c, d)orFoldableRS(ring, k0, c, d)is the code,Basefold(code, schedule)the scheme andBasefoldEval(scheme, rep)the evaluation protocol.distanceis the code’srelative_distance,gammaanddeltathe arguments ofBasefoldEval.soundness_errorthat givesoundness_error, andproof_bitsthe size estimate the choice minimized.- property n0: int¶
The length of the base codeword.
- property num_vars: int¶
The variables of the committed polynomials.
- class vfhe.polycom.BatchFoldEval(scheme: Basefold, rep: int = 32)¶
BatchFold’s Eval protocol: discharges
Relation_Evalstatements on oracles committed under aBasefoldscheme over R_q (aFoldableRScode, with its twists in either field), by basefold runs over the residue fields of R_q (module docstring).Register with
iop.register(Relation_Eval, BatchFoldEval(scheme))in place ofBasefoldEval: the commitments are the same, so a polynomial committed once may be opened by either. As withBasefoldEval, the bundle is every pending claim on the oracles committed under the scheme, and a single claim is a bundle of one.repis the number of query positions, shared by the runs at every prime.- slots¶
k = N / split_degree, the number of CRT components at each prime.
- residue_protocols¶
Per prime p_i, basefold over the residue code at p_i with this scheme’s schedule. These run the per-prime folds and are never registered with an IOP.
- soundness_error(statement: Statement, domain, gamma: float, delta: float, claims: int = 1, polynomials: int = 1) float | None¶
The information-theoretic soundness error for a bundle of
claimsevaluation claims onpolynomialsdistinct polynomials:2d / (gamma^3 |F|) + (2l + k claims - 1) / |F| + (k polynomials - 1) / |F| + (1 - delta + gamma d)^rep, one prime’s error: the common-point sumcheck [CCCFGS26, §7.1], the random linear combination [CCCFGS26, §7.2, Lemma 5] and basefold over a residue code [ZCF24]. Here|F|= min_i p_i^d is the size of the smallest residue field, which is also the size of the set the shared challenges come from, l the number of variables, k the number of components at a prime, and d the code’s depth (not the split degree).gammaanddeltaare the caller’s, as inBasefoldEval.soundness_error, with the smallest of the residue codes’ relative distances (min(p.code.relative_distance() for p in residue_protocols)) as the distance Delta that boundsdelta. None if a field’s size is unknown.Why one prime’s error, not L times it. The ring commitment fixes the committed codeword before the protocol, and the statement fixes the claims, so whether the components at prime i are codewords whose polynomials satisfy the component claims is decided, for every i, before any challenge or query is drawn. When the bundle is false, some prime i fails in this way, and the verifier accepts only if that prime’s checks pass, which happens with probability at most that prime’s error. Each prime’s error is bounded by the expression above: its challenges come after the messages they answer and are uniform over a set of size
|F|(they are one ring element’s components, so the primes’ challenges are correlated, which no prime’s argument looks at), and its query positions are uniform and drawn after every oracle they check is committed. The same holds round by round, which Fiat-Shamir needs: the composition is doomed when that prime’s run is ([BCFW25] proves it for parallel copies of an interactive oracle reduction). The ring sumcheck over R_q, which through the CRT is the per-prime sumchecks on one shared challenge, likewise has no factor for the number of primes [CCCFGS25, Thm. 2.6]. [CCCFGS26, §7] states its bound with a factor L + 1, for its L + 1 primes run independently.The paper commits to the k*L component polynomials separately and opens each prime with its own query positions and challenges; here the ring commitments serve every prime and the primes share both, as well as one tree per later layer. A ring leaf holds every component at its position, and a later layer’s leaf every prime’s fiber at its position, which includes what the paper’s verifier reads there; and every layer’s tree is committed before the queries are drawn.
Two terms rest on assumptions. The fold term 2d / (gamma^3
|F|) is [ZCF24]’s for fold challenges uniform over the whole field; here they are uniform over a subset of size|F|, which keeps the bound if it comes from counting the challenges that fold badly (the ringBasefoldEvalmakes the same assumption). And as inBasefoldEval.soundness_error, the bound is stated for the default schedule, and the hash’s collision term is not included.
- class vfhe.polycom.FieldFoldableRS(field: Field, k0: int, c: int, d: int, *, instantiation: str = 'general', seed: bytes = b'vfhe.polycom foldable code', twist_field: str = 'field', root_field: str = 'prime')¶
A depth-d foldable code over
field, with base dimension k0 and inverse rate c: level l encodes k0 * 2^l field elements into n_l = c * k0 * 2^l.encodeinfers the level from the message length;fold/fold_atimplement the verifier-checkable fold that takes the level-l codeword of P to the level-(l-1) codeword of P_even + r * P_odd (seecode.FoldableRSfor the construction and the tables).instantiationselects the code (the module docstring describes both):"general"(the default): seeded twists above a Reed-Solomon base code, [ZCF24]’s construction. Any field, any length; the base encoder is a transform when the field has a2 n0-th root of unity and a Vandermonde product otherwise."rs": every level a Reed-Solomon code on roots of unity, encoded by one transform per level. Needs2 n_d | p - 1, i.e.log2(n_d) + 1 <= field.two_adicity; faster, and with the exact distancerelative_distancereports for it.
seedis the public parameter every table of the general code is derived from – two parties building the code from the same arguments hold the same code. It is ignored by the"rs"instantiation.twist_fieldsays where the general code’s twists are drawn from:"field"(the default), the whole field, or"prime", its prime subfieldF_p. Prime-subfield twists make every lift and fold multiply plane-wise –dprime-field products per element in place of a full extension product – at the price of the distance bound running onlog2 pbits rather thanlog2 p^d, which is more queries for the same soundness. Over a prime field the two coincide, and the"rs"instantiation’s twists are roots of unity inF_pwhatever is asked.root_fieldsays where the general code’s base transform may find its2 n0-th root of unity:"prime"(the default), only inF_p, so a field whosep - 1lacks the 2-adicity gets the Vandermonde base; or"field", inF_pwhere it has one and in the extension otherwise, for a transform whose butterflies are extension products rather than plane-wise products inF_p. Both encode the same code on their points. It plays no part over a prime field or in the"rs"instantiation, whose transforms always have their roots inF_p.- classmethod residue_code(code: FoldableRS, index: int) FieldFoldableRS¶
The code that
code, a foldable code overR_q, induces on the residue fieldR_q/P_0at the primep = code.ring.primes[index](RNSRing.residue_field): the code whose codewords are the CRT components at p (RNSRing.crt_components) ofcode’s codewords.A ring code with twists in the residue fields (
twist_field = "field") is built from one such code per prime, and that code is returned.A ring code with integer twists applies the same
F_p-linear maps to every coordinate of its symbols, since its twists and base points at p are integers mod p, and the CRT components at p are ring homomorphisms that fixF_p. So component s ofcode.encode(m)is the encoding of component s of m under the same tables, and the code returned hascode’s instantiation and parameters, its twists and base points at p as tables over the prime subfield (twist_field = "prime"), and a fold that commutes withcode.foldcomponent by component. Its base level is encoded by the field’s transform when that transform’s root inF_pis the ring transform’s, and by a Vandermonde product on the same points otherwise. For the"rs"instantiation every level’s transform must have the ring code’s root; aValueErroris raised when it does not.
- digest() bytes¶
A 32-byte digest of the code’s public parameters: the field,
k0,c,d, the instantiation, the seed, the twist field and the root field. Two codes with equal digests encode, fold and hash identically.
- truncated(depth: int) FieldFoldableRS¶
The depth-
depthcode with this code’s field,k0,c, seed and options: its levels 0 todepth.A foldable code’s level
lis defined by the levels below it and levell’s twists [ZCF24, Def. 5], and here a level’s twists are drawn from the seed, the level and its length alone, as the base code is from the seed andn0. So the code of a smaller depth is this one’s first levels, and it is returned sharing their tables and transforms rather than sampling them again; it encodes, folds and hashes exactly as the code built withdepthdoes.
- relative_distance(security_bits: int = 128, bound: str = 'cccfgs26') float¶
A lower bound on the relative minimum distance at every level: the distance Delta that bounds the proximity parameter
deltaofBasefoldEval.soundness_error. It is a property of the code rather than of the protocol.For the
"rs"instantiation every level is a Reed-Solomon code on distinct points, so levellhas distance exactly1 - k_l/n_l + 1/n_l; the rate is1/cthroughout, so the longest codeword’s value is the bound and the other arguments play no part.For the general code it is
code.foldable_relative_distance– [CCCFGS26]’s bound unlessboundnames [ZCF24]’s – which holds with probability at least1 - d * 2^-security_bitsover the twists; the field size in it is the order oftwists_domain, the field the twists are drawn from.
- property twists: list[list[FieldElement]]¶
T_l[i], the even-position twist of the pairifolding levell+1tol, per level, as elements oftwists_domain;x_i = psi_{l+1}^(2 brv(i) + 1)for the"rs"instantiation.
- property twists_odd: list[list[FieldElement]]¶
T'_l[i] = -T_l[i], the odd-position twist, per level;-x_ifor the"rs"instantiation. Derived, not stored.
- level_of(message) int¶
The code level a message of this length belongs to.
- encode(message) FieldVector¶
The codeword of a coefficient vector (level inferred from its length). The operand is left untouched.
- encode_batch(messages, count: int) FieldVector¶
The codewords of
countmessages of one level, in one pass.messagesholds them interleaved – coefficientiof messagecati * count + c– and the result holds their codewords end to end, messagec’s atc * n_l.countis a power of two.For the general code the interleaved messages are one message of
log2(count)more levels, whose base messages are those of allcountmessages. Encoding it but stopping after the lifts of the messages’ own levels leaves exactly their codewords, in this order. For the"rs"instantiation each message is transformed on its own.
- decode(word) tuple[bool, FieldVector]¶
(is_codeword, message)for a codeword: the level’s inverse transform plus the degree check that rejects vectors outside the code (the level is inferred from the length).
- fold_pair(lo, hi, r, level: int, i: int)¶
The folded value at position i of a level-
levelcodeword, from that position’s pair alone:(lo, hi) = (word[2i], word[2i + 1]).This is the form a Merkle verifier uses — it holds one authenticated pair per queried position, never a whole codeword.
- fold_pairs(los, his, r, level: int, indices) list¶
fold_pairat many positions at once.los[k],his[k]are the pair atindices[k], and the result is that position’s folded value – exactly whatfold_pairreturns for it, one entry per position.A verifier holds one pair per queried position and folds it at every level, so the scalar form costs a handful of element operations per (query, level), each its own crossing into C. Here a level’s pairs are one vector folded by one
FieldVector.fold_twistedcall, and the table is read with one gather rather than an index at a time.
- fold_batch(words, challenges, level: int) FieldVector¶
foldoflen(challenges)level-levelcodewords laid end to end, codewordcwithchallenges[c]; the folded codewords come out end to end in the same order. It is onefold_twisted_blockscall, in which every codeword reads the level’s table.challengesis a vector over the field or a sequence of its elements.
- fold_fibers_batch(values, challenges, level: int, indices) FieldVector¶
fold_fibersforcountcodewords at once, at the same positions:valuesholdscountblocks end to end, blockcthe fibers of codewordcaboveindices(asfold_fiberstakes them), andchallenges[k]holds thecountchallenges of foldk, one per codeword. The result holds, block by block,fold_fibersof each. Each fold is onefold_twisted_blockscall, with the level’s table gathered at the fibers’ pairs.
- fold_fibers(values, challenges, level: int, indices) FieldVector¶
Fold fibers of a level-
levelcodewords = len(challenges)times, one challenge per fold in order, down to the one symbol each determines.The fiber above position
jof the codewordsfolds below is the2^sadjacent symbolsword[j 2^s : (j + 1) 2^s], since every fold sends pair(2i, 2i + 1)to positioni.valuesholds fibers end to end andindices[k]is the position below fiberk; the result has one symbol per fiber, entrykthe value atindices[k]of the level-(level - s)codeword. Each fold is oneFieldVector.fold_twistedcall over all the fibers, with the level’s table gathered at their pairs’ positions. With one challenge it isfold_pairson the pairs ofvalues.
- fiber_at(word: FieldVector, i: int, size: int)¶
The
sizeadjacent symbolsword[i size : (i + 1) size]: the Merkle leafiof a tree oversize-symbol fibers. A pair ispair_at’s tuple, a larger fiber a vector.
- fibers_at(word: FieldVector, positions, size: int) FieldVector¶
Gather the fibers of
sizesymbols at fiber indicespositionsinto one vector, end to end in that order: for eachjofpositions, the symbols offiber_at(word, j, size).For example,
positions = [2, 0]andsize = 2give the vector[word[4], word[5], word[0], word[1]].
- check_fibers(fibers, count: int, size: int) FieldVector¶
Check that
fibersiscountfibers ofsizesymbols end to end, asfibers_atgathers them: a vector ofcount * sizeelements of this code’s field. Returns it.Raises
ValueErrorotherwise.
- pair_at(word: FieldVector, i: int) tuple[FieldElement, FieldElement]¶
Position i’s pair,
(word[2i], word[2i + 1])— the unit the fold reads, and the Merkle leaf (seeleaf_digest).
- leaf_digests_of(pairs) memoryview¶
The leaf digests of
pairs, packed –leaf_digestfor a set of pairs rather than one.The pairs go into one vector and are digested with the adjacent windows
leaf_digestsuses on a codeword, so entrykisleaf_digest(pairs[k])and the lane-parallel hashing applies to a handful of pairs as much as to a whole codeword.
- pair_leaves(word: FieldVector) list[tuple]¶
wordas the list of adjacent pairs its Merkle tree commits to.
- leaf_digest(pair: tuple) bytes¶
The Merkle leaf digest of one pair: the vector digest of the two elements in order, so it equals the matching entry of
leaf_digestsand binds the pair as an ordered unit.A verifier recomputes this once per query, where the vector it used to build was most of the cost and none of the hashing.
- leaf_digests(word: FieldVector, size: int = 2) memoryview¶
The leaf digests of every adjacent pair of
word, packed, in one pass over the codeword (FieldVector.hash_elementswith adjacent windows). Leafiisdigests[32 * i : 32 * (i + 1)], and equalsleaf_digestofpair_at(word, i). Withsize, the leaves are the fibers of that many symbols instead,fiber_at(word, i, size). RaisesValueErrorwhensizedoes not divide the length ofword.A read-only view of the kernel’s buffer, not a copy of it – so a codeword reaches its root without its digests being duplicated on the way.
bytes(...)is how a caller takes a copy.
- fold_at(word: FieldVector, r, level: int, i: int)¶
Position i of the fold of the level-
levelcodewordwordwith challenge r — the value the folded codeword must hold there.
- fold(word: FieldVector, r, level: int) FieldVector¶
The full fold of a level-
levelcodeword with challenge r: the level-(level-1) codeword of the r-folded message, as one call (FieldVector.fold_twistedwith this level’s1 / (2 T)table).
- class vfhe.polycom.FoldableRS(ring: RNSRing, k0: int, c: int, d: int, *, instantiation: str = 'general', seed: bytes = b'vfhe.polycom foldable code', twist_field: str | None = None)¶
A depth-d foldable code over
ring, with base dimension k0 and inverse rate c: level l encodes k0 * 2^l ring elements into n_l = c * k0 * 2^l.encodeinfers the level from the message length;fold/fold_atimplement the verifier-checkable fold taking the level-l codeword of P to the level-(l-1) codeword of P_even + r * P_odd (the module docstring has the construction and both instantiations).Everything is per RNS prime: the twists are per-prime integers applied through
Polynomial * list, their inverses per-prime modular inverses, and there are no ring inversions anywhere.The ring’s primes satisfy
p = 1 mod 2N/split_degree, so a negacyclic transform of length n exists exactly whenn | N/split_degree. The"rs"instantiation needs one of lengthn_d; the general code uses one of lengthn0when it exists and a Vandermonde product otherwise.seedis the public parameter every table of the general code is derived from; the"rs"instantiation ignores it.twist_fieldsays where the general code’s twists live:"prime", the per-prime integers above; or"field", the residue fieldsR_q/Pof the ring’s primes (RNSRing.residue_field,F_(p^d)with d the split degree). Left as None, it is"field"when the ring’s split degree is above 1 and"prime"otherwise, where the residue fields are theF_pand the two give the same distance. With"field"the code is defined by one code per prime –FieldFoldableRSover that residue field with full-field twists, its own seeded tables and base, built fromseedand the prime – and a codeword ofR_qis the element-wise CRT lift of their codewords: its CRT components at a prime (RNSRing.crt_components) are that prime’s code’s codewords of the message’s components. Encoding and folding run in the residue fields, so a twist multiply costs anF_(p^d)product, dF_pproducts per coefficient where an integer twist costs one; the distance bound runs onlog2 p^dbits instead oflog2 p. Either way the base code’s transform has its root inF_pwhen the primes carry one of order2 n0, i.e. whenn0 <= N/d. The"rs"instantiation’s twists are roots of unity inF_pwhatever is asked.- roots: list[list[int]]¶
one row per level for the
"rs"instantiation, the base transform’s alone for the general code (empty when its base is a Vandermonde product).- Type:
The roots of the transforms in use,
[level][prime]
- residue_codes: list[FieldFoldableRS]¶
With full-field twists, the code over each prime’s residue field that defines this one (in
ring.primesorder); empty otherwise.
- property twists_odd: list[list[list[int]]]¶
T'_l[j] = -T_l[j]per level, position and prime – the odd-position twist. Derived fromtwists, not stored.
- digest() bytes¶
A 32-byte digest of the code’s public parameters: the ring,
k0,c,d, the instantiation, the seed and the twist field. Two codes with equal digests encode, fold and hash identically.
- truncated(depth: int) FoldableRS¶
The depth-
depthcode with this code’s ring,k0,c, seed and options: its levels 0 todepth.A foldable code’s level
lis defined by the levels below it and levell’s twists [ZCF24, Def. 5], and here a level’s twists are drawn from the seed, the level and its length alone, as the base code is from the seed andn0(and a transform’s root from its length). So the code of a smaller depth is this one’s first levels, and it is returned sharing their tables, plans and residue codes rather than building them again; it encodes, folds and hashes exactly as the code built withdepthdoes.
- relative_distance(security_bits: int = 128, bound: str = 'cccfgs26') float¶
A lower bound on the relative minimum distance at every level, per RNS-prime component: the distance Delta that bounds the proximity parameter
deltaofBasefoldEval.soundness_error. It is a property of the code rather than of the protocol.For the
"rs"instantiation every level is a Reed-Solomon code on distinct points, so levellhas distance exactly1 - k_l/n_l + 1/n_l; the rate is1/cthroughout, so the longest codeword’s value is the bound and the other arguments play no part.For the general code it is
foldable_relative_distanceat the smallest prime – [CCCFGS26]’s bound unlessboundnames [ZCF24]’s – which holds with probability at least1 - d * 2^-security_bitsover the twists.
- level_of(message: list) int¶
The code level a message of this length belongs to.
- encode(message: list) list¶
The codeword of a coefficient vector (level inferred from its length).
- decode(word: list) tuple[bool, list]¶
(is_codeword, message)for a codeword: the encoding inverted, plus the check that rejects vectors outside the code (the level is inferred from the length).
- fold_pair(lo: RNSPolynomial, hi: RNSPolynomial, r: RNSPolynomial, level: int, i: int) RNSPolynomial¶
The folded value at position i of a level-
levelcodeword, from that position’s pair alone:(lo, hi) = (word[2i], word[2i + 1]).This is the form a Merkle verifier uses — it holds one authenticated pair per queried position, never a whole codeword.
- fold_pairs(los, his, r, level: int, indices) list¶
fold_pairat many positions at once; seeFieldFoldableRS, which has a vectorised one. Over a ring the entries are polynomials with their own arithmetic, so this is the loop a caller would write – the uniform name is what lets a verifier fold a level without knowing which code family answers.With full-field twists the pairs are folded component by component: at each prime, component s of every pair by that prime’s code with component s of r, and the results lifted back.
- fold_fibers(values, challenges, level: int, indices) list¶
Fold fibers of a level-
levelcodewords = len(challenges)times, one challenge per fold in order, down to the one symbol each determines; seeFieldFoldableRS, which has a vectorised one. Here each fold isfold_pairsover the pairs of every fiber.valuesholds fibers of2^sadjacent symbols end to end, andindices[k]is the position below fiberkin the codewordsfolds below; entrykof the result is the value there.
- fiber_at(word: list, i: int, size: int) tuple[RNSPolynomial, ...]¶
The
sizeadjacent symbolsword[i size : (i + 1) size]: the Merkle leafiof a tree oversize-symbol fibers. A pair ispair_at’s tuple.
- fibers_at(word: list, positions, size: int) list[RNSPolynomial]¶
Gather the fibers of
sizesymbols at fiber indicespositions, end to end in that order: for eachjofpositions, the symbols offiber_at(word, j, size). The entries areword’s own elements, not copies.For example,
positions = [2, 0]andsize = 2give[word[4], word[5], word[0], word[1]].
- check_fibers(fibers, count: int, size: int) list[RNSPolynomial]¶
Check that
fibersiscountfibers ofsizesymbols end to end, asfibers_atgathers them: a list or tuple ofcount * sizeelements of this code’s ring. Returns them as a list.Raises
ValueErrorotherwise.
- pair_at(word: list, i: int) tuple[RNSPolynomial, RNSPolynomial]¶
Position i’s pair,
(word[2i], word[2i + 1])— the unit the fold reads, and the Merkle leaf (seepair_leaves).
- leaf_digests_of(pairs: list[tuple[RNSPolynomial, RNSPolynomial]]) bytes | memoryview¶
The leaf digests of
pairs, packed: entrykisleaf_digest(pairs[k]). The pairs are digested together, asleaf_digestsdigests a codeword’s.
- pair_leaves(word: list) list[tuple[RNSPolynomial, RNSPolynomial]]¶
wordas the leaf vector its Merkle tree commits to: one leaf per adjacent pair, so a single path authenticates both operands of a fold check ([ZCF24, Remark 9]’s packed leaves).
- leaf_digest(pair: tuple[RNSPolynomial, RNSPolynomial]) bytes¶
The Merkle leaf digest of one adjacent pair (
pair_digest).
- leaf_digests(word: list, size: int = 2) bytes | memoryview¶
The leaf digests of every adjacent pair of
word, packed: leafiisdigests[32 * i : 32 * (i + 1)], and equalsleaf_digestofpair_at(word, i). Withsize, the leaves are the fibers of that many symbols instead,fiber_at(word, i, size). RaisesValueErrorwhensizedoes not divide the length ofword.One native call (
rs_leaf_digests). The entries are hashed in NTT form, asget_hashhashes them, and are left in the form they are in. The result is a read-only view of the kernel’s buffer.
- fold_at(word: list, r: RNSPolynomial, level: int, i: int) RNSPolynomial¶
Position i of the fold of the level-
levelcodewordwordwith challenge r — the value the folded codeword must hold there. The pair is adjacent:(word[2i], word[2i + 1]).
- fold(word: list, r: RNSPolynomial, level: int) list¶
The full fold of a level-
levelcodeword with challenge r (the level-(level-1) codeword of the r-folded message). With full-field twists, at each prime every component is folded by that prime’s code with the same component of r (FieldFoldableRS.fold_batch), and the results lifted back.
- class vfhe.polycom.LayerAnswers(leaves: tuple, paths: bytes)¶
The answers of one committed layer to a run’s query positions: the leaves at those positions and their authentication paths.
A leaf is a fiber of adjacent symbols of a codeword (
fiber_at).leavesholds one word per codeword under the layer’s tree, in the codeword’s own form (aFieldVectorfor a field code, a list of ring elements for a ring code): the queried fibers end to end, in query order (fibers_at). A tree over one codeword has one word; a tree whose leaf joins the leaves of several codewords has one per codeword.pathsholds the leaves’ authentication paths end to end, in query order, asMerkle.open_manywrites them.For example, for queries at leaf indices
[5, 2]of a codewordwwith fibers of 2 symbols, the word is[w[10], w[11], w[4], w[5]], andpathsis the path of leaf 5 followed by the path of leaf 2.Its transcript digest hashes each word whole, and the paths’ bytes once.
- digest() bytes¶
Return the transcript digest: a tag, one hash per word of leaves, then one hash of the paths’ bytes.
leavesother than a tuple, which no honest prover sends, is digested whole as any other message is.
- vfhe.polycom.basefold_messages(domain: Field | RNSRing, sizes: Iterable[int], security_bits: int = 128, *, twist_field: str | None = None, **options) tuple[BasefoldMessages, list[BasefoldEval]]¶
Oracle messages for tables of
2^nentries overdomain, forninsizes, at soundness error2^-security_bits, and the evaluation protocols of their schemes, which the caller registers forRelation_Eval.Each size gets the scheme and the query count
basefold_parameterschooses for it (withtwist_fieldandoptionspassed on), over the general foldable code. The sizes below the smallest one that has parameters are sent as their entries (BasefoldMessagessent). An opening needs fewer queries than its base codeword has positions, which small tables do not allow.Raises
ValueErrorwhen no size has parameters, givingbasefold_parameters’ reason for the largest, and when a size above one that has parameters has none.
- vfhe.polycom.basefold_parameters(domain: Field | RNSRing, num_vars: int, security_bits: int = 128, *, claims: int = 1, polynomials: int = 1, twist_field: str | None = None, bound: str = 'cccfgs26', max_k0: int = 256, inverse_rates: tuple[int, ...] = (2, 4), digest_bits: int = 256) BasefoldParameters¶
The basefold parameters for opening
num_vars-variate multilinear polynomials overdomain– a field, orR_qas anRNSRing– with soundness error at most2^-security_bits, by the general foldable code [ZCF24] and the default schedule, one fold per committed codeword, which is what the soundness theorem covers.The search is the one of the parameter estimator of [CCCFGS26], run on the library’s bounds. For every base dimension
k0 = 2^i <= max_k0that leavesd = num_vars - i >= 1folds, and every inverse ratecininverse_rates:Deltaisfoldable_relative_distance(k0, c, d, ...)withbound, the valuerelative_distancereports on the code these parameters build; its field is the one the twists are drawn from, chosen bytwist_fieldas the code classes do (their own default when None: the whole field forFieldFoldableRS, and forFoldableRSthe residue fieldsF_(p^d)on a split ring andF_potherwise);gamma = gamma_0 + gfor everygin a half-decade grid from10^-2to10^-7.5, wheregamma_0makes2d / (gamma^3 |A|)the whole budget left by the batching terms;delta = (1 - 2^-20) min((Delta + d gamma) / 3, J_gamma(J_gamma(Delta))), just below the supremum the theorem admits, so that both of its conditions hold strictly;repis the fewest queries for whichbasefold_soundness_error, the expressionBasefoldEval.soundness_errorreports, is at most2^-security_bits, and it must be belown0 = c k0, asBasefoldEvalrequires.
The candidate with the smallest
proof_bitsis returned: the round messages, the roots, the base table and the queries’ pairs and paths of one opening, with elements oflog2 |F|bits over a field andN log2 qoverR_q, and digests ofdigest_bits.|A|is the domain’sexceptional_set_size, the set the challenges come from.claimsandpolynomialsdescribe a bundle opened together, assoundness_errortakes them. They enter the bound only through its batching terms,(2 num_vars + claims - 1) / |A|whenclaims > 1and(polynomials - 1) / |A|: the parameters chosen for one claim, opened as a bundle, have the error reported plus those terms.max_k0bounds the base table the verifier re-encodes in full; withinverse_rates, its default is the estimator’s search space.Raises
ValueErrorwhen no candidate reaches the target, which is always the case when|A|is below about2^security_bits: the first term of the bound then exceeds the target for everygamma < 1.
- vfhe.polycom.batch_inverse(values: list[int], p: int) list[int]¶
The inverses modulo the prime
pof every entry ofvalues, by Montgomery’s trick: one exponentiation and three multiplications per entry in place of an exponentiation each. Raises ValueError on a zero.
- vfhe.polycom.bit_reverse(i: int, bits: int) int¶
iwith its lowbitsbits reversed — the index permutationntt_forward(CT_NR) leaves in its output.Public because it is not this code family’s: any code built on that transform needs it to say which evaluation point a position holds, and a second one carrying its own copy is a second place for the convention to drift from arith’s.
- vfhe.polycom.bit_reverse_permutation(bits: int) list[int]¶
[bit_reverse(i, bits) for i in range(1 << bits)], in one pass.Each entry follows from the one at half its index – the low bit becomes the high one, and the rest is the shorter reversal already computed – so the whole permutation costs O(n) where calling
bit_reverseper index costs O(n log n). That difference is the whole cost of a twist table once the modular exponentiations are gone.
- vfhe.polycom.foldable_relative_distance(k0: int, c: int, d: int, field_bits: float, security_bits: int = 128, bound: str = 'cccfgs26') float¶
A lower bound on the relative minimum distance of the general foldable code with base dimension
k0, inverse ratec, depthdand twists uniform inF^xfor a field of2^field_bitselements, holding with probability at least1 - d * 2^-security_bitsover the twists.Both bounds have the shape of [ZCF24, Thm. 2]: with
t_0 = k0andn_i = c k0 2^i, levelimay addl_izeros to a codeword’s worst case,t_i = 2 t_{i-1} + l_i, anddistance >= 1 - t_d / n_d. They differ inl_i:"cccfgs26": l_i = (lambda + 2 t_{i-1} (1 + log2(``|F|`` / (``|F|`` - 1))) + 0.585 n_i) / (log2(``|F|`` - 1) - 1) "zcf24": l_i = (2 log2(n_{i-1}) + lambda + 2.002 t_{i-1} + 0.6 n_i) / (log2|F| - 1.001)The default is [CCCFGS26]’s (its appendix on BaseFold, the theorem on the codes’ minimum distance), a tightening of [ZCF24, Thm. 2] for this very code –
T' = -T,diag(T)uniform inF^x, an MDS base: it drops the2 (i-1) log2(n0)term and sharpens0.6to0.585, and it is stated for every field with more than three elements where the [ZCF24] form assumes|F| >= 2^10. It is never smaller, and the difference shows where the field is small relative to the depth (about two percentage points atlog2|F| = 61,d = 20). The [ZCF24] bound stays reachable by name, as the one the literature quotes.t_0 = k0is the base code’s distance as an MDS code, so the base must be a Reed-Solomon code on distinct points for either bound to apply. The value is clamped at 0: a 0 means the theorem gives nothing at these parameters, not that the code has no distance.
- vfhe.polycom.pair_digest(pair: tuple[RNSPolynomial, RNSPolynomial]) bytes¶
The Merkle leaf digest of one adjacent pair.
Both ring elements are hashed with their own
digestand the two digests hashed together, so the leaf binds the pair as an ordered unit.digesthashes the NTT form and leaves the entry alone, so hashing a codeword never disturbs it.
- vfhe.polycom.query_positions(seed: bytes, span: int, shift: int, rep: int) tuple[int, ...]¶
repdistinct spot-check positions in[0, span), derived fromseed.- Parameters:
seed – The published bit-string challenge. The positions are a deterministic function of it, so prover and verifier derive the same ones – the prover to answer them, the verifier to check.
span – How many positions the top oracle has. A power of two, so that masking a uniform word is unbiased and no rejection is needed for the range itself.
shift – How many low index bits one walk consumes, i.e. how far a position must be shifted right to give the position its walk ends at.
0makes every position its own endpoint and the rejection below a plain distinctness check.rep – How many positions to draw.
The seed is expanded with BLAKE3 in counter mode (
BLAKE3(seed || counter), eight candidates per digest), and a candidate is rejected on its projectioncandidate >> shift: two queries that meet at the end of their walks run the same final check twice, so sampling with replacement there buys fewer effective repetitions thanrepclaims while reportingrep. That is a silent loss of soundness, which is why it is rejected rather than tolerated.Distinct endpoints imply distinct positions all the way up, since a position’s projection at any height extends its endpoint. Termination needs at least
rependpoints to exist, which is checked.