circomlib/test/smt.js
test/smt.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
16
17describe("SMT test", function () {
18 let circuit;
19 let tree;
20
21 this.timeout(100000);
22
23 before( async () => {
24 const cirDef = await compiler(path.join(__dirname, "circuits", "smtinsert10_test.circom"));
25
26 circuit = new snarkjs.Circuit(cirDef);
27
28 console.log("NConstrains SMTInsert: " + circuit.nConstraints);
29
30 tree = await smt.newMemEmptyTrie();
31 });
32
33 it("Should verify an insert to an empty tree", async () => {
34 const key = bigInt(111);
35 const value = bigInt(222);
36
37 const res = await tree.insert(key,value);
38 let siblings = res.sibblings;
39 while (siblings.length<10) siblings.push(bigInt(0));
40
41 const w = circuit.calculateWitness({
42 oldRoot: res.oldRoot,
43 newRoot: res.newRoot,
44 siblings: siblings,
45 oldKey: res.oldKey,
46 oldValue: res.oldValue,
47 isOld0: res.isOld0 ? 1 : 0,
48 newKey: key,
49 newValue: value
50 });
51
52 const root1 = w[circuit.getSignalIdx("main.levels[0].newRoot")];
53
54 console.log("root1: " + root1.toString());
55 console.log("root2: " + res.newRoot.toString());
56 assert(root1.equals(res.newRoot));
57
58 assert(circuit.checkWitness(w));
59 });
60
61 it("It should add another element", async () => {
62 const key = bigInt(333);
63 const value = bigInt(444);
64
65 const res = await tree.insert(key,value);
66 let siblings = res.sibblings;
67 while (siblings.length<10) siblings.push(bigInt(0));
68
69 const w = circuit.calculateWitness({
70 oldRoot: res.oldRoot,
71 newRoot: res.newRoot,
72 siblings: siblings,
73 oldKey: res.oldKey,
74 oldValue: res.oldValue,
75 isOld0: res.isOld0 ? 1 : 0,
76 newKey: key,
77 newValue: value
78 });
79
80 const root1 = w[circuit.getSignalIdx("main.levels[0].newRoot")];
81
82 console.log("root1: " + root1.toString());
83 console.log("root2: " + res.newRoot.toString());
84 assert(root1.equals(res.newRoot));
85
86 assert(circuit.checkWitness(w));
87 });
88});