circomlib/test/smtverifier.js
test/smtverifier.jsRaw
1const chai = require("chai");
2const path = require("path");
3const snarkjs = require("snarkjs");
4const compiler = require("circom");
5
6const smt = require("../src/smt.js");
7
8const assert = chai.assert;
9
10const bigInt = snarkjs.bigInt;
11
12function print(circuit, w, s) {
13 console.log(s + ": " + w[circuit.getSignalIdx(s)]);
14}
15
16async function testInclusion(tree, key, circuit) {
17
18 const res = await tree.find(key);
19
20 assert(res.found);
21 let siblings = res.siblings;
22 while (siblings.length<10) siblings.push(bigInt(0));
23
24 const w = circuit.calculateWitness({
25 enabled: 1,
26 fnc: 0,
27 root: tree.root,
28 siblings: siblings,
29 oldKey: 0,
30 oldValue: 0,
31 isOld0: 0,
32 key: key,
33 value: res.foundValue
34 });
35
36 assert(circuit.checkWitness(w));
37}
38
39async function testExclusion(tree, key, circuit) {
40 const res = await tree.find(key);
41
42 assert(!res.found);
43 let siblings = res.siblings;
44 while (siblings.length<10) siblings.push(bigInt(0));
45
46 const w = circuit.calculateWitness({
47 enabled: 1,
48 fnc: 1,
49 root: tree.root,
50 siblings: siblings,
51 oldKey: res.isOld0 ? 0 : res.notFoundKey,
52 oldValue: res.isOld0 ? 0 : res.notFoundValue,
53 isOld0: res.isOld0 ? 1 : 0,
54 key: key,
55 value: 0
56 });
57
58 assert(circuit.checkWitness(w));
59}
60
61describe("SMT test", function () {
62 let circuit;
63 let tree;
64
65 this.timeout(100000);
66
67 before( async () => {
68 const cirDef = await compiler(path.join(__dirname, "circuits", "smtverifier10_test.circom"));
69
70 circuit = new snarkjs.Circuit(cirDef);
71
72 console.log("NConstrains SMTVerifier: " + circuit.nConstraints);
73
74 tree = await smt.newMemEmptyTrie();
75 await tree.insert(7,77);
76 await tree.insert(8,88);
77 await tree.insert(32,3232);
78 });
79
80 it("Check inclussion in a tree of 3", async () => {
81 await testInclusion(tree, 7, circuit);
82 await testInclusion(tree, 8, circuit);
83 await testInclusion(tree, 32, circuit);
84 });
85
86 it("Check exclussion in a tree of 3", async () => {
87 await testExclusion(tree, 0, circuit);
88 await testExclusion(tree, 6, circuit);
89 await testExclusion(tree, 9, circuit);
90 await testExclusion(tree, 33, circuit);
91 await testExclusion(tree, 31, circuit);
92 await testExclusion(tree, 16, circuit);
93 await testExclusion(tree, 64, circuit);
94 });
95
96 it("Check not enabled accepts any thing", async () => {
97 let siblings = [];
98 for (let i=0; i<10; i++) siblings.push(i);
99
100 const w = circuit.calculateWitness({
101 enabled: 0,
102 fnc: 0,
103 root: 1,
104 siblings: siblings,
105 oldKey: 22,
106 oldValue: 33,
107 isOld0: 0,
108 key: 44,
109 value: 0
110 });
111 assert(circuit.checkWitness(w));
112 });
113
114
115});