You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

290 lines
8.4 KiB

3 years ago
  1. /* globals WebAssembly */
  2. /*
  3. Copyright 2020 0KIMS association.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. const bigInt = require("big-integer");
  15. const fnv = require("fnv-plus");
  16. function flatArray(a) {
  17. var res = [];
  18. fillArray(res, a);
  19. return res;
  20. function fillArray(res, a) {
  21. if (Array.isArray(a)) {
  22. for (let i=0; i<a.length; i++) {
  23. fillArray(res, a[i]);
  24. }
  25. } else {
  26. res.push(bigInt(a));
  27. }
  28. }
  29. }
  30. function fnvHash(str) {
  31. return fnv.hash(str, 64).hex();
  32. }
  33. module.exports = async function builder(code, options) {
  34. options = options || {};
  35. const memory = new WebAssembly.Memory({initial:20000});
  36. const wasmModule = await WebAssembly.compile(code);
  37. let wc;
  38. const instance = await WebAssembly.instantiate(wasmModule, {
  39. env: {
  40. "memory": memory
  41. },
  42. runtime: {
  43. error: function(code, pstr, a,b,c,d) {
  44. let errStr;
  45. if (code == 7) {
  46. errStr=p2str(pstr) + " " + wc.getFr(b).toString() + " != " + wc.getFr(c).toString() + " " +p2str(d);
  47. } else {
  48. errStr=p2str(pstr)+ " " + a + " " + b + " " + c + " " + d;
  49. }
  50. console.log("ERROR: ", code, errStr);
  51. throw new Error(errStr);
  52. },
  53. log: function(a) {
  54. console.log(wc.getFr(a).toString());
  55. },
  56. logGetSignal: function(signal, pVal) {
  57. if (options.logGetSignal) {
  58. options.logGetSignal(signal, wc.getFr(pVal) );
  59. }
  60. },
  61. logSetSignal: function(signal, pVal) {
  62. if (options.logSetSignal) {
  63. options.logSetSignal(signal, wc.getFr(pVal) );
  64. }
  65. },
  66. logStartComponent: function(cIdx) {
  67. if (options.logStartComponent) {
  68. options.logStartComponent(cIdx);
  69. }
  70. },
  71. logFinishComponent: function(cIdx) {
  72. if (options.logFinishComponent) {
  73. options.logFinishComponent(cIdx);
  74. }
  75. }
  76. }
  77. });
  78. const sanityCheck =
  79. options &&
  80. (
  81. options.sanityCheck ||
  82. options.logGetSignal ||
  83. options.logSetSignal ||
  84. options.logStartComponent ||
  85. options.logFinishComponent
  86. );
  87. wc = new WitnessCalculator(memory, instance, sanityCheck);
  88. return wc;
  89. function p2str(p) {
  90. const i8 = new Uint8Array(memory.buffer);
  91. const bytes = [];
  92. for (let i=0; i8[p+i]>0; i++) bytes.push(i8[p+i]);
  93. return String.fromCharCode.apply(null, bytes);
  94. }
  95. };
  96. class WitnessCalculator {
  97. constructor(memory, instance, sanityCheck) {
  98. this.memory = memory;
  99. this.i32 = new Uint32Array(memory.buffer);
  100. this.instance = instance;
  101. this.n32 = (this.instance.exports.getFrLen() >> 2) - 2;
  102. const pRawPrime = this.instance.exports.getPRawPrime();
  103. console.log("pRawPrime:", pRawPrime);
  104. // console.log("0:", this.i32[(pRawPrime >> 2)]);
  105. this.prime = bigInt(0);
  106. for (let i=this.n32-1; i>=0; i--) {
  107. this.prime = this.prime.shiftLeft(32);
  108. this.prime = this.prime.add(bigInt(this.i32[(pRawPrime >> 2) + i]));
  109. }
  110. console.log("prime:", this.prime);
  111. this.mask32 = bigInt("FFFFFFFF", 16);
  112. console.log("mask32:", this.mask32);
  113. this.NVars = this.instance.exports.getNVars();
  114. console.log("NVars:", this.NVars);
  115. this.n64 = Math.floor((this.prime.bitLength() - 1) / 64)+1;
  116. console.log("n64:", this.n64);
  117. this.R = bigInt.one.shiftLeft(this.n64*64);
  118. console.log("R:", this.R);
  119. this.RInv = this.R.modInv(this.prime);
  120. console.log("RInv:", this.RInv);
  121. this.sanityCheck = sanityCheck;
  122. }
  123. async _doCalculateWitness(input, sanityCheck) {
  124. this.instance.exports.init((this.sanityCheck || sanityCheck) ? 1 : 0);
  125. const pSigOffset = this.allocInt();
  126. console.log("pSigOffset:", pSigOffset);
  127. const pFr = this.allocFr();
  128. console.log("pFr:", pFr);
  129. for (let k in input) {
  130. const h = fnvHash(k);
  131. const hMSB = parseInt(h.slice(0,8), 16);
  132. const hLSB = parseInt(h.slice(8,16), 16);
  133. console.log("h(", k, ") =", h, " = ", hMSB, hLSB);
  134. this.instance.exports.getSignalOffset32(pSigOffset, 0, hMSB, hLSB);
  135. const sigOffset = this.getInt(pSigOffset);
  136. console.log("sigOffset:", sigOffset);
  137. const fArr = flatArray(input[k]);
  138. for (let i=0; i<fArr.length; i++) {
  139. this.setFr(pFr, fArr[i]);
  140. this.instance.exports.setSignal(0, 0, sigOffset + i, pFr);
  141. }
  142. }
  143. }
  144. async calculateWitness(input, sanityCheck) {
  145. const self = this;
  146. const old0 = self.i32[0];
  147. const w = [];
  148. await self._doCalculateWitness(input, sanityCheck);
  149. for (let i=0; i<self.NVars; i++) {
  150. const pWitness = self.instance.exports.getPWitness(i);
  151. w.push(self.getFr(pWitness));
  152. }
  153. self.i32[0] = old0;
  154. return w;
  155. }
  156. async calculateBinWitness(input, sanityCheck) {
  157. const self = this;
  158. const old0 = self.i32[0];
  159. await self._doCalculateWitness(input, sanityCheck);
  160. const pWitnessBuffer = self.instance.exports.getWitnessBuffer();
  161. self.i32[0] = old0;
  162. const buff = self.memory.buffer.slice(pWitnessBuffer, pWitnessBuffer + (self.NVars * self.n64 * 8));
  163. return buff;
  164. }
  165. allocInt() {
  166. const p = this.i32[0];
  167. this.i32[0] = p+8;
  168. return p;
  169. }
  170. allocFr() {
  171. const p = this.i32[0];
  172. this.i32[0] = p+this.n32*4 + 8;
  173. return p;
  174. }
  175. getInt(p) {
  176. return this.i32[p>>2];
  177. }
  178. setInt(p, v) {
  179. this.i32[p>>2] = v;
  180. }
  181. getFr(p) {
  182. const self = this;
  183. const idx = (p>>2);
  184. if (self.i32[idx + 1] & 0x80000000) {
  185. let res= bigInt(0);
  186. for (let i=self.n32-1; i>=0; i--) {
  187. res = res.shiftLeft(32);
  188. res = res.add(bigInt(self.i32[idx+2+i]));
  189. }
  190. if (self.i32[idx + 1] & 0x40000000) {
  191. return fromMontgomery(res);
  192. } else {
  193. return res;
  194. }
  195. } else {
  196. if (self.i32[idx] & 0x80000000) {
  197. return self.prime.add( bigInt(self.i32[idx]).minus(bigInt(0x100000000)) );
  198. } else {
  199. return bigInt(self.i32[idx]);
  200. }
  201. }
  202. function fromMontgomery(n) {
  203. return n.times(self.RInv).mod(self.prime);
  204. }
  205. }
  206. setFr(p, v) {
  207. const self = this;
  208. v = bigInt(v);
  209. if (v.lt(bigInt("80000000", 16)) ) {
  210. return setShortPositive(v);
  211. }
  212. if (v.geq(self.prime.minus(bigInt("80000000", 16))) ) {
  213. return setShortNegative(v);
  214. }
  215. return setLongNormal(v);
  216. function setShortPositive(a) {
  217. self.i32[(p >> 2)] = parseInt(a);
  218. self.i32[(p >> 2) + 1] = 0;
  219. }
  220. function setShortNegative(a) {
  221. const b = bigInt("80000000", 16 ).add(a.minus( self.prime.minus(bigInt("80000000", 16 ))));
  222. self.i32[(p >> 2)] = parseInt(b);
  223. self.i32[(p >> 2) + 1] = 0;
  224. }
  225. function setLongNormal(a) {
  226. self.i32[(p >> 2)] = 0;
  227. self.i32[(p >> 2) + 1] = 0x80000000;
  228. for (let i=0; i<self.n32; i++) {
  229. self.i32[(p >> 2) + 2 + i] = a.shiftRight(i*32).and(self.mask32);
  230. }
  231. console.log(">>>", self.i32[(p >> 2)] , self.i32[(p >> 2) + 1]);
  232. console.log(">>>", self.i32.slice((p >> 2) + 2, (p >> 2) + 2 + self.n32));
  233. }
  234. }
  235. }