UNPKG

snarkjs

Version:

zkSNARKs implementation in JavaScript

1,797 lines (1,419 loc) 569 kB
import { Scalar, BigBuffer, buildBn128, buildBls12381, ChaCha, F1Field, utils, getCurveFromR as getCurveFromR$1 } from 'ffjavascript'; var fs = {}; async function open(fileName, openFlags, cacheSize, pageSize) { cacheSize = cacheSize || 4096*64; if (typeof openFlags !== "number" && ["w+", "wx+", "r", "ax+", "a+"].indexOf(openFlags) <0) throw new Error("Invalid open option"); const fd =await fs.promises.open(fileName, openFlags); const stats = await fd.stat(); return new FastFile(fd, stats, cacheSize, pageSize, fileName); } class FastFile { constructor(fd, stats, cacheSize, pageSize, fileName) { this.fileName = fileName; this.fd = fd; this.pos = 0; this.pageSize = pageSize || (1 << 8); while (this.pageSize < stats.blksize) { this.pageSize *= 2; } this.totalSize = stats.size; this.totalPages = Math.floor((stats.size -1) / this.pageSize)+1; this.maxPagesLoaded = Math.floor( cacheSize / this.pageSize)+1; this.pages = {}; this.pendingLoads = []; this.writing = false; this.reading = false; this.avBuffs = []; this.history = {}; } _loadPage(p) { const self = this; const P = new Promise((resolve, reject)=> { self.pendingLoads.push({ page: p, resolve: resolve, reject: reject }); }); self.__statusPage("After Load request: ", p); return P; } __statusPage(s, p) { const logEntry = []; const self=this; if (!self.logHistory) return; logEntry.push("==" + s+ " " +p); let S = ""; for (let i=0; i<self.pendingLoads.length; i++) { if (self.pendingLoads[i].page == p) S = S + " " + i; } if (S) logEntry.push("Pending loads:"+S); if (typeof self.pages[p] != "undefined") { const page = self.pages[p]; logEntry.push("Loaded"); logEntry.push("pendingOps: "+page.pendingOps); if (page.loading) logEntry.push("loading: "+page.loading); if (page.writing) logEntry.push("writing"); if (page.dirty) logEntry.push("dirty"); } logEntry.push("=="); if (!self.history[p]) self.history[p] = []; self.history[p].push(logEntry); } __printHistory(p) { const self = this; if (!self.history[p]) console.log("Empty History ", p); console.log("History "+p); for (let i=0; i<self.history[p].length; i++) { for (let j=0; j<self.history[p][i].length; j++) { console.log("-> " + self.history[p][i][j]); } } } _triggerLoad() { const self = this; if (self.reading) return; if (self.pendingLoads.length==0) return; const pageIdxs = Object.keys(self.pages); const deletablePages = []; for (let i=0; i<pageIdxs.length; i++) { const page = self.pages[parseInt(pageIdxs[i])]; if ((page.dirty == false)&&(page.pendingOps==0)&&(!page.writing)&&(!page.loading)) deletablePages.push(parseInt(pageIdxs[i])); } let freePages = self.maxPagesLoaded - pageIdxs.length; const ops = []; // while pending loads and // the page is loaded or I can recover one. while ( (self.pendingLoads.length>0) && ( (typeof self.pages[self.pendingLoads[0].page] != "undefined" ) ||( (freePages>0) ||(deletablePages.length>0)))) { const load = self.pendingLoads.shift(); if (typeof self.pages[load.page] != "undefined") { self.pages[load.page].pendingOps ++; const idx = deletablePages.indexOf(load.page); if (idx>=0) deletablePages.splice(idx, 1); if (self.pages[load.page].loading) { self.pages[load.page].loading.push(load); } else { load.resolve(); } self.__statusPage("After Load (cached): ", load.page); } else { if (freePages) { freePages--; } else { const fp = deletablePages.shift(); self.__statusPage("Before Unload: ", fp); self.avBuffs.unshift(self.pages[fp]); delete self.pages[fp]; self.__statusPage("After Unload: ", fp); } if (load.page>=self.totalPages) { self.pages[load.page] = getNewPage(); load.resolve(); self.__statusPage("After Load (new): ", load.page); } else { self.reading = true; self.pages[load.page] = getNewPage(); self.pages[load.page].loading = [load]; ops.push(self.fd.read(self.pages[load.page].buff, 0, self.pageSize, load.page*self.pageSize).then((res)=> { self.pages[load.page].size = res.bytesRead; const loading = self.pages[load.page].loading; delete self.pages[load.page].loading; for (let i=0; i<loading.length; i++) { loading[i].resolve(); } self.__statusPage("After Load (loaded): ", load.page); return res; }, (err) => { load.reject(err); })); self.__statusPage("After Load (loading): ", load.page); } } } // if (ops.length>1) console.log(ops.length); Promise.all(ops).then( () => { self.reading = false; if (self.pendingLoads.length>0) setImmediate(self._triggerLoad.bind(self)); self._tryClose(); }); function getNewPage() { if (self.avBuffs.length>0) { const p = self.avBuffs.shift(); p.dirty = false; p.pendingOps = 1; p.size =0; return p; } else { return { dirty: false, buff: new Uint8Array(self.pageSize), pendingOps: 1, size: 0 }; } } } _triggerWrite() { const self = this; if (self.writing) return; const pageIdxs = Object.keys(self.pages); const ops = []; for (let i=0; i<pageIdxs.length; i++) { const page = self.pages[parseInt(pageIdxs[i])]; if (page.dirty) { page.dirty = false; page.writing = true; self.writing = true; ops.push( self.fd.write(page.buff, 0, page.size, parseInt(pageIdxs[i])*self.pageSize).then(() => { page.writing = false; return; }, (err) => { console.log("ERROR Writing: "+err); self.error = err; self._tryClose(); })); } } if (self.writing) { Promise.all(ops).then( () => { self.writing = false; setImmediate(self._triggerWrite.bind(self)); self._tryClose(); if (self.pendingLoads.length>0) setImmediate(self._triggerLoad.bind(self)); }); } } _getDirtyPage() { for (let p in this.pages) { if (this.pages[p].dirty) return p; } return -1; } async write(buff, pos) { if (buff.byteLength == 0) return; const self = this; /* if (buff.byteLength > self.pageSize*self.maxPagesLoaded*0.8) { const cacheSize = Math.floor(buff.byteLength * 1.1); this.maxPagesLoaded = Math.floor( cacheSize / self.pageSize)+1; } */ if (typeof pos == "undefined") pos = self.pos; self.pos = pos+buff.byteLength; if (self.totalSize < pos + buff.byteLength) self.totalSize = pos + buff.byteLength; if (self.pendingClose) throw new Error("Writing a closing file"); const firstPage = Math.floor(pos / self.pageSize); const lastPage = Math.floor((pos + buff.byteLength -1) / self.pageSize); const pagePromises = []; for (let i=firstPage; i<=lastPage; i++) pagePromises.push(self._loadPage(i)); self._triggerLoad(); let p = firstPage; let o = pos % self.pageSize; let r = buff.byteLength; while (r>0) { await pagePromises[p-firstPage]; const l = (o+r > self.pageSize) ? (self.pageSize -o) : r; const srcView = buff.slice( buff.byteLength - r, buff.byteLength - r + l); const dstView = new Uint8Array(self.pages[p].buff.buffer, o, l); dstView.set(srcView); self.pages[p].dirty = true; self.pages[p].pendingOps --; self.pages[p].size = Math.max(o+l, self.pages[p].size); if (p>=self.totalPages) { self.totalPages = p+1; } r = r-l; p ++; o = 0; if (!self.writing) setImmediate(self._triggerWrite.bind(self)); } } async read(len, pos) { const self = this; let buff = new Uint8Array(len); await self.readToBuffer(buff, 0, len, pos); return buff; } async readToBuffer(buffDst, offset, len, pos) { if (len == 0) { return; } const self = this; if (len > self.pageSize*self.maxPagesLoaded*0.8) { const cacheSize = Math.floor(len * 1.1); this.maxPagesLoaded = Math.floor( cacheSize / self.pageSize)+1; } if (typeof pos == "undefined") pos = self.pos; self.pos = pos+len; if (self.pendingClose) throw new Error("Reading a closing file"); const firstPage = Math.floor(pos / self.pageSize); const lastPage = Math.floor((pos + len -1) / self.pageSize); const pagePromises = []; for (let i=firstPage; i<=lastPage; i++) pagePromises.push(self._loadPage(i)); self._triggerLoad(); let p = firstPage; let o = pos % self.pageSize; // Remaining bytes to read let r = pos + len > self.totalSize ? len - (pos + len - self.totalSize): len; while (r>0) { await pagePromises[p - firstPage]; self.__statusPage("After Await (read): ", p); // bytes to copy from this page const l = (o+r > self.pageSize) ? (self.pageSize -o) : r; const srcView = new Uint8Array(self.pages[p].buff.buffer, self.pages[p].buff.byteOffset + o, l); buffDst.set(srcView, offset+len-r); self.pages[p].pendingOps --; self.__statusPage("After Op done: ", p); r = r-l; p ++; o = 0; if (self.pendingLoads.length>0) setImmediate(self._triggerLoad.bind(self)); } this.pos = pos + len; } _tryClose() { const self = this; if (!self.pendingClose) return; if (self.error) { self.pendingCloseReject(self.error); } const p = self._getDirtyPage(); if ((p>=0) || (self.writing) || (self.reading) || (self.pendingLoads.length>0)) return; self.pendingClose(); } close() { const self = this; if (self.pendingClose) throw new Error("Closing the file twice"); return new Promise((resolve, reject) => { self.pendingClose = resolve; self.pendingCloseReject = reject; self._tryClose(); }).then(()=> { self.fd.close(); }, (err) => { self.fd.close(); throw (err); }); } async discard() { const self = this; await self.close(); await fs.promises.unlink(this.fileName); } async writeULE32(v, pos) { const self = this; const tmpBuff32 = new Uint8Array(4); const tmpBuff32v = new DataView(tmpBuff32.buffer); tmpBuff32v.setUint32(0, v, true); await self.write(tmpBuff32, pos); } async writeUBE32(v, pos) { const self = this; const tmpBuff32 = new Uint8Array(4); const tmpBuff32v = new DataView(tmpBuff32.buffer); tmpBuff32v.setUint32(0, v, false); await self.write(tmpBuff32, pos); } async writeULE64(v, pos) { const self = this; const tmpBuff64 = new Uint8Array(8); const tmpBuff64v = new DataView(tmpBuff64.buffer); tmpBuff64v.setUint32(0, v & 0xFFFFFFFF, true); tmpBuff64v.setUint32(4, Math.floor(v / 0x100000000) , true); await self.write(tmpBuff64, pos); } async readULE32(pos) { const self = this; const b = await self.read(4, pos); const view = new Uint32Array(b.buffer); return view[0]; } async readUBE32(pos) { const self = this; const b = await self.read(4, pos); const view = new DataView(b.buffer); return view.getUint32(0, false); } async readULE64(pos) { const self = this; const b = await self.read(8, pos); const view = new Uint32Array(b.buffer); return view[1] * 0x100000000 + view[0]; } async readString(pos) { const self = this; if (self.pendingClose) { throw new Error("Reading a closing file"); } let currentPosition = typeof pos == "undefined" ? self.pos : pos; let currentPage = Math.floor(currentPosition / self.pageSize); let endOfStringFound = false; let str = ""; while (!endOfStringFound) { //Read page let pagePromise = self._loadPage(currentPage); self._triggerLoad(); await pagePromise; self.__statusPage("After Await (read): ", currentPage); let offsetOnPage = currentPosition % self.pageSize; const dataArray = new Uint8Array( self.pages[currentPage].buff.buffer, self.pages[currentPage].buff.byteOffset + offsetOnPage, self.pageSize - offsetOnPage ); let indexEndOfString = dataArray.findIndex(element => element === 0); endOfStringFound = indexEndOfString !== -1; if (endOfStringFound) { str += new TextDecoder().decode(dataArray.slice(0, indexEndOfString)); self.pos = currentPage * this.pageSize + offsetOnPage + indexEndOfString + 1; } else { str += new TextDecoder().decode(dataArray); self.pos = currentPage * this.pageSize + offsetOnPage + dataArray.length; } self.pages[currentPage].pendingOps--; self.__statusPage("After Op done: ", currentPage); currentPosition = self.pos; currentPage++; if (self.pendingLoads.length > 0) setImmediate(self._triggerLoad.bind(self)); } return str; } } function createNew$1(o) { const initialSize = o.initialSize || 1<<20; const fd = new MemFile(); fd.o = o; fd.o.data = new Uint8Array(initialSize); fd.allocSize = initialSize; fd.totalSize = 0; fd.readOnly = false; fd.pos = 0; return fd; } function readExisting$2(o) { const fd = new MemFile(); fd.o = o; fd.allocSize = o.data.byteLength; fd.totalSize = o.data.byteLength; fd.readOnly = true; fd.pos = 0; return fd; } const tmpBuff32$1 = new Uint8Array(4); const tmpBuff32v$1 = new DataView(tmpBuff32$1.buffer); const tmpBuff64$1 = new Uint8Array(8); const tmpBuff64v$1 = new DataView(tmpBuff64$1.buffer); class MemFile { constructor() { this.pageSize = 1 << 14; // for compatibility } _resizeIfNeeded(newLen) { if (newLen > this.allocSize) { const newAllocSize = Math.max( this.allocSize + (1 << 20), Math.floor(this.allocSize * 1.1), newLen ); const newData = new Uint8Array(newAllocSize); newData.set(this.o.data); this.o.data = newData; this.allocSize = newAllocSize; } } async write(buff, pos) { const self =this; if (typeof pos == "undefined") pos = self.pos; if (this.readOnly) throw new Error("Writing a read only file"); this._resizeIfNeeded(pos + buff.byteLength); this.o.data.set(buff.slice(), pos); if (pos + buff.byteLength > this.totalSize) this.totalSize = pos + buff.byteLength; this.pos = pos + buff.byteLength; } async readToBuffer(buffDest, offset, len, pos) { const self = this; if (typeof pos == "undefined") pos = self.pos; if (this.readOnly) { if (pos + len > this.totalSize) throw new Error("Reading out of bounds"); } this._resizeIfNeeded(pos + len); const buffSrc = new Uint8Array(this.o.data.buffer, this.o.data.byteOffset + pos, len); buffDest.set(buffSrc, offset); this.pos = pos + len; } async read(len, pos) { const self = this; const buff = new Uint8Array(len); await self.readToBuffer(buff, 0, len, pos); return buff; } close() { if (this.o.data.byteLength != this.totalSize) { this.o.data = this.o.data.slice(0, this.totalSize); } } async discard() { } async writeULE32(v, pos) { const self = this; tmpBuff32v$1.setUint32(0, v, true); await self.write(tmpBuff32$1, pos); } async writeUBE32(v, pos) { const self = this; tmpBuff32v$1.setUint32(0, v, false); await self.write(tmpBuff32$1, pos); } async writeULE64(v, pos) { const self = this; tmpBuff64v$1.setUint32(0, v & 0xFFFFFFFF, true); tmpBuff64v$1.setUint32(4, Math.floor(v / 0x100000000) , true); await self.write(tmpBuff64$1, pos); } async readULE32(pos) { const self = this; const b = await self.read(4, pos); const view = new Uint32Array(b.buffer); return view[0]; } async readUBE32(pos) { const self = this; const b = await self.read(4, pos); const view = new DataView(b.buffer); return view.getUint32(0, false); } async readULE64(pos) { const self = this; const b = await self.read(8, pos); const view = new Uint32Array(b.buffer); return view[1] * 0x100000000 + view[0]; } async readString(pos) { const self = this; let currentPosition = typeof pos == "undefined" ? self.pos : pos; if (currentPosition > this.totalSize) { if (this.readOnly) { throw new Error("Reading out of bounds"); } this._resizeIfNeeded(pos); } const dataArray = new Uint8Array( self.o.data.buffer, currentPosition, this.totalSize - currentPosition ); let indexEndOfString = dataArray.findIndex(element => element === 0); let endOfStringFound = indexEndOfString !== -1; let str = ""; if (endOfStringFound) { str = new TextDecoder().decode(dataArray.slice(0, indexEndOfString)); self.pos = currentPosition + indexEndOfString + 1; } else { self.pos = currentPosition; } return str; } } const PAGE_SIZE = 1<<22; function createNew(o) { const initialSize = o.initialSize || 0; const fd = new BigMemFile(); fd.o = o; const nPages = initialSize ? Math.floor((initialSize - 1) / PAGE_SIZE)+1 : 0; fd.o.data = []; for (let i=0; i<nPages-1; i++) { fd.o.data.push( new Uint8Array(PAGE_SIZE)); } if (nPages) fd.o.data.push( new Uint8Array(initialSize - PAGE_SIZE*(nPages-1))); fd.totalSize = 0; fd.readOnly = false; fd.pos = 0; return fd; } function readExisting$1(o) { const fd = new BigMemFile(); fd.o = o; fd.totalSize = (o.data.length-1)* PAGE_SIZE + o.data[o.data.length-1].byteLength; fd.readOnly = true; fd.pos = 0; return fd; } const tmpBuff32 = new Uint8Array(4); const tmpBuff32v = new DataView(tmpBuff32.buffer); const tmpBuff64 = new Uint8Array(8); const tmpBuff64v = new DataView(tmpBuff64.buffer); class BigMemFile { constructor() { this.pageSize = 1 << 14; // for compatibility } _resizeIfNeeded(newLen) { if (newLen <= this.totalSize) return; if (this.readOnly) throw new Error("Reading out of file bounds"); const nPages = Math.floor((newLen - 1) / PAGE_SIZE)+1; for (let i= Math.max(this.o.data.length-1, 0); i<nPages; i++) { const newSize = i<nPages-1 ? PAGE_SIZE : newLen - (nPages-1)*PAGE_SIZE; const p = new Uint8Array(newSize); if (i == this.o.data.length-1) p.set(this.o.data[i]); this.o.data[i] = p; } this.totalSize = newLen; } async write(buff, pos) { const self =this; if (typeof pos == "undefined") pos = self.pos; if (this.readOnly) throw new Error("Writing a read only file"); this._resizeIfNeeded(pos + buff.byteLength); const firstPage = Math.floor(pos / PAGE_SIZE); let p = firstPage; let o = pos % PAGE_SIZE; let r = buff.byteLength; while (r>0) { const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; const srcView = buff.slice(buff.byteLength - r, buff.byteLength - r + l); const dstView = new Uint8Array(self.o.data[p].buffer, o, l); dstView.set(srcView); r = r-l; p ++; o = 0; } this.pos = pos + buff.byteLength; } async readToBuffer(buffDst, offset, len, pos) { const self = this; if (typeof pos == "undefined") pos = self.pos; if (this.readOnly) { if (pos + len > this.totalSize) throw new Error("Reading out of bounds"); } this._resizeIfNeeded(pos + len); const firstPage = Math.floor(pos / PAGE_SIZE); let p = firstPage; let o = pos % PAGE_SIZE; // Remaining bytes to read let r = len; while (r>0) { // bytes to copy from this page const l = (o+r > PAGE_SIZE) ? (PAGE_SIZE -o) : r; const srcView = new Uint8Array(self.o.data[p].buffer, o, l); buffDst.set(srcView, offset+len-r); r = r-l; p ++; o = 0; } this.pos = pos + len; } async read(len, pos) { const self = this; const buff = new Uint8Array(len); await self.readToBuffer(buff, 0, len, pos); return buff; } close() { } async discard() { } async writeULE32(v, pos) { const self = this; tmpBuff32v.setUint32(0, v, true); await self.write(tmpBuff32, pos); } async writeUBE32(v, pos) { const self = this; tmpBuff32v.setUint32(0, v, false); await self.write(tmpBuff32, pos); } async writeULE64(v, pos) { const self = this; tmpBuff64v.setUint32(0, v & 0xFFFFFFFF, true); tmpBuff64v.setUint32(4, Math.floor(v / 0x100000000) , true); await self.write(tmpBuff64, pos); } async readULE32(pos) { const self = this; const b = await self.read(4, pos); const view = new Uint32Array(b.buffer); return view[0]; } async readUBE32(pos) { const self = this; const b = await self.read(4, pos); const view = new DataView(b.buffer); return view.getUint32(0, false); } async readULE64(pos) { const self = this; const b = await self.read(8, pos); const view = new Uint32Array(b.buffer); return view[1] * 0x100000000 + view[0]; } async readString(pos) { const self = this; const fixedSize = 2048; let currentPosition = typeof pos == "undefined" ? self.pos : pos; if (currentPosition > this.totalSize) { if (this.readOnly) { throw new Error("Reading out of bounds"); } this._resizeIfNeeded(pos); } let endOfStringFound = false; let str = ""; while (!endOfStringFound) { let currentPage = Math.floor(currentPosition / PAGE_SIZE); let offsetOnPage = currentPosition % PAGE_SIZE; if (self.o.data[currentPage] === undefined) { throw new Error("ERROR"); } let readLength = Math.min(fixedSize, self.o.data[currentPage].length - offsetOnPage); const dataArray = new Uint8Array(self.o.data[currentPage].buffer, offsetOnPage, readLength); let indexEndOfString = dataArray.findIndex(element => element === 0); endOfStringFound = indexEndOfString !== -1; if (endOfStringFound) { str += new TextDecoder().decode(dataArray.slice(0, indexEndOfString)); self.pos = currentPage * PAGE_SIZE + offsetOnPage + indexEndOfString + 1; } else { str += new TextDecoder().decode(dataArray); self.pos = currentPage * PAGE_SIZE + offsetOnPage + dataArray.length; } currentPosition = self.pos; } return str; } } const O_TRUNC = 1024; const O_CREAT = 512; const O_RDWR = 2; const O_RDONLY = 0; /* global fetch */ const DEFAULT_CACHE_SIZE = (1 << 16); const DEFAULT_PAGE_SIZE = (1 << 13); async function createOverride(o, b, c) { if (typeof o === "string") { o = { type: "file", fileName: o, cacheSize: b || DEFAULT_CACHE_SIZE, pageSize: c || DEFAULT_PAGE_SIZE }; } if (o.type == "file") { return await open(o.fileName, O_TRUNC | O_CREAT | O_RDWR, o.cacheSize, o.pageSize); } else if (o.type == "mem") { return createNew$1(o); } else if (o.type == "bigMem") { return createNew(o); } else { throw new Error("Invalid FastFile type: "+o.type); } } async function readExisting(o, b, c) { if (o instanceof Uint8Array) { o = { type: "mem", data: o }; } { if (typeof o === "string") { const buff = await fetch(o).then( function(res) { return res.arrayBuffer(); }).then(function (ab) { return new Uint8Array(ab); }); o = { type: "mem", data: buff }; } } if (o.type == "file") { return await open(o.fileName, O_RDONLY, o.cacheSize, o.pageSize); } else if (o.type == "mem") { return await readExisting$2(o); } else if (o.type == "bigMem") { return await readExisting$1(o); } else { throw new Error("Invalid FastFile type: "+o.type); } } async function readBinFile(fileName, type, maxVersion, cacheSize, pageSize) { const fd = await readExisting(fileName); const b = await fd.read(4); let readedType = ""; for (let i=0; i<4; i++) readedType += String.fromCharCode(b[i]); if (readedType != type) throw new Error(fileName + ": Invalid File format"); let v = await fd.readULE32(); if (v>maxVersion) throw new Error("Version not supported"); const nSections = await fd.readULE32(); // Scan sections let sections = []; for (let i=0; i<nSections; i++) { let ht = await fd.readULE32(); let hl = await fd.readULE64(); if (typeof sections[ht] == "undefined") sections[ht] = []; sections[ht].push({ p: fd.pos, size: hl }); fd.pos += hl; } return {fd, sections}; } async function createBinFile(fileName, type, version, nSections, cacheSize, pageSize) { const fd = await createOverride(fileName, cacheSize, pageSize); const buff = new Uint8Array(4); for (let i=0; i<4; i++) buff[i] = type.charCodeAt(i); await fd.write(buff, 0); // Magic "r1cs" await fd.writeULE32(version); // Version await fd.writeULE32(nSections); // Number of Sections return fd; } async function startWriteSection(fd, idSection) { if (typeof fd.writingSection !== "undefined") throw new Error("Already writing a section"); await fd.writeULE32(idSection); // Header type fd.writingSection = { pSectionSize: fd.pos }; await fd.writeULE64(0); // Temporally set to 0 length } async function endWriteSection(fd) { if (typeof fd.writingSection === "undefined") throw new Error("Not writing a section"); const sectionSize = fd.pos - fd.writingSection.pSectionSize - 8; const oldPos = fd.pos; fd.pos = fd.writingSection.pSectionSize; await fd.writeULE64(sectionSize); fd.pos = oldPos; delete fd.writingSection; } async function startReadUniqueSection(fd, sections, idSection) { if (typeof fd.readingSection !== "undefined") throw new Error("Already reading a section"); if (!sections[idSection]) throw new Error(fd.fileName + ": Missing section "+ idSection ); if (sections[idSection].length>1) throw new Error(fd.fileName +": Section Duplicated " +idSection); fd.pos = sections[idSection][0].p; fd.readingSection = sections[idSection][0]; } async function endReadSection(fd, noCheck) { if (typeof fd.readingSection === "undefined") throw new Error("Not reading a section"); if (!noCheck) { if (fd.pos-fd.readingSection.p != fd.readingSection.size) throw new Error("Invalid section size reading"); } delete fd.readingSection; } async function writeBigInt(fd, n, n8, pos) { const buff = new Uint8Array(n8); Scalar.toRprLE(buff, 0, n, n8); await fd.write(buff, pos); } async function readBigInt(fd, n8, pos) { const buff = await fd.read(n8, pos); return Scalar.fromRprLE(buff, 0, n8); } async function copySection(fdFrom, sections, fdTo, sectionId, size) { if (typeof size === "undefined") { size = sections[sectionId][0].size; } const chunkSize = fdFrom.pageSize; await startReadUniqueSection(fdFrom, sections, sectionId); await startWriteSection(fdTo, sectionId); for (let p=0; p<size; p+=chunkSize) { const l = Math.min(size -p, chunkSize); const buff = await fdFrom.read(l); await fdTo.write(buff); } await endWriteSection(fdTo); await endReadSection(fdFrom, size != sections[sectionId][0].size); } async function readSection(fd, sections, idSection, offset, length) { offset = (typeof offset === "undefined") ? 0 : offset; length = (typeof length === "undefined") ? sections[idSection][0].size - offset : length; if (offset + length > sections[idSection][0].size) { throw new Error("Reading out of the range of the section"); } let buff; if (length < (1 << 30) ) { buff = new Uint8Array(length); } else { buff = new BigBuffer(length); } await fd.readToBuffer(buff, 0, length, sections[idSection][0].p + offset); return buff; } async function sectionIsEqual(fd1, sections1, fd2, sections2, idSection) { const MAX_BUFF_SIZE = fd1.pageSize * 16; await startReadUniqueSection(fd1, sections1, idSection); await startReadUniqueSection(fd2, sections2, idSection); if (sections1[idSection][0].size != sections2[idSection][0].size) return false; const totalBytes=sections1[idSection][0].size; for (let i=0; i<totalBytes; i+= MAX_BUFF_SIZE) { const n = Math.min(totalBytes-i, MAX_BUFF_SIZE); const buff1 = await fd1.read(n); const buff2 = await fd2.read(n); for (let j=0; j<n; j++) if (buff1[j] != buff2[j]) return false; } await endReadSection(fd1); await endReadSection(fd2); return true; } const bls12381r$1 = Scalar.e("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001", 16); const bn128r$1 = Scalar.e("21888242871839275222246405745257275088548364400416034343698204186575808495617"); const bls12381q = Scalar.e("1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab", 16); const bn128q = Scalar.e("21888242871839275222246405745257275088696311157297823662689037894645226208583"); async function getCurveFromR(r, options) { let curve; // check that options param is defined and that options.singleThread is defined let singleThread = options && options.singleThread; if (Scalar.eq(r, bn128r$1)) { curve = await buildBn128(singleThread); } else if (Scalar.eq(r, bls12381r$1)) { curve = await buildBls12381(singleThread); } else { throw new Error(`Curve not supported: ${Scalar.toString(r)}`); } return curve; } async function getCurveFromQ(q, options) { let curve; let singleThread = options && options.singleThread; if (Scalar.eq(q, bn128q)) { curve = await buildBn128(singleThread); } else if (Scalar.eq(q, bls12381q)) { curve = await buildBls12381(singleThread); } else { throw new Error(`Curve not supported: ${Scalar.toString(q)}`); } return curve; } async function getCurveFromName(name, options) { let curve; let singleThread = options && options.singleThread; const normName = normalizeName(name); if (["BN128", "BN254", "ALTBN128"].indexOf(normName) >= 0) { curve = await buildBn128(singleThread); } else if (["BLS12381"].indexOf(normName) >= 0) { curve = await buildBls12381(singleThread); } else { throw new Error(`Curve not supported: ${name}`); } return curve; function normalizeName(n) { return n.toUpperCase().match(/[A-Za-z0-9]+/g).join(""); } } var curves = /*#__PURE__*/Object.freeze({ __proto__: null, getCurveFromR: getCurveFromR, getCurveFromQ: getCurveFromQ, getCurveFromName: getCurveFromName }); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var blake2bWasm = {exports: {}}; var nanoassert = assert$1; class AssertionError extends Error {} AssertionError.prototype.name = 'AssertionError'; /** * Minimal assert function * @param {any} t Value to check if falsy * @param {string=} m Optional assertion error message * @throws {AssertionError} */ function assert$1 (t, m) { if (!t) { var err = new AssertionError(m); if (Error.captureStackTrace) Error.captureStackTrace(err, assert$1); throw err } } var browser = {exports: {}}; function byteLength$4 (string) { return string.length } function toString$4 (buffer) { const len = buffer.byteLength; let result = ''; for (let i = 0; i < len; i++) { result += String.fromCharCode(buffer[i]); } return result } function write$5 (buffer, string, offset = 0, length = byteLength$4(string)) { const len = Math.min(length, buffer.byteLength - offset); for (let i = 0; i < len; i++) { buffer[offset + i] = string.charCodeAt(i); } return len } var ascii = { byteLength: byteLength$4, toString: toString$4, write: write$5 }; const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; const codes = new Uint8Array(256); for (let i = 0; i < alphabet.length; i++) { codes[alphabet.charCodeAt(i)] = i; } codes[/* - */ 0x2d] = 62; codes[/* _ */ 0x5f] = 63; function byteLength$3 (string) { let len = string.length; if (string.charCodeAt(len - 1) === 0x3d) len--; if (len > 1 && string.charCodeAt(len - 1) === 0x3d) len--; return (len * 3) >>> 2 } function toString$3 (buffer) { const len = buffer.byteLength; let result = ''; for (let i = 0; i < len; i += 3) { result += ( alphabet[buffer[i] >> 2] + alphabet[((buffer[i] & 3) << 4) | (buffer[i + 1] >> 4)] + alphabet[((buffer[i + 1] & 15) << 2) | (buffer[i + 2] >> 6)] + alphabet[buffer[i + 2] & 63] ); } if (len % 3 === 2) { result = result.substring(0, result.length - 1) + '='; } else if (len % 3 === 1) { result = result.substring(0, result.length - 2) + '=='; } return result } function write$4 (buffer, string, offset = 0, length = byteLength$3(string)) { const len = Math.min(length, buffer.byteLength - offset); for (let i = 0, j = 0; j < len; i += 4) { const a = codes[string.charCodeAt(i)]; const b = codes[string.charCodeAt(i + 1)]; const c = codes[string.charCodeAt(i + 2)]; const d = codes[string.charCodeAt(i + 3)]; buffer[j++] = (a << 2) | (b >> 4); buffer[j++] = ((b & 15) << 4) | (c >> 2); buffer[j++] = ((c & 3) << 6) | (d & 63); } return len } var base64 = { byteLength: byteLength$3, toString: toString$3, write: write$4 }; function byteLength$2 (string) { return string.length >>> 1 } function toString$2 (buffer) { const len = buffer.byteLength; buffer = new DataView(buffer.buffer, buffer.byteOffset, len); let result = ''; let i = 0; for (let n = len - (len % 4); i < n; i += 4) { result += buffer.getUint32(i).toString(16).padStart(8, '0'); } for (; i < len; i++) { result += buffer.getUint8(i).toString(16).padStart(2, '0'); } return result } function write$3 (buffer, string, offset = 0, length = byteLength$2(string)) { const len = Math.min(length, buffer.byteLength - offset); for (let i = 0; i < len; i++) { const a = hexValue(string.charCodeAt(i * 2)); const b = hexValue(string.charCodeAt(i * 2 + 1)); if (a === undefined || b === undefined) { return buffer.subarray(0, i) } buffer[offset + i] = (a << 4) | b; } return len } var hex = { byteLength: byteLength$2, toString: toString$2, write: write$3 }; function hexValue (char) { if (char >= 0x30 && char <= 0x39) return char - 0x30 if (char >= 0x41 && char <= 0x46) return char - 0x41 + 10 if (char >= 0x61 && char <= 0x66) return char - 0x61 + 10 } function byteLength$1 (string) { let length = 0; for (let i = 0, n = string.length; i < n; i++) { const code = string.charCodeAt(i); if (code >= 0xd800 && code <= 0xdbff && i + 1 < n) { const code = string.charCodeAt(i + 1); if (code >= 0xdc00 && code <= 0xdfff) { length += 4; i++; continue } } if (code <= 0x7f) length += 1; else if (code <= 0x7ff) length += 2; else length += 3; } return length } let toString$1; if (typeof TextDecoder !== 'undefined') { const decoder = new TextDecoder(); toString$1 = function toString (buffer) { return decoder.decode(buffer) }; } else { toString$1 = function toString (buffer) { const len = buffer.byteLength; let output = ''; let i = 0; while (i < len) { let byte = buffer[i]; if (byte <= 0x7f) { output += String.fromCharCode(byte); i++; continue } let bytesNeeded = 0; let codePoint = 0; if (byte <= 0xdf) { bytesNeeded = 1; codePoint = byte & 0x1f; } else if (byte <= 0xef) { bytesNeeded = 2; codePoint = byte & 0x0f; } else if (byte <= 0xf4) { bytesNeeded = 3; codePoint = byte & 0x07; } if (len - i - bytesNeeded > 0) { let k = 0; while (k < bytesNeeded) { byte = buffer[i + k + 1]; codePoint = (codePoint << 6) | (byte & 0x3f); k += 1; } } else { codePoint = 0xfffd; bytesNeeded = len - i; } output += String.fromCodePoint(codePoint); i += bytesNeeded + 1; } return output }; } let write$2; if (typeof TextEncoder !== 'undefined') { const encoder = new TextEncoder(); write$2 = function write (buffer, string, offset = 0, length = byteLength$1(string)) { const len = Math.min(length, buffer.byteLength - offset); encoder.encodeInto(string, buffer.subarray(offset, offset + len)); return len }; } else { write$2 = function write (buffer, string, offset = 0, length = byteLength$1(string)) { const len = Math.min(length, buffer.byteLength - offset); buffer = buffer.subarray(offset, offset + len); let i = 0; let j = 0; while (i < string.length) { const code = string.codePointAt(i); if (code <= 0x7f) { buffer[j++] = code; i++; continue } let count = 0; let bits = 0; if (code <= 0x7ff) { count = 6; bits = 0xc0; } else if (code <= 0xffff) { count = 12; bits = 0xe0; } else if (code <= 0x1fffff) { count = 18; bits = 0xf0; } buffer[j++] = bits | (code >> count); count -= 6; while (count >= 0) { buffer[j++] = 0x80 | ((code >> count) & 0x3f); count -= 6; } i += code >= 0x10000 ? 2 : 1; } return len }; } var utf8 = { byteLength: byteLength$1, toString: toString$1, write: write$2 }; function byteLength (string) { return string.length * 2 } function toString (buffer) { const len = buffer.byteLength; let result = ''; for (let i = 0; i < len - 1; i += 2) { result += String.fromCharCode(buffer[i] + (buffer[i + 1] * 256)); } return result } function write$1 (buffer, string, offset = 0, length = byteLength(string)) { const len = Math.min(length, buffer.byteLength - offset); let units = len; for (let i = 0; i < string.length; ++i) { if ((units -= 2) < 0) break const c = string.charCodeAt(i); const hi = c >> 8; const lo = c % 256; buffer[offset + i * 2] = lo; buffer[offset + i * 2 + 1] = hi; } return len } var utf16le = { byteLength, toString, write: write$1 }; (function (module, exports) { const ascii$1 = ascii; const base64$1 = base64; const hex$1 = hex; const utf8$1 = utf8; const utf16le$1 = utf16le; const LE = new Uint8Array(Uint16Array.of(0xff).buffer)[0] === 0xff; function codecFor (encoding) { switch (encoding) { case 'ascii': return ascii$1 case 'base64': return base64$1 case 'hex': return hex$1 case 'utf8': case 'utf-8': case undefined: return utf8$1 case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16le$1 default: throw new Error(`Unknown encoding: ${encoding}`) } } function isBuffer (value) { return value instanceof Uint8Array } function isEncoding (encoding) { try { codecFor(encoding); return true } catch { return false } } function alloc (size, fill, encoding) { const buffer = new Uint8Array(size); if (fill !== undefined) exports.fill(buffer, fill, 0, buffer.byteLength, encoding); return buffer } function allocUnsafe (size) { return new Uint8Array(size) } function allocUnsafeSlow (size) { return new Uint8Array(size) } function byteLength (string, encoding) { return codecFor(encoding).byteLength(string) } function compare (a, b) { if (a === b) return 0 const len = Math.min(a.byteLength, b.byteLength); a = new DataView(a.buffer, a.byteOffset, a.byteLength); b = new DataView(b.buffer, b.byteOffset, b.byteLength); let i = 0; for (let n = len - (len % 4); i < n; i += 4) { const x = a.getUint32(i, LE); const y = b.getUint32(i, LE); if (x !== y) break } for (; i < len; i++) { const x = a.getUint8(i); const y = b.getUint8(i); if (x < y) return -1 if (x > y) return 1 } return a.byteLength > b.byteLength ? 1 : a.byteLength < b.byteLength ? -1 : 0 } function concat (buffers, totalLength) { if (totalLength === undefined) { totalLength = buffers.reduce((len, buffer) => len + buffer.byteLength, 0); } const result = new Uint8Array(totalLength); let offset = 0; for (const buffer of buffers) { if (offset + buffer.byteLength > result.byteLength) { const sub = buffer.subarray(0, result.byteLength - offset); result.set(sub, offset); return result } result.set(buffer, offset); offset += buffer.byteLength; } return result } function copy (source, target, targetStart = 0, start = 0, end = source.byteLength) { if (end > 0 && end < start) return 0 if (end === start) return 0 if (source.byteLength === 0 || target.byteLength === 0) return 0 if (targetStart < 0) throw new RangeError('targetStart is out of range') if (start < 0 || start >= source.byteLength) throw new RangeError('sourceStart is out of range') if (end < 0) throw new RangeError('sourceEnd is out of range') if (targetStart >= target.byteLength) targetStart = target.byteLength; if (end > source.byteLength) end = source.byteLength; if (target.byteLength - targetStart < end - start) { end = target.length - targetStart + start; } const len = end - start; if (source === target) { target.copyWithin(targetStart, start, end); } else { target.set(source.subarray(start, end), targetStart); } return len } function equals (a, b) { if (a === b) return true if (a.byteLength !== b.byteLength) return false const len = a.byteLength; a = new DataView(a.buffer, a.byteOffset, a.byteLength); b = new DataView(b.buffer, b.byteOffset, b.byteLength); let i = 0; for (let n = len - (len % 4); i < n; i += 4) { if (a.getUint32(i, LE) !== b.getUint32(i, LE)) return false } for (; i < len; i++) { if (a.getUint8(i) !== b.getUint8(i)) return false } return true } function fill (buffer, value, offset, end, encoding) { if (typeof value === 'string') { // fill(buffer, string, encoding) if (typeof offset === 'string') { encoding = offset; offset = 0; end = buffer.byteLength; // fill(buffer, string, offset, encoding) } else if (typeof end === 'string') { encoding = end; end = buffer.byteLength; } } else if (typeof value === 'number') { value = value & 0xff; } else if (typeof value === 'boolean') { value = +value; } if (offset < 0 || buffer.byteLength < offset || buffer.byteLength < end) { throw new RangeError('Out of range index') } if (offset === undefined) offset = 0; if (end === undefined) end = buffer.byteLength; if (end <= offset) return buffer if (!value) value = 0; if (typeof value === 'number') { for (let i = offset; i < end; ++i) { buffer[i] = value; } } else { value = isBuffer(value) ? value : from(value, encoding); const len = value.byteLength; for (let i = 0; i < end - offset; ++i) { buffer[i + offset] = value[i % len]; } } return buffer } function from (value, encodingOrOffset, length) { // from(string, encoding) if (typeof value === 'string') return fromString(value, encodingOrOffset) // from(array) if (Array.isArray(value)) return fromArray(value) // from(buffer) if (ArrayBuffer.isView(value)) return fromBuffer(value) // from(arrayBuffer[, byteOffset[, length]]) return fromArrayBuffer(value, encodingOrOffset, length) } function fromString (string, encoding) { const codec = codecFor(encoding); const buffer = new Uint8Array(codec.byteLength(string)); codec.write(buffer, string, 0, buffer.byteLength); return buffer } function fromArray (array) { const buffer = new Uint8Array(array.length); buffer.set(array); return buffer } function fromBuffer (buffer) { const copy = new Uint8Array(buffer.byteLength); copy.set(buffer); return copy } function fromArrayBuffer (arrayBuffer, byteOffset, length) { return new Uint8Array(arrayBuffer, byteOffset, length) } function includes (buffer, value, byteOffset, encoding) { return indexOf(buffer, value, byteOffset, encoding) !== -1 } function bidirectionalIndexOf (buffer, value, byteOffset, encoding, first) { if (buffer.byteLength === 0) return -1 if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset === undefined) { byteOffset = first ? 0 : (buffer.length - 1); } else if (byteOffset < 0) { byteOffset += buffer.byteLength; } if (byteOffset >= buffer.byteLength) { if (first) return -1 else byteOffset = buffer.byteLength - 1; } else if (byteOffset < 0) { if (first) byteOffset = 0; else return -1 } if (typeof value === 'string') { value = from(value, encoding); } else if (typeof value === 'number') { value = value & 0xff; if (first) { return buffer.indexOf(value, byteOffset) } else { return buffer.lastIndexOf(value, byteOffset) } } if (value.byteLength === 0) return -1 if (first) { let foundIndex = -1; for (let i = byteOffset; i < buffer.byteLength; i++) { if (buffer[i] === value[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === value.byteLength) return foundIndex } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valu