Advertisement
Guest User

Untitled

a guest
Jun 15th, 2016
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.43 KB | None | 0 0
  1. importScripts('../../thirdparty.js');
  2. importScripts('../../request.js');
  3.  
  4. //importScripts('../network.js');
  5. importScripts('../../jaxx_main/jaxx_constants.js');
  6. //importScripts('../wallet/hdwallet_helper.js');
  7. importScripts('../../wallet/token/coin_token.js');
  8.  
  9. var doDebug = false;
  10.  
  11. function log() {
  12. if (doDebug === false) {
  13. return;
  14. }
  15.  
  16. var args = [].slice.call(arguments);
  17. args.unshift('WorkerLog:');
  18. console.log(args);
  19. // postMessage({action: 'log', content: args});
  20. }
  21.  
  22. var CoinTokenWorker = function() {
  23. this._tokenName = "";
  24. this._tokenSymbol = "";
  25. this._tokenCoinType = 0;
  26.  
  27. this._receiveNode = null;
  28. this._changeNode = null;
  29.  
  30. this._transactions = {};
  31. this._addressMap = {};
  32. //
  33. // this._lastReceiveIndex = -1;
  34. // this._currentReceiveAddress = null;
  35. //
  36. // this._lastChangeIndex = -1;
  37. // this._currentChangeAddress = null;
  38. //
  39. // this._addressMap = {};
  40. //
  41. // this._transactions = {};
  42. //
  43. // this._watcherQueue = [];
  44. //
  45. // this._usesWSS = false;
  46. // this._watcherWebSocket = null;
  47. //
  48. // this._hasForcedRecheck = false;
  49. }
  50.  
  51. CoinTokenWorker.getDefaultTransactionRefreshTime = function() {
  52. return 60000;
  53. }
  54.  
  55.  
  56. CoinTokenWorker.prototype.initialize = function(tokenName, tokenSymbol, tokenCoinType) {
  57. log("[ Initializing " + tokenName + " Token Worker ]");
  58. this._tokenName = tokenName;
  59. this._tokenSymbol = tokenSymbol;
  60. this._tokenCoinType = tokenCoinType;
  61.  
  62. this._GATHER_TX = "/api/v1/address/txs/";
  63. this._GATHER_TX_APPEND = "";
  64.  
  65. this._GATHER_UNCONFIRMED_TX = "/api/v1/address/unconfirmed/";
  66.  
  67. this._GATHER_TX = "/api/v1/address/txs/";
  68.  
  69. this._MULTI_BALANCE = "";
  70. this._MULTI_BALANCE_APPEND = "";
  71.  
  72. var socketUri = "";
  73.  
  74. if (this._tokenCoinType === CoinToken.TheDAO) {
  75. socketUri = "";// "wss://api.ether.fund";
  76.  
  77. this._STATIC_RELAY_URL = "http://52.38.226.208:8080/api/thedao";
  78. // this._GATHER_TX = "/balance";
  79. // this._GATHER_TX_APPEND = "&sort=asc&apikey=" + HDWalletHelper.jaxxEtherscanAPIKEY;
  80.  
  81. this._GATHER_UNCONFIRMED_TX = "";
  82.  
  83. this._MULTI_BALANCE = "/balance"//?addresses%5B%5D=";
  84. // this._MULTI_BALANCE_APPEND = "&tag=latest&apikey=" + HDWalletHelper.jaxxEtherscanAPIKEY;
  85. }
  86. //
  87. // var self = this;
  88. //
  89. // if (socketUri !== "") {
  90. // this._usesWSS = true;
  91. // this._watcherWebSocket = new WebSocket(socketUri);
  92. //
  93. //
  94. // this._watcherWebSocket.onopen = function() {
  95. //
  96. // setInterval(function(){
  97. // hdWalletWorker._sendPing();
  98. // //Will reply with pong
  99. // }, 18000); //send a ping every 20 seconds more or less to avoid getting disconnected
  100. //
  101. // // We set the watcherQueue to null to indicate we are connected
  102. // var watcherQueue = self._watcherQueue;
  103. // self._watcherQueue = null;
  104. //
  105. // for (var i = 0; i < watcherQueue.length; i++) {
  106. // self._watchAddress(watcherQueue[i]);
  107. // }
  108. // };
  109. //
  110. //
  111. // this._watcherWebSocket.onmessage = function(event) {
  112. // if (!event || !event.data) {
  113. // return;
  114. // }
  115. //
  116. // var data = JSON.parse(event.data);
  117. // // log("message from socket : "+ JSON.stringify(data));
  118. //
  119. // if(data.block_height == -1){ //tx not included in any block. schedule a refresh of tx in 10 seconds
  120. // setTimeout(function () {
  121. // hdWalletWorker.checkTransactions(0);
  122. // }, 12000);
  123. // }
  124. //
  125. // /*
  126. // if (data.payload && data.payload.transaction_hash) {
  127. // // Retry up to 10 times, with "exponential back-off" (not true exponential back-off)
  128. // (function(txid) {
  129. //
  130. // var startTime = (new Date()).getTime();
  131. // var retry = 0;
  132. // var lookupTransaction = function() {
  133. //
  134. // self._lookupBitcoinTransactions([txid], function (updated) {
  135. // if (!updated[txid] && retry < 10) {
  136. //
  137. // timeout = 1.5 + Math.pow(1.4, retry++);
  138. // setTimeout(lookupTransaction, timeout * 1000);
  139. // }
  140. // });
  141. // }
  142. //
  143. // setTimeout(lookupTransaction, 0);
  144. // })(data.payload.transaction_hash);
  145. // }
  146. // */
  147. // };
  148. //
  149. // // @TODO: onerror, re-connect
  150. // this._watcherWebSocket.onerror = function(event) {
  151. // log("watcher :: " + this._coinType + " :: error :: " + JSON.stringify(event));
  152. // }
  153. // }
  154. }
  155.  
  156. CoinTokenWorker.prototype.shutDown = function() {
  157. // if (this._watcherWebSocket !== null) {
  158. // if (this._watcherWebSocket.readyState !== WebSocket.CLOSING && this._watcherWebSocket.readyState !== WebSocket.CLOSED) {
  159. // this._watcherWebSocket.onclose = function() {};
  160. // this._watcherWebSocket.close();
  161. // }
  162. // }
  163.  
  164. close();
  165. }
  166.  
  167. CoinTokenWorker.prototype._sendPing = function() {
  168. this._watcherWebSocket.send("{ \"event\": \"ping\" }");
  169. }
  170.  
  171. //@note: @here: should it remove addresses if they are in the addressinfo but not passed into this function.
  172.  
  173. CoinTokenWorker.prototype.setTokenAddresses = function(transferableTokenAddresses, votableTokenAddresses) {
  174. var transferableUpdateDict = {};
  175. var votableUpdateDict = {};
  176.  
  177. for (var i = 0; i < transferableTokenAddresses.length; i++) {
  178. var curAddress = transferableTokenAddresses[i];
  179.  
  180. var addressInfo = this._addressMap[curAddress];
  181.  
  182. if (typeof(addressInfo) !== 'undefined' && addressInfo !== null) {
  183.  
  184. } else {
  185. addressInfo = this.createNewAddressMapping(curAddress);
  186. }
  187.  
  188. addressInfo.isTransferable = true;
  189.  
  190. transferableUpdateDict[curAddress] = true;
  191. }
  192.  
  193. for (var i = 0; i < votableTokenAddresses.length; i++) {
  194. var curAddress = votableTokenAddresses[i];
  195.  
  196. var addressInfo = this._addressMap[curAddress];
  197.  
  198. if (typeof(addressInfo) !== 'undefined' && addressInfo !== null) {
  199.  
  200. } else {
  201. addressInfo = this.createNewAddressMapping(curAddress);
  202. }
  203.  
  204. addressInfo.isVotable = true;
  205.  
  206. votableUpdateDict[curAddress] = true;
  207. }
  208.  
  209. for (var curAddress in this._addressMap) {
  210. var addressInfo = this._addressMap[curAddress];
  211.  
  212. if (addressInfo.isTransferable === true && (typeof(transferableUpdateDict[curAddress]) === 'undefined' || transferableUpdateDict[curAddress] === null)) {
  213. addressInfo.isTransferable = false;
  214. }
  215.  
  216. if (addressInfo.isVotable === true && (typeof(votableUpdateDict[curAddress]) === 'undefined' || votableUpdateDict[curAddress] === null)) {
  217. addressInfo.isVotable = false;
  218. }
  219. }
  220.  
  221. // log("addressMap :: " + JSON.stringify(this._addressMap));
  222.  
  223. this.updateBalances();
  224. }
  225.  
  226. CoinTokenWorker.prototype.createNewAddressMapping = function(newAddress) {
  227. this._addressMap[newAddress] = {balance: 0, isTransferable: false, isVotable: false, isBlocked: false};
  228.  
  229. return this._addressMap[newAddress];
  230. }
  231.  
  232. CoinTokenWorker.prototype.updateTokenData = function() {
  233. //@note: @todo: updateTokenData should check for existing addresses and only call update if necessary.
  234. for (var i = 0; i < this._votableAddresses; i++) {
  235.  
  236. }
  237. }
  238.  
  239. CoinTokenWorker.prototype.updateBalances = function() {
  240. if (this._tokenCoinType === CoinToken.TheDAO) {
  241. this.updateBalancesTheDAO();
  242. }
  243. }
  244.  
  245. CoinTokenWorker.prototype.updateBalancesTheDAO = function() {
  246. var addressesToCheck = [];
  247.  
  248. for (var address in this._addressMap) {
  249. var addressInfo = this._addressMap[address];
  250.  
  251. if (typeof(addressInfo) !== "undefined" && addressInfo !== null && addressInfo.isTransferable === true) {
  252. addressesToCheck.push(address);
  253. }
  254. }
  255.  
  256. // log("addressesToCheck :: " + JSON.stringify(addressesToCheck) + " :: " + addressesToCheck.length);
  257.  
  258. var self = this;
  259.  
  260. var BATCH_SIZE = 20;
  261.  
  262. var batch = [];
  263. while (addressesToCheck.length) {
  264. batch.push(addressesToCheck.shift());
  265. if (batch.length === BATCH_SIZE || addressesToCheck.length === 0) {
  266.  
  267. var addressParam = batch.join('&addresses%5B%5D=');
  268. // log("get dao balances :: " + this._STATIC_RELAY_URL + this._MULTI_BALANCE + "?addresses%5B%5D=" + addressParam);
  269.  
  270. // log("checking :: " + batch + " :: " + batch.length + " :: " + this._STATIC_RELAY_URL + this._MULTI_BALANCE + addressParam + this._MULTI_BALANCE_APPEND);
  271.  
  272. // @note: @here: request the account balances for this batch
  273. RequestSerializer.getJSON(this._STATIC_RELAY_URL + this._MULTI_BALANCE + "?addresses%5B%5D=" + addressParam, function(data, success, passthroughParam) {
  274. // log(JSON.stringify(success));
  275. // log(JSON.stringify(data););
  276. if (success === 'success') {
  277. var balanceString = "";
  278. for (var i = 0; i < passthroughParam.length; i++) {
  279. if (typeof(self._addressMap[passthroughParam[i]]) !== 'undefined' && self._addressMap[passthroughParam[i]] !== null) {
  280. self._addressMap[passthroughParam[i]].balance = parseInt(data[i]);
  281. }
  282.  
  283.  
  284. balanceString += passthroughParam[i] + " :: " + data[i] + "\n";
  285. }
  286.  
  287. // log("balances received :: \n" + balanceString);
  288.  
  289. self.update();
  290. } else {
  291. log("error :: " + success);
  292. }
  293. }, null, batch);
  294.  
  295. batch = [];
  296. }
  297. }
  298. }
  299.  
  300. CoinTokenWorker.prototype.update = function() {
  301. // log("watcher :: " + this._coinType + " :: update :: " + this._transactions.length);
  302. var updates = {
  303. transactions: this._transactions,
  304. workerCacheAddressMap: this._addressMap,
  305. }
  306.  
  307. // if (!this._currentReceiveAddress) {
  308. // this._currentReceiveAddress = HDWalletPouch.getCoinAddress(this._coinType, this._receiveNode.derive(this._lastReceiveIndex + 1)).toString();
  309. //
  310. // updates.currentReceiveAddress = this._currentReceiveAddress;
  311. //
  312. // //@note:@todo:@here:
  313. // if (this._coinType === COIN_BITCOIN) {
  314. // updates.smallQrCode = "data:image/png;base64," + thirdparty.qrImage.imageSync("bitcoin:" + this._currentReceiveAddress, {type: "png", ec_level: "H", size: 3, margin: 1}).toString('base64');
  315. // updates.largeQrCode = "data:image/png;base64," + thirdparty.qrImage.imageSync("bitcoin:" + this._currentReceiveAddress, {type: "png", ec_level: "H", size: 7, margin: 4}).toString('base64');
  316. // } else if (this._coinType === COIN_ETHEREUM) {
  317. // //@note: given the ICAP library issue and the fact that this is effectively an isolated "thread", ethereum can regenerate its QR codes later on.
  318. // }
  319. // }
  320.  
  321. // if (!this._currentChangeAddress) {
  322. // this._currentChangeAddress = HDWalletPouch.getCoinAddress(this._coinType, this._changeNode.derive(this._lastChangeIndex + 1)).toString();
  323. // updates.currentChangeIndex = this._lastChangeIndex + 1;
  324. // updates.currentChangeAddress = this._currentChangeAddress;
  325. // }
  326.  
  327. // if (typeof(forcePouchRecheck) !== 'undefined' && forcePouchRecheck !== null) {
  328. // updates.forceRecheck = true;
  329. // }
  330.  
  331. postMessage({action: 'update', content: updates});
  332. }
  333.  
  334. var coinTokenWorker = new CoinTokenWorker();
  335.  
  336. onmessage = function(message) {
  337. if (message.data.action === 'initialize') {
  338. // log("message.data :: " + JSON.stringify(message.data));
  339. coinTokenWorker.initialize(message.data.content.tokenName, message.data.content.tokenSymbol, message.data.content.tokenCoinType);
  340. }
  341. if (message.data.action === 'setTokenAddresses') {
  342. var transferableTokenAddresses = message.data.content.transferableTokenAddresses;
  343. var votableTokenAddresses = message.data.content.votableTokenAddresses;
  344. coinTokenWorker.setTokenAddresses(transferableTokenAddresses, votableTokenAddresses);
  345. } else if (message.data.action === 'restoreAddressMapCache') {
  346. var cache = message.data.content.workerCacheAddressMap;
  347.  
  348. if (cache) {
  349. for (var address in cache) {
  350. // coinTokenWorker._addressMap[address] = cache[address];
  351. // hdWalletWorker._watchAddress(address);
  352. }
  353. }
  354. } else if (message.data.action == 'updateAddressMap') {
  355. var addressMapUpdate = message.data.content.addressMap;
  356.  
  357. if (addressMapUpdate) {
  358. for (var address in addressMapUpdate) {
  359. // hdWalletWorker._addressMap[address] = addressMapUpdate[address];
  360. }
  361. }
  362. } else if (message.data.action === 'triggerExtendedUpdate') {
  363. if (message.data.content.type && message.data.content.type === 'balances') {
  364. // setTimeout(function() {
  365. // if (hdWalletWorker._coinType === COIN_ETHEREUM) {
  366. // log("ethereum :: restore address map balance refresh");
  367. // hdWalletWorker.updateBalancesEthereum();
  368. // }
  369. // }, 10000);
  370. }
  371. }else if (message.data.action === 'refresh') {
  372. log("watcher :: " + coinTokenWorker._tokenName + " :: refreshing");
  373.  
  374. // var crashy = this.will.crash;
  375.  
  376. // log('Refreshing...');
  377. setTimeout(function () {
  378. coinTokenWorker.updateBalances();
  379. // hdWalletWorker.checkTransactions(0);
  380. }, 0);
  381. } else if (message.data.action === 'shutDown') {
  382. coinTokenWorker.shutDown();
  383. }
  384. }
  385.  
  386. setInterval(function() {
  387. setTimeout(function() {
  388. coinTokenWorker.updateBalances();
  389. }, 10000);
  390.  
  391. // hdWalletWorker.checkTransactions(HDWalletWorker.getDefaultTransactionRefreshTime());
  392.  
  393. }, CoinTokenWorker.getDefaultTransactionRefreshTime() + 100);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement