Use merkle tree from npm & remove ./lib

Reference: 0c6e638852

- fixed yarn installation bug as well
This commit is contained in:
Ayanami 2022-02-27 07:32:24 +09:00
parent 863474c203
commit d55ca374e4
No known key found for this signature in database
GPG Key ID: 0CABDF03077D92E4
22 changed files with 697 additions and 262 deletions

13
cli.js
View File

@ -9,7 +9,7 @@ const snarkjs = require('snarkjs')
const crypto = require('crypto')
const circomlib = require('circomlib')
const bigInt = snarkjs.bigInt
const merkleTree = require('./lib/MerkleTree')
const merkleTree = require('fixed-merkle-tree')
const Web3 = require('web3')
const Web3HttpProvider = require('web3-providers-http');
const buildGroth16 = require('websnark/src/groth16')
@ -232,7 +232,7 @@ async function generateMerkleProof(deposit, currency, amount) {
const tree = new merkleTree(MERKLE_TREE_HEIGHT, leaves)
// Validate that our data is correct
const root = await tree.root()
const root = tree.root()
const isValidRoot = await tornadoContract.methods.isKnownRoot(toHex(root)).call()
const isSpent = await tornadoContract.methods.isSpent(toHex(deposit.nullifierHash)).call()
assert(isValidRoot === true, 'Merkle tree is corrupted')
@ -240,7 +240,8 @@ async function generateMerkleProof(deposit, currency, amount) {
assert(leafIndex >= 0, 'The deposit is not found in the tree')
// Compute merkle proof of our commitment
return tree.path(leafIndex)
const { pathElements, pathIndices } = tree.path(leafIndex)
return { root, pathElements, pathIndices }
}
/**
@ -253,7 +254,7 @@ async function generateMerkleProof(deposit, currency, amount) {
*/
async function generateProof({ deposit, currency, amount, recipient, relayerAddress = 0, fee = 0, refund = 0 }) {
// Compute merkle proof of our commitment
const { root, path_elements, path_index } = await generateMerkleProof(deposit, currency, amount)
const { root, pathElements, pathIndices } = await generateMerkleProof(deposit, currency, amount)
// Prepare circuit input
const input = {
@ -268,8 +269,8 @@ async function generateProof({ deposit, currency, amount, recipient, relayerAddr
// Private snark inputs
nullifier: deposit.nullifier,
secret: deposit.secret,
pathElements: path_elements,
pathIndices: path_index
pathElements: pathElements,
pathIndices: pathIndices
}
console.log('Generating SNARK proof')

View File

@ -1,195 +0,0 @@
const jsStorage = require('./Storage')
const hasherImpl = require('./MiMC')
class MerkleTree {
constructor(n_levels, defaultElements, prefix, storage, hasher) {
this.prefix = prefix
this.storage = storage || new jsStorage()
this.hasher = hasher || new hasherImpl()
this.n_levels = n_levels
this.zero_values = []
this.totalElements = 0
let current_zero_value = '21663839004416932945382355908790599225266501822907911457504978515578255421292'
this.zero_values.push(current_zero_value)
for (let i = 0; i < n_levels; i++) {
current_zero_value = this.hasher.hash(i, current_zero_value, current_zero_value)
this.zero_values.push(
current_zero_value.toString(),
)
}
if (defaultElements) {
let level = 0
this.totalElements = defaultElements.length
defaultElements.forEach((element, i) => {
this.storage.put(MerkleTree.index_to_key(prefix, level, i), element)
})
level++
let numberOfElementsInLevel = Math.ceil(defaultElements.length / 2)
for (level; level <= this.n_levels; level++) {
for(let i = 0; i < numberOfElementsInLevel; i++) {
const leftKey = MerkleTree.index_to_key(prefix, level - 1, 2 * i)
const rightKey = MerkleTree.index_to_key(prefix, level - 1, 2 * i + 1)
const left = this.storage.get(leftKey)
const right = this.storage.get_or_element(rightKey, this.zero_values[level - 1])
const subRoot = this.hasher.hash(null, left, right)
this.storage.put(MerkleTree.index_to_key(prefix, level, i), subRoot)
}
numberOfElementsInLevel = Math.ceil(numberOfElementsInLevel / 2)
}
}
}
static index_to_key(prefix, level, index) {
const key = `${prefix}_tree_${level}_${index}`
return key
}
async root() {
let root = await this.storage.get_or_element(
MerkleTree.index_to_key(this.prefix, this.n_levels, 0),
this.zero_values[this.n_levels],
)
return root
}
async path(index) {
class PathTraverser {
constructor(prefix, storage, zero_values) {
this.prefix = prefix
this.storage = storage
this.zero_values = zero_values
this.path_elements = []
this.path_index = []
}
async handle_index(level, element_index, sibling_index) {
const sibling = await this.storage.get_or_element(
MerkleTree.index_to_key(this.prefix, level, sibling_index),
this.zero_values[level],
)
this.path_elements.push(sibling)
this.path_index.push(element_index % 2)
}
}
index = Number(index)
let traverser = new PathTraverser(this.prefix, this.storage, this.zero_values)
const root = await this.storage.get_or_element(
MerkleTree.index_to_key(this.prefix, this.n_levels, 0),
this.zero_values[this.n_levels],
)
const element = await this.storage.get_or_element(
MerkleTree.index_to_key(this.prefix, 0, index),
this.zero_values[0],
)
await this.traverse(index, traverser)
return {
root,
path_elements: traverser.path_elements,
path_index: traverser.path_index,
element
}
}
async update(index, element, insert = false) {
if (!insert && index >= this.totalElements) {
throw Error('Use insert method for new elements.')
} else if(insert && index < this.totalElements) {
throw Error('Use update method for existing elements.')
}
try {
class UpdateTraverser {
constructor(prefix, storage, hasher, element, zero_values) {
this.prefix = prefix
this.current_element = element
this.zero_values = zero_values
this.storage = storage
this.hasher = hasher
this.key_values_to_put = []
}
async handle_index(level, element_index, sibling_index) {
if (level == 0) {
this.original_element = await this.storage.get_or_element(
MerkleTree.index_to_key(this.prefix, level, element_index),
this.zero_values[level],
)
}
const sibling = await this.storage.get_or_element(
MerkleTree.index_to_key(this.prefix, level, sibling_index),
this.zero_values[level],
)
let left, right
if (element_index % 2 == 0) {
left = this.current_element
right = sibling
} else {
left = sibling
right = this.current_element
}
this.key_values_to_put.push({
key: MerkleTree.index_to_key(this.prefix, level, element_index),
value: this.current_element,
})
this.current_element = this.hasher.hash(level, left, right)
}
}
let traverser = new UpdateTraverser(
this.prefix,
this.storage,
this.hasher,
element,
this.zero_values
)
await this.traverse(index, traverser)
traverser.key_values_to_put.push({
key: MerkleTree.index_to_key(this.prefix, this.n_levels, 0),
value: traverser.current_element,
})
await this.storage.put_batch(traverser.key_values_to_put)
} catch(e) {
console.error(e)
}
}
async insert(element) {
const index = this.totalElements
await this.update(index, element, true)
this.totalElements++
}
async traverse(index, handler) {
let current_index = index
for (let i = 0; i < this.n_levels; i++) {
let sibling_index = current_index
if (current_index % 2 == 0) {
sibling_index += 1
} else {
sibling_index -= 1
}
await handler.handle_index(i, current_index, sibling_index)
current_index = Math.floor(current_index / 2)
}
}
getIndexByElement(element) {
for(let i = this.totalElements - 1; i >= 0; i--) {
const elementFromTree = this.storage.get(MerkleTree.index_to_key(this.prefix, 0, i))
if (elementFromTree === element) {
return i
}
}
return false
}
}
module.exports = MerkleTree

View File

@ -1,13 +0,0 @@
const circomlib = require('circomlib')
const mimcsponge = circomlib.mimcsponge
const snarkjs = require('snarkjs')
const bigInt = snarkjs.bigInt
class MimcSpongeHasher {
hash(level, left, right) {
return mimcsponge.multiHash([bigInt(left), bigInt(right)]).toString()
}
}
module.exports = MimcSpongeHasher

View File

@ -1,39 +0,0 @@
class JsStorage {
constructor() {
this.db = {}
}
get(key) {
return this.db[key]
}
get_or_element(key, defaultElement) {
const element = this.db[key]
if (element === undefined) {
return defaultElement
} else {
return element
}
}
put(key, value) {
if (key === undefined || value === undefined) {
throw Error('key or value is undefined')
}
this.db[key] = value
}
del(key) {
delete this.db[key]
}
put_batch(key_values) {
key_values.forEach(element => {
this.db[element.key] = element.value
})
}
}
module.exports = JsStorage

View File

@ -1,6 +1,4 @@
node_modules
yarn-error.log
.idea
**/*.js
**/*.js.map
!wallaby.js

View File

@ -0,0 +1,45 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var SecurityError = /** @class */ (function (_super) {
__extends(SecurityError, _super);
function SecurityError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return SecurityError;
}(Error));
exports.SecurityError = SecurityError;
var InvalidStateError = /** @class */ (function (_super) {
__extends(InvalidStateError, _super);
function InvalidStateError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return InvalidStateError;
}(Error));
exports.InvalidStateError = InvalidStateError;
var NetworkError = /** @class */ (function (_super) {
__extends(NetworkError, _super);
function NetworkError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return NetworkError;
}(Error));
exports.NetworkError = NetworkError;
var SyntaxError = /** @class */ (function (_super) {
__extends(SyntaxError, _super);
function SyntaxError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return SyntaxError;
}(Error));
exports.SyntaxError = SyntaxError;
//# sourceMappingURL=errors.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../errors.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;IAAmC,iCAAK;IAAxC;;IAA0C,CAAC;IAAD,oBAAC;AAAD,CAAC,AAA3C,CAAmC,KAAK,GAAG;AAA9B,sCAAa;AAC1B;IAAuC,qCAAK;IAA5C;;IAA8C,CAAC;IAAD,wBAAC;AAAD,CAAC,AAA/C,CAAuC,KAAK,GAAG;AAAlC,8CAAiB;AAC9B;IAAkC,gCAAK;IAAvC;;IAAyC,CAAC;IAAD,mBAAC;AAAD,CAAC,AAA1C,CAAkC,KAAK,GAAG;AAA7B,oCAAY;AACzB;IAAiC,+BAAK;IAAtC;;IAAwC,CAAC;IAAD,kBAAC;AAAD,CAAC,AAAzC,CAAiC,KAAK,GAAG;AAA5B,kCAAW"}

View File

@ -0,0 +1,9 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./xml-http-request"));
var xml_http_request_event_target_1 = require("./xml-http-request-event-target");
exports.XMLHttpRequestEventTarget = xml_http_request_event_target_1.XMLHttpRequestEventTarget;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;AAAA,wCAAmC;AACnC,iFAA4E;AAAnE,oEAAA,yBAAyB,CAAA"}

View File

@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ProgressEvent = /** @class */ (function () {
function ProgressEvent(type) {
this.type = type;
this.bubbles = false;
this.cancelable = false;
this.loaded = 0;
this.lengthComputable = false;
this.total = 0;
}
return ProgressEvent;
}());
exports.ProgressEvent = ProgressEvent;
//# sourceMappingURL=progress-event.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"progress-event.js","sourceRoot":"","sources":["../progress-event.ts"],"names":[],"mappings":";;AAEA;IAQC,uBAAoB,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;QAPhC,YAAO,GAAG,KAAK,CAAC;QAChB,eAAU,GAAG,KAAK,CAAC;QAEnB,WAAM,GAAG,CAAC,CAAC;QACX,qBAAgB,GAAG,KAAK,CAAC;QACzB,UAAK,GAAG,CAAC,CAAC;IAEyB,CAAC;IACrC,oBAAC;AAAD,CAAC,AATD,IASC;AATY,sCAAa"}

View File

@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var XMLHttpRequestEventTarget = /** @class */ (function () {
function XMLHttpRequestEventTarget() {
this.listeners = {};
}
XMLHttpRequestEventTarget.prototype.addEventListener = function (eventType, listener) {
eventType = eventType.toLowerCase();
this.listeners[eventType] = this.listeners[eventType] || [];
this.listeners[eventType].push(listener.handleEvent || listener);
};
XMLHttpRequestEventTarget.prototype.removeEventListener = function (eventType, listener) {
eventType = eventType.toLowerCase();
if (!this.listeners[eventType]) {
return;
}
var index = this.listeners[eventType].indexOf(listener.handleEvent || listener);
if (index < 0) {
return;
}
this.listeners[eventType].splice(index, 1);
};
XMLHttpRequestEventTarget.prototype.dispatchEvent = function (event) {
var eventType = event.type.toLowerCase();
event.target = this; // TODO: set event.currentTarget?
if (this.listeners[eventType]) {
for (var _i = 0, _a = this.listeners[eventType]; _i < _a.length; _i++) {
var listener_1 = _a[_i];
listener_1.call(this, event);
}
}
var listener = this["on" + eventType];
if (listener) {
listener.call(this, event);
}
return true;
};
return XMLHttpRequestEventTarget;
}());
exports.XMLHttpRequestEventTarget = XMLHttpRequestEventTarget;
//# sourceMappingURL=xml-http-request-event-target.js.map

View File

@ -0,0 +1 @@
{"version":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C,CAAiB,UAAyB,EAAzB,KAAA,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAzB,cAAyB,EAAzB,IAAyB;gBAAzC,IAAI,UAAQ,SAAA;gBAChB,UAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;aAC3B;QACF,CAAC;QAED,IAAM,QAAQ,GAAG,IAAI,CAAC,OAAK,SAAW,CAAC,CAAC;QACxC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;YACd,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC5B,CAAC;QAED,MAAM,CAAC,IAAI,CAAC;IACb,CAAC;IACF,gCAAC;AAAD,CAAC,AA1CD,IA0CC;AA1CY,8DAAyB"}

View File

@ -0,0 +1,78 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var xml_http_request_event_target_1 = require("./xml-http-request-event-target");
var XMLHttpRequestUpload = /** @class */ (function (_super) {
__extends(XMLHttpRequestUpload, _super);
function XMLHttpRequestUpload() {
var _this = _super.call(this) || this;
_this._contentType = null;
_this._body = null;
_this._reset();
return _this;
}
XMLHttpRequestUpload.prototype._reset = function () {
this._contentType = null;
this._body = null;
};
XMLHttpRequestUpload.prototype._setData = function (data) {
if (data == null) {
return;
}
if (typeof data === 'string') {
if (data.length !== 0) {
this._contentType = 'text/plain;charset=UTF-8';
}
this._body = Buffer.from(data, 'utf-8');
}
else if (Buffer.isBuffer(data)) {
this._body = data;
}
else if (data instanceof ArrayBuffer) {
var body = Buffer.alloc(data.byteLength);
var view = new Uint8Array(data);
for (var i = 0; i < data.byteLength; i++) {
body[i] = view[i];
}
this._body = body;
}
else if (data.buffer && data.buffer instanceof ArrayBuffer) {
var body = Buffer.alloc(data.byteLength);
var offset = data.byteOffset;
var view = new Uint8Array(data.buffer);
for (var i = 0; i < data.byteLength; i++) {
body[i] = view[i + offset];
}
this._body = body;
}
else {
throw new Error("Unsupported send() data " + data);
}
};
XMLHttpRequestUpload.prototype._finalizeHeaders = function (headers, loweredHeaders) {
if (this._contentType && !loweredHeaders['content-type']) {
headers['Content-Type'] = this._contentType;
}
if (this._body) {
headers['Content-Length'] = this._body.length.toString();
}
};
XMLHttpRequestUpload.prototype._startUpload = function (request) {
if (this._body) {
request.write(this._body);
}
request.end();
};
return XMLHttpRequestUpload;
}(xml_http_request_event_target_1.XMLHttpRequestEventTarget));
exports.XMLHttpRequestUpload = XMLHttpRequestUpload;
//# sourceMappingURL=xml-http-request-upload.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"xml-http-request-upload.js","sourceRoot":"","sources":["../xml-http-request-upload.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iFAA4E;AAG5E;IAA0C,wCAAyB;IAIlE;QAAA,YACC,iBAAO,SAEP;QANO,kBAAY,GAAkB,IAAI,CAAC;QACnC,WAAK,GAAG,IAAI,CAAC;QAIpB,KAAI,CAAC,MAAM,EAAE,CAAC;;IACf,CAAC;IAED,qCAAM,GAAN;QACC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,uCAAQ,GAAR,UAAS,IAAsD;QAC9D,EAAE,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC;YAAC,MAAM,CAAC;QAAC,CAAC;QAE7B,EAAE,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC;YAC9B,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC;gBACvB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GAAG,MAAM,CAAC,CAAC;YAAC,CAAC;YACzE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACnB,CAAC;QAAC,IAAI,CAAC,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,6BAA2B,IAAM,CAAC,CAAC;QACpD,CAAC;IACF,CAAC;IAED,+CAAgB,GAAhB,UAAiB,OAAe,EAAE,cAAsB;QACvD,EAAE,CAAC,CAAC,IAAI,CAAC,YAAY,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;YAC1D,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC,YAAY,CAAC;QAC7C,CAAC;QACD,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;YAChB,OAAO,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QAC1D,CAAC;IACF,CAAC;IAED,2CAAY,GAAZ,UAAa,OAAsB;QAClC,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;YAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAAC,CAAC;QAC9C,OAAO,CAAC,GAAG,EAAE,CAAC;IACf,CAAC;IACF,2BAAC;AAAD,CAAC,AArDD,CAA0C,yDAAyB,GAqDlE;AArDY,oDAAoB"}

View File

@ -0,0 +1,448 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var http = require("http");
var https = require("https");
var url = require("url");
var progress_event_1 = require("./progress-event");
var errors_1 = require("./errors");
var xml_http_request_event_target_1 = require("./xml-http-request-event-target");
var xml_http_request_upload_1 = require("./xml-http-request-upload");
var Cookie = require("cookiejar");
var XMLHttpRequest = /** @class */ (function (_super) {
__extends(XMLHttpRequest, _super);
function XMLHttpRequest(options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this) || this;
_this.UNSENT = XMLHttpRequest.UNSENT;
_this.OPENED = XMLHttpRequest.OPENED;
_this.HEADERS_RECEIVED = XMLHttpRequest.HEADERS_RECEIVED;
_this.LOADING = XMLHttpRequest.LOADING;
_this.DONE = XMLHttpRequest.DONE;
_this.onreadystatechange = null;
_this.readyState = XMLHttpRequest.UNSENT;
_this.response = null;
_this.responseText = '';
_this.responseType = '';
_this.status = 0; // TODO: UNSENT?
_this.statusText = '';
_this.timeout = 0;
_this.upload = new xml_http_request_upload_1.XMLHttpRequestUpload();
_this.responseUrl = '';
_this.withCredentials = false;
_this._method = null;
_this._url = null;
_this._sync = false;
_this._headers = {};
_this._loweredHeaders = {};
_this._mimeOverride = null; // TODO: is type right?
_this._request = null;
_this._response = null;
_this._responseParts = null;
_this._responseHeaders = null;
_this._aborting = null; // TODO: type?
_this._error = null; // TODO: type?
_this._loadedBytes = 0;
_this._totalBytes = 0;
_this._lengthComputable = false;
_this._restrictedMethods = { CONNECT: true, TRACE: true, TRACK: true };
_this._restrictedHeaders = {
'accept-charset': true,
'accept-encoding': true,
'access-control-request-headers': true,
'access-control-request-method': true,
connection: true,
'content-length': true,
cookie: true,
cookie2: true,
date: true,
dnt: true,
expect: true,
host: true,
'keep-alive': true,
origin: true,
referer: true,
te: true,
trailer: true,
'transfer-encoding': true,
upgrade: true,
'user-agent': true,
via: true
};
_this._privateHeaders = { 'set-cookie': true, 'set-cookie2': true };
//Redacted private information (${os.type()} ${os.arch()}) node.js/${process.versions.node} v8/${process.versions.v8} from the original version @ github
//Pretend to be tor-browser https://blog.torproject.org/browser-fingerprinting-introduction-and-challenges-ahead/
_this._userAgent = "Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0";
_this._anonymous = options.anon || false;
return _this;
}
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
if (async === void 0) { async = true; }
method = method.toUpperCase();
if (this._restrictedMethods[method]) {
throw new XMLHttpRequest.SecurityError("HTTP method " + method + " is not allowed in XHR");
}
;
var xhrUrl = this._parseUrl(url, user, password);
if (this.readyState === XMLHttpRequest.HEADERS_RECEIVED || this.readyState === XMLHttpRequest.LOADING) {
// TODO(pwnall): terminate abort(), terminate send()
}
this._method = method;
this._url = xhrUrl;
this._sync = !async;
this._headers = {};
this._loweredHeaders = {};
this._mimeOverride = null;
this._setReadyState(XMLHttpRequest.OPENED);
this._request = null;
this._response = null;
this.status = 0;
this.statusText = '';
this._responseParts = [];
this._responseHeaders = null;
this._loadedBytes = 0;
this._totalBytes = 0;
this._lengthComputable = false;
};
XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
if (this.readyState !== XMLHttpRequest.OPENED) {
throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED');
}
var loweredName = name.toLowerCase();
if (this._restrictedHeaders[loweredName] || /^sec-/.test(loweredName) || /^proxy-/.test(loweredName)) {
console.warn("Refused to set unsafe header \"" + name + "\"");
return;
}
value = value.toString();
if (this._loweredHeaders[loweredName] != null) {
name = this._loweredHeaders[loweredName];
this._headers[name] = this._headers[name] + ", " + value;
}
else {
this._loweredHeaders[loweredName] = name;
this._headers[name] = value;
}
};
XMLHttpRequest.prototype.send = function (data) {
if (this.readyState !== XMLHttpRequest.OPENED) {
throw new XMLHttpRequest.InvalidStateError('XHR readyState must be OPENED');
}
if (this._request) {
throw new XMLHttpRequest.InvalidStateError('send() already called');
}
switch (this._url.protocol) {
case 'file:':
return this._sendFile(data);
case 'http:':
case 'https:':
return this._sendHttp(data);
default:
throw new XMLHttpRequest.NetworkError("Unsupported protocol " + this._url.protocol);
}
};
XMLHttpRequest.prototype.abort = function () {
if (this._request == null) {
return;
}
this._request.abort();
this._setError();
this._dispatchProgress('abort');
this._dispatchProgress('loadend');
};
XMLHttpRequest.prototype.getResponseHeader = function (name) {
if (this._responseHeaders == null || name == null) {
return null;
}
var loweredName = name.toLowerCase();
return this._responseHeaders.hasOwnProperty(loweredName)
? this._responseHeaders[name.toLowerCase()]
: null;
};
XMLHttpRequest.prototype.getAllResponseHeaders = function () {
var _this = this;
if (this._responseHeaders == null) {
return '';
}
return Object.keys(this._responseHeaders).map(function (key) { return key + ": " + _this._responseHeaders[key]; }).join('\r\n');
};
XMLHttpRequest.prototype.overrideMimeType = function (mimeType) {
if (this.readyState === XMLHttpRequest.LOADING || this.readyState === XMLHttpRequest.DONE) {
throw new XMLHttpRequest.InvalidStateError('overrideMimeType() not allowed in LOADING or DONE');
}
this._mimeOverride = mimeType.toLowerCase();
};
XMLHttpRequest.prototype.nodejsSet = function (options) {
this.nodejsHttpAgent = options.httpAgent || this.nodejsHttpAgent;
this.nodejsHttpsAgent = options.httpsAgent || this.nodejsHttpsAgent;
if (options.hasOwnProperty('baseUrl')) {
if (options.baseUrl != null) {
var parsedUrl = url.parse(options.baseUrl, false, true);
if (!parsedUrl.protocol) {
throw new XMLHttpRequest.SyntaxError("baseUrl must be an absolute URL");
}
}
this.nodejsBaseUrl = options.baseUrl;
}
};
XMLHttpRequest.nodejsSet = function (options) {
XMLHttpRequest.prototype.nodejsSet(options);
};
XMLHttpRequest.prototype._setReadyState = function (readyState) {
this.readyState = readyState;
this.dispatchEvent(new progress_event_1.ProgressEvent('readystatechange'));
};
XMLHttpRequest.prototype._sendFile = function (data) {
// TODO
throw new Error('Protocol file: not implemented');
};
XMLHttpRequest.prototype._sendHttp = function (data) {
if (this._sync) {
throw new Error('Synchronous XHR processing not implemented');
}
if (data && (this._method === 'GET' || this._method === 'HEAD')) {
console.warn("Discarding entity body for " + this._method + " requests");
data = null;
}
else {
data = data || '';
}
this.upload._setData(data);
this._finalizeHeaders();
this._sendHxxpRequest();
};
XMLHttpRequest.prototype._sendHxxpRequest = function () {
var _this = this;
if (this.withCredentials) {
var cookie = XMLHttpRequest.cookieJar
.getCookies(Cookie.CookieAccessInfo(this._url.hostname, this._url.pathname, this._url.protocol === 'https:')).toValueString();
this._headers.cookie = this._headers.cookie2 = cookie;
}
var _a = this._url.protocol === 'http:' ? [http, this.nodejsHttpAgent] : [https, this.nodejsHttpsAgent], hxxp = _a[0], agent = _a[1];
var requestMethod = hxxp.request.bind(hxxp);
var request = requestMethod({
hostname: this._url.hostname,
port: +this._url.port,
path: this._url.path,
auth: this._url.auth,
method: this._method,
headers: this._headers,
agent: agent
});
this._request = request;
if (this.timeout) {
request.setTimeout(this.timeout, function () { return _this._onHttpTimeout(request); });
}
request.on('response', function (response) { return _this._onHttpResponse(request, response); });
request.on('error', function (error) { return _this._onHttpRequestError(request, error); });
this.upload._startUpload(request);
if (this._request === request) {
this._dispatchProgress('loadstart');
}
};
XMLHttpRequest.prototype._finalizeHeaders = function () {
this._headers = __assign({}, this._headers, { Connection: 'keep-alive', Host: this._url.host, 'User-Agent': this._userAgent }, this._anonymous ? { Referer: 'about:blank' } : {});
this.upload._finalizeHeaders(this._headers, this._loweredHeaders);
};
XMLHttpRequest.prototype._onHttpResponse = function (request, response) {
var _this = this;
if (this._request !== request) {
return;
}
if (this.withCredentials && (response.headers['set-cookie'] || response.headers['set-cookie2'])) {
XMLHttpRequest.cookieJar
.setCookies(response.headers['set-cookie'] || response.headers['set-cookie2']);
}
if ([301, 302, 303, 307, 308].indexOf(response.statusCode) >= 0) {
this._url = this._parseUrl(response.headers.location);
this._method = 'GET';
if (this._loweredHeaders['content-type']) {
delete this._headers[this._loweredHeaders['content-type']];
delete this._loweredHeaders['content-type'];
}
if (this._headers['Content-Type'] != null) {
delete this._headers['Content-Type'];
}
delete this._headers['Content-Length'];
this.upload._reset();
this._finalizeHeaders();
this._sendHxxpRequest();
return;
}
this._response = response;
this._response.on('data', function (data) { return _this._onHttpResponseData(response, data); });
this._response.on('end', function () { return _this._onHttpResponseEnd(response); });
this._response.on('close', function () { return _this._onHttpResponseClose(response); });
this.responseUrl = this._url.href.split('#')[0];
this.status = response.statusCode;
this.statusText = http.STATUS_CODES[this.status];
this._parseResponseHeaders(response);
var lengthString = this._responseHeaders['content-length'] || '';
this._totalBytes = +lengthString;
this._lengthComputable = !!lengthString;
this._setReadyState(XMLHttpRequest.HEADERS_RECEIVED);
};
XMLHttpRequest.prototype._onHttpResponseData = function (response, data) {
if (this._response !== response) {
return;
}
this._responseParts.push(Buffer.from(data));
this._loadedBytes += data.length;
if (this.readyState !== XMLHttpRequest.LOADING) {
this._setReadyState(XMLHttpRequest.LOADING);
}
this._dispatchProgress('progress');
};
XMLHttpRequest.prototype._onHttpResponseEnd = function (response) {
if (this._response !== response) {
return;
}
this._parseResponse();
this._request = null;
this._response = null;
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('load');
this._dispatchProgress('loadend');
};
XMLHttpRequest.prototype._onHttpResponseClose = function (response) {
if (this._response !== response) {
return;
}
var request = this._request;
this._setError();
request.abort();
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('error');
this._dispatchProgress('loadend');
};
XMLHttpRequest.prototype._onHttpTimeout = function (request) {
if (this._request !== request) {
return;
}
this._setError();
request.abort();
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('timeout');
this._dispatchProgress('loadend');
};
XMLHttpRequest.prototype._onHttpRequestError = function (request, error) {
if (this._request !== request) {
return;
}
this._setError();
request.abort();
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('error');
this._dispatchProgress('loadend');
};
XMLHttpRequest.prototype._dispatchProgress = function (eventType) {
var event = new XMLHttpRequest.ProgressEvent(eventType);
event.lengthComputable = this._lengthComputable;
event.loaded = this._loadedBytes;
event.total = this._totalBytes;
this.dispatchEvent(event);
};
XMLHttpRequest.prototype._setError = function () {
this._request = null;
this._response = null;
this._responseHeaders = null;
this._responseParts = null;
};
XMLHttpRequest.prototype._parseUrl = function (urlString, user, password) {
var absoluteUrl = this.nodejsBaseUrl == null ? urlString : url.resolve(this.nodejsBaseUrl, urlString);
var xhrUrl = url.parse(absoluteUrl, false, true);
xhrUrl.hash = null;
var _a = (xhrUrl.auth || '').split(':'), xhrUser = _a[0], xhrPassword = _a[1];
if (xhrUser || xhrPassword || user || password) {
xhrUrl.auth = (user || xhrUser || '') + ":" + (password || xhrPassword || '');
}
return xhrUrl;
};
XMLHttpRequest.prototype._parseResponseHeaders = function (response) {
this._responseHeaders = {};
for (var name_1 in response.headers) {
var loweredName = name_1.toLowerCase();
if (this._privateHeaders[loweredName]) {
continue;
}
this._responseHeaders[loweredName] = response.headers[name_1];
}
if (this._mimeOverride != null) {
this._responseHeaders['content-type'] = this._mimeOverride;
}
};
XMLHttpRequest.prototype._parseResponse = function () {
var buffer = Buffer.concat(this._responseParts);
this._responseParts = null;
switch (this.responseType) {
case 'json':
this.responseText = null;
try {
this.response = JSON.parse(buffer.toString('utf-8'));
}
catch (_a) {
this.response = null;
}
return;
case 'buffer':
this.responseText = null;
this.response = buffer;
return;
case 'arraybuffer':
this.responseText = null;
var arrayBuffer = new ArrayBuffer(buffer.length);
var view = new Uint8Array(arrayBuffer);
for (var i = 0; i < buffer.length; i++) {
view[i] = buffer[i];
}
this.response = arrayBuffer;
return;
case 'text':
default:
try {
this.responseText = buffer.toString(this._parseResponseEncoding());
}
catch (_b) {
this.responseText = buffer.toString('binary');
}
this.response = this.responseText;
}
};
XMLHttpRequest.prototype._parseResponseEncoding = function () {
return /;\s*charset=(.*)$/.exec(this._responseHeaders['content-type'] || '')[1] || 'utf-8';
};
XMLHttpRequest.ProgressEvent = progress_event_1.ProgressEvent;
XMLHttpRequest.InvalidStateError = errors_1.InvalidStateError;
XMLHttpRequest.NetworkError = errors_1.NetworkError;
XMLHttpRequest.SecurityError = errors_1.SecurityError;
XMLHttpRequest.SyntaxError = errors_1.SyntaxError;
XMLHttpRequest.XMLHttpRequestUpload = xml_http_request_upload_1.XMLHttpRequestUpload;
XMLHttpRequest.UNSENT = 0;
XMLHttpRequest.OPENED = 1;
XMLHttpRequest.HEADERS_RECEIVED = 2;
XMLHttpRequest.LOADING = 3;
XMLHttpRequest.DONE = 4;
XMLHttpRequest.cookieJar = Cookie.CookieJar();
return XMLHttpRequest;
}(xml_http_request_event_target_1.XMLHttpRequestEventTarget));
exports.XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest.prototype.nodejsHttpAgent = http.globalAgent;
XMLHttpRequest.prototype.nodejsHttpsAgent = https.globalAgent;
XMLHttpRequest.prototype.nodejsBaseUrl = null;
//# sourceMappingURL=xml-http-request.js.map

File diff suppressed because one or more lines are too long

View File

@ -15,7 +15,7 @@
"main": "lib/index.js",
"dependencies": {
"web3-core-helpers": "1.6.1",
"xhr2-cookies": "file:./local_modules/xhr2-cookies"
"xhr2-cookies": "file:local_modules/xhr2-cookies"
},
"devDependencies": {
"dtslint": "^3.4.1",

22
package-lock.json generated
View File

@ -2580,6 +2580,28 @@
"locate-path": "^3.0.0"
}
},
"fixed-merkle-tree": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/fixed-merkle-tree/-/fixed-merkle-tree-0.6.1.tgz",
"integrity": "sha512-cYwK8ZJRC/qlRwB6f1WDbqDi3SLSraFr9LQp948U3LmHZpF0VnuB0QOsLhMVwOpR1eJ178oiqz0JcwaupRU9kA==",
"requires": {
"circomlib": "git+https://github.com/tornadocash/circomlib.git#5beb6aee94923052faeecea40135d45b6ce6172c",
"snarkjs": "git+https://github.com/tornadocash/snarkjs.git#869181cfaf7526fe8972073d31655493a04326d5"
},
"dependencies": {
"circomlib": {
"version": "git+https://github.com/tornadocash/circomlib.git#5beb6aee94923052faeecea40135d45b6ce6172c",
"from": "git+https://github.com/tornadocash/circomlib.git#5beb6aee94923052faeecea40135d45b6ce6172c",
"requires": {
"blake-hash": "^1.1.0",
"blake2b": "^2.1.3",
"snarkjs": "git+https://github.com/tornadocash/snarkjs.git#869181cfaf7526fe8972073d31655493a04326d5",
"typedarray-to-buffer": "^3.1.5",
"web3": "^1.2.11"
}
}
}
},
"flat-cache": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz",

View File

@ -10,16 +10,17 @@
"license": "ISC",
"dependencies": {
"axios": "^0.19.2",
"bignumber.js": "9.0.0",
"bignumber.js": "^9.0.0",
"circom": "0.0.35",
"circomlib": "git+https://github.com/tornadocash/circomlib.git#3b492f9801573eebcfe1b6c584afe8a3beecf2b4",
"commander": "^5.1.0",
"dotenv": "^8.2.0",
"fixed-merkle-tree": "^0.6.1",
"gas-price-oracle": "^0.4.4",
"socks-proxy-agent": "^6.1.1",
"snarkjs": "git+https://github.com/tornadocash/snarkjs.git#869181cfaf7526fe8972073d31655493a04326d5",
"web3": "^1.6.1",
"web3-providers-http": "file:./local_modules/web3-providers-http",
"web3-providers-http": "file:local_modules/web3-providers-http",
"websnark": "git+https://github.com/tornadocash/websnark.git#4c0af6a8b65aabea3c09f377f63c44e7a58afa6d"
},
"devDependencies": {

View File

@ -800,6 +800,16 @@ circom@0.0.35:
typedarray-to-buffer "^3.1.5"
web3 "^1.2.11"
"circomlib@git+https://github.com/tornadocash/circomlib.git#5beb6aee94923052faeecea40135d45b6ce6172c":
version "0.0.20"
resolved "git+https://github.com/tornadocash/circomlib.git#5beb6aee94923052faeecea40135d45b6ce6172c"
dependencies:
blake-hash "^1.1.0"
blake2b "^2.1.3"
snarkjs "git+https://github.com/tornadocash/snarkjs.git#869181cfaf7526fe8972073d31655493a04326d5"
typedarray-to-buffer "^3.1.5"
web3 "^1.2.11"
class-is@^1.1.0:
version "1.1.0"
resolved "https://registry.npmjs.org/class-is/-/class-is-1.1.0.tgz#9d3c0fba0440d211d843cec3dedfa48055005825"
@ -1711,6 +1721,14 @@ find-up@^3.0.0:
dependencies:
locate-path "^3.0.0"
fixed-merkle-tree@^0.6.1:
version "0.6.1"
resolved "https://registry.yarnpkg.com/fixed-merkle-tree/-/fixed-merkle-tree-0.6.1.tgz#ff64bf0beb5d862e73d6c643950926b05b440926"
integrity sha512-cYwK8ZJRC/qlRwB6f1WDbqDi3SLSraFr9LQp948U3LmHZpF0VnuB0QOsLhMVwOpR1eJ178oiqz0JcwaupRU9kA==
dependencies:
circomlib "git+https://github.com/tornadocash/circomlib.git#5beb6aee94923052faeecea40135d45b6ce6172c"
snarkjs "git+https://github.com/tornadocash/snarkjs.git#869181cfaf7526fe8972073d31655493a04326d5"
flat-cache@^2.0.1:
version "2.0.1"
resolved "https://registry.npmjs.org/flat-cache/-/flat-cache-2.0.1.tgz#5d296d6f04bda44a4630a301413bdbc2ec085ec0"
@ -4180,11 +4198,11 @@ web3-providers-http@1.6.1:
web3-core-helpers "1.6.1"
xhr2-cookies "1.1.0"
"web3-providers-http@file:./local_modules/web3-providers-http":
"web3-providers-http@file:local_modules/web3-providers-http":
version "1.6.1"
dependencies:
web3-core-helpers "1.6.1"
xhr2-cookies "file:./../../AppData/Local/Yarn/Cache/v6/npm-web3-providers-http-1.6.1-6879cf8b-ee02-483d-9a46-76314494b334-1638895560210/node_modules/web3-providers-http/local_modules/xhr2-cookies"
xhr2-cookies "file:local_modules/web3-providers-http/local_modules/xhr2-cookies"
web3-providers-ipc@1.3.1:
version "1.3.1"
@ -4411,7 +4429,7 @@ xhr2-cookies@1.1.0:
dependencies:
cookiejar "^2.1.1"
"xhr2-cookies@file:./local_modules/web3-providers-http/local_modules/xhr2-cookies":
"xhr2-cookies@file:local_modules/web3-providers-http/local_modules/xhr2-cookies":
version "1.1.0"
dependencies:
cookiejar "^2.1.1"