-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathripple-0.7.201-debug.js
356 lines (224 loc) · 450 KB
/
ripple-0.7.201-debug.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
var ripple =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function require(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(null, module, module.exports, require);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // The bundle contains no chunks. A empty chunk loading function.
/******/ require.e = function requireEnsure(_, callback) {
/******/ callback.call(null, require);
/******/ };
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ require.modules = modules;
/******/
/******/ // expose the module cache
/******/ require.cache = installedModules;
/******/
/******/
/******/ // Load entry module and return exports
/******/ return require(0);
/******/ })
/************************************************************************/
/******/ ({
/******/ // __webpack_public_path__
/******/ c: "",
/***/ 0:
/***/ function(module, exports, require) {
eval("exports.Remote = require(1).Remote;\r\nexports.Amount = require(2).Amount;\r\nexports.Currency = require(3).Currency;\r\nexports.Base = require(4).Base;\r\nexports.UInt160 = require(2).UInt160;\r\nexports.Seed = require(2).Seed;\r\nexports.Transaction = require(5).Transaction;\r\nexports.Meta = require(6).Meta;\r\nexports.SerializedObject = require(7).SerializedObject;\r\n\r\nexports.binformat = require(8);\r\nexports.utils = require(9);\r\nexports.Server = require(11).Server;\r\n\r\n// Important: We do not guarantee any specific version of SJCL or for any\r\n// specific features to be included. The version and configuration may change at\r\n// any time without warning.\r\n//\r\n// However, for programs that are tied to a specific version of ripple.js like\r\n// the official client, it makes sense to expose the SJCL instance so we don't\r\n// have to include it twice.\r\nexports.sjcl = require(10);\r\n\r\nexports.config = require(12);\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 0\n// module.readableIdentifier = ./src/js/ripple/index.js\n//@ sourceURL=webpack-module:///./src/js/ripple/index.js");
/***/ },
/***/ 1:
/***/ function(module, exports, require) {
eval("// Remote access to a server.\r\n// - We never send binary data.\r\n// - We use the W3C interface for node and browser compatibility:\r\n// http://www.w3.org/TR/websockets/#the-websocket-interface\r\n//\r\n// This class is intended for both browser and node.js use.\r\n//\r\n// This class is designed to work via peer protocol via either the public or\r\n// private websocket interfaces. The JavaScript class for the peer protocol\r\n// has not yet been implemented. However, this class has been designed for it\r\n// to be a very simple drop option.\r\n//\r\n// YYY Will later provide js/network.js which will transparently use multiple\r\n// instances of this class for network access.\r\n//\r\n\r\n// npm\r\nvar EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\n\r\nvar Request = require(14).Request;\r\nvar Server = require(11).Server;\r\nvar Amount = require(2).Amount;\r\nvar Currency = require(3).Currency;\r\nvar UInt160 = require(15).UInt160;\r\nvar Transaction = require(5).Transaction;\r\nvar Account = require(16).Account;\r\nvar Meta = require(6).Meta;\r\nvar OrderBook = require(17).OrderBook;\r\nvar PathFind = require(18).PathFind;\r\nvar RippleError = require(19).RippleError;\r\n\r\nvar utils = require(9);\r\nvar config = require(12);\r\nvar sjcl = require(10);\r\n\r\n/**\r\n Interface to manage the connection to a Ripple server.\r\n\r\n This implementation uses WebSockets.\r\n\r\n Keys for opts:\r\n\r\n trace\r\n max_listeners : Set maxListeners for remote; prevents EventEmitter warnings\r\n connection_offset : Connect to remote servers on supplied interval (in seconds)\r\n trusted : truthy, if remote is trusted\r\n max_fee : Maximum acceptable transaction fee\r\n fee_cushion : Extra fee multiplier to account for async fee changes.\r\n servers : Array of server objects with the following form\r\n\r\n { \r\n host: <string>\r\n , port: <number>\r\n , secure: <boolean>\r\n }\r\n\r\n Events:\r\n 'connect'\r\n 'connected' (DEPRECATED)\r\n 'disconnect'\r\n 'disconnected' (DEPRECATED)\r\n 'state':\r\n - 'online' : Connected and subscribed.\r\n - 'offline' : Not subscribed or not connected.\r\n 'subscribed' : This indicates stand-alone is available.\r\n\r\n Server events:\r\n 'ledger_closed' : A good indicate of ready to serve.\r\n 'transaction' : Transactions we receive based on current subscriptions.\r\n 'transaction_all' : Listening triggers a subscribe to all transactions\r\n globally in the network.\r\n\r\n @param opts Connection options.\r\n @param trace\r\n*/\r\n\r\nfunction Remote(opts, trace) {\r\n EventEmitter.call(this);\r\n\r\n var self = this;\r\n\r\n this.trusted = Boolean(opts.trusted);\r\n this.local_sequence = Boolean(opts.local_sequence); // Locally track sequence numbers\r\n this.local_fee = (typeof opts.local_fee === 'undefined') ? true : Boolean(opts.local_fee); // Locally set fees\r\n this.local_signing = (typeof opts.local_signing === 'undefined') ? true : Boolean(opts.local_signing);\r\n this.fee_cushion = (typeof opts.fee_cushion === 'undefined') ? 1.5 : Number(opts.fee_cushion);\r\n this.max_fee = (typeof opts.max_fee === 'undefined') ? Infinity : Number(opts.max_fee);\r\n this.id = 0;\r\n this.trace = Boolean(opts.trace);\r\n this._server_fatal = false; // True, if we know server exited.\r\n this._ledger_current_index = void(0);\r\n this._ledger_hash = void(0);\r\n this._ledger_time = void(0);\r\n this._stand_alone = void(0);\r\n this._testnet = void(0);\r\n this._transaction_subs = 0;\r\n this.online_target = false;\r\n this._online_state = 'closed'; // 'open', 'closed', 'connecting', 'closing'\r\n this.state = 'offline'; // 'online', 'offline'\r\n this.retry_timer = void(0);\r\n this.retry = void(0);\r\n\r\n this._load_base = 256;\r\n this._load_factor = 256;\r\n this._fee_ref = 10;\r\n this._fee_base = 10;\r\n this._reserve_base = void(0);\r\n this._reserve_inc = void(0);\r\n this._connection_count = 0;\r\n this._connected = false;\r\n this._connection_offset = 1000 * (Number(opts.connection_offset) || 5);\r\n this._submission_timeout = 1000 * (Number(opts.submission_timeout) || 10);\r\n\r\n this._received_tx = { };\r\n this._cur_path_find = null;\r\n\r\n // Local signing implies local fees and sequences\r\n if (this.local_signing) {\r\n this.local_sequence = true;\r\n this.local_fee = true;\r\n }\r\n\r\n this._servers = [ ];\r\n this._primary_server = void(0);\r\n\r\n // Cache information for accounts.\r\n // DEPRECATED, will be removed\r\n this.accounts = {\r\n // Consider sequence numbers stable if you know you're not generating bad transactions.\r\n // Otherwise, clear it to have it automatically refreshed from the network.\r\n\r\n // account : { seq : __ }\r\n };\r\n\r\n // Account objects by AccountId.\r\n this._accounts = { };\r\n\r\n // OrderBook objects\r\n this._books = { };\r\n\r\n // Secrets that we know about.\r\n this.secrets = {\r\n // Secrets can be set by calling set_secret(account, secret).\r\n\r\n // account : secret\r\n };\r\n\r\n // Cache for various ledgers.\r\n // XXX Clear when ledger advances.\r\n this.ledgers = {\r\n current : {\r\n account_root : {}\r\n }\r\n };\r\n\r\n // Fallback for previous API\r\n if (!opts.hasOwnProperty('servers')) {\r\n opts.servers = [ \r\n {\r\n host: opts.websocket_ip,\r\n port: opts.websocket_port,\r\n secure: opts.websocket_ssl,\r\n trusted: opts.trusted\r\n }\r\n ];\r\n }\r\n\r\n opts.servers.forEach(function(server) {\r\n var pool = Number(server.pool) || 1;\r\n while (pool--) { self.add_server(server); };\r\n });\r\n\r\n // This is used to remove Node EventEmitter warnings\r\n var maxListeners = opts.maxListeners || opts.max_listeners || 0;\r\n this._servers.concat(this).forEach(function(emitter) {\r\n emitter.setMaxListeners(maxListeners);\r\n });\r\n\r\n function listener_added(type, listener) {\r\n if (type === 'transaction_all') {\r\n if (!self._transaction_subs && self._connected) {\r\n self.request_subscribe('transactions').request();\r\n }\r\n self._transaction_subs += 1;\r\n }\r\n }\r\n\r\n function listener_removed(type, listener) {\r\n if (type === 'transaction_all') {\r\n self._transaction_subs -= 1;\r\n if (!self._transaction_subs && self._connected) {\r\n self.request_unsubscribe('transactions').request();\r\n }\r\n }\r\n }\r\n\r\n this.on('newListener', listener_added);\r\n this.on('removeListener', listener_removed);\r\n}\r\n\r\nutil.inherits(Remote, EventEmitter);\r\n\r\n// Flags for ledger entries. In support of account_root().\r\nRemote.flags = {\r\n account_root : {\r\n PasswordSpent: 0x00010000,\r\n RequireDestTag: 0x00020000,\r\n RequireAuth: 0x00040000,\r\n DisallowXRP: 0x00080000\r\n }\r\n};\r\n\r\nfunction isTemMalformed(engine_result_code) {\r\n return (engine_result_code >= -299 && engine_result_code < 199);\r\n};\r\n\r\nfunction isTefFailure(engine_result_code) {\r\n return (engine_result_code >= -299 && engine_result_code < 199);\r\n};\r\n\r\nRemote.from_config = function (obj, trace) {\r\n var serverConfig = typeof obj === 'string' ? config.servers[obj] : obj;\r\n\r\n var remote = new Remote(serverConfig, trace);\r\n\r\n function initialize_account(account) {\r\n var accountInfo = config.accounts[account];\r\n if (typeof accountInfo === 'object') {\r\n if (accountInfo.secret) {\r\n // Index by nickname ...\r\n remote.set_secret(account, accountInfo.secret);\r\n // ... and by account ID\r\n remote.set_secret(accountInfo.account, accountInfo.secret);\r\n }\r\n }\r\n }\r\n\r\n if (typeof config.accounts === 'object') {\r\n for (var account in config.accounts) {\r\n initialize_account(account);\r\n }\r\n }\r\n\r\n return remote;\r\n};\r\n\r\nRemote.create_remote = function(options, callback) {\r\n var remote = Remote.from_config(options);\r\n remote.connect(callback);\r\n return remote;\r\n};\r\n\r\nRemote.prototype.add_server = function (opts) {\r\n var self = this;\r\n\r\n var server = new Server(this, {\r\n host : opts.host || opts.websocket_ip,\r\n port : opts.port || opts.websocket_port,\r\n secure : opts.secure || opts.websocket_ssl\r\n });\r\n\r\n function server_message(data) {\r\n self._handle_message(data, server);\r\n }\r\n\r\n function server_connect() {\r\n self._connection_count++;\r\n self._set_state('online');\r\n if (opts.primary || !self._primary_server) {\r\n self._set_primary_server(server);\r\n }\r\n if (self._connection_count === self._servers.length) {\r\n self.emit('ready');\r\n }\r\n }\r\n\r\n function server_disconnect() {\r\n self._connection_count--;\r\n if (!self._connection_count) {\r\n self._set_state('offline');\r\n }\r\n }\r\n\r\n server.on('message', server_message);\r\n server.on('connect', server_connect);\r\n server.on('disconnect', server_disconnect);\r\n\r\n this._servers.push(server);\r\n\r\n return this;\r\n};\r\n\r\n// Inform remote that the remote server is not comming back.\r\nRemote.prototype.server_fatal = function () {\r\n this._server_fatal = true;\r\n};\r\n\r\n// Set the emitted state: 'online' or 'offline'\r\nRemote.prototype._set_state = function (state) {\r\n this._trace('remote: set_state: %s', state);\r\n\r\n if (this.state !== state) {\r\n this.state = state;\r\n\r\n this.emit('state', state);\r\n\r\n switch (state) {\r\n case 'online':\r\n this._online_state = 'open';\r\n this._connected = true;\r\n this.emit('connect');\r\n this.emit('connected');\r\n break;\r\n\r\n case 'offline':\r\n this._online_state = 'closed';\r\n this._connected = false;\r\n this.emit('disconnect');\r\n this.emit('disconnected');\r\n break;\r\n }\r\n }\r\n};\r\n\r\nRemote.prototype.set_trace = function (trace) {\r\n this.trace = trace === void(0) || trace;\r\n return this;\r\n};\r\n\r\nRemote.prototype._trace = function() {\r\n if (this.trace) {\r\n utils.logObject.apply(utils, arguments);\r\n }\r\n};\r\n\r\n/**\r\n * Connect to the Ripple network.\r\n */\r\nRemote.prototype.connect = function (online) {\r\n if (!this._servers.length) {\r\n throw new Error('No servers available.');\r\n }\r\n\r\n switch (typeof online) {\r\n case 'undefined':\r\n break;\r\n case 'function':\r\n this.once('connect', online);\r\n break;\r\n default:\r\n // Downwards compatibility\r\n if (!Boolean(online)) {\r\n return this.disconnect();\r\n }\r\n }\r\n\r\n var self = this;\r\n\r\n ;(function next_server(i) {\r\n var server = self._servers[i];\r\n server.connect();\r\n server._sid = ++i;\r\n\r\n if (i < self._servers.length) {\r\n setTimeout(function() {\r\n next_server(i);\r\n }, self._connection_offset);\r\n }\r\n })(0);\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Disconnect from the Ripple network.\r\n */\r\nRemote.prototype.disconnect = function (online) {\r\n if (!this._servers.length) {\r\n throw new Error('No servers available, not disconnecting');\r\n }\r\n\r\n this._servers.forEach(function(server) {\r\n server.disconnect();\r\n });\r\n\r\n this._set_state('offline');\r\n\r\n return this;\r\n};\r\n\r\n// It is possible for messages to be dispatched after the connection is closed.\r\nRemote.prototype._handle_message = function (message, server) {\r\n var self = this;\r\n\r\n try { message = JSON.parse(message); } catch(e) { }\r\n\r\n var unexpected = typeof message !== 'object' || typeof message.type !== 'string';\r\n\r\n if (unexpected) {\r\n // Unexpected response from remote.\r\n this.emit('error', new RippleError('remoteUnexpected', 'Unexpected response from remote'));\r\n return;\r\n }\r\n\r\n switch (message.type) {\r\n case 'response':\r\n // Handled by the server that sent the request\r\n break;\r\n\r\n case 'ledgerClosed':\r\n // XXX If not trusted, need to verify we consider ledger closed.\r\n // XXX Also need to consider a slow server or out of order response.\r\n // XXX Be more defensive fields could be missing or of wrong type.\r\n // YYY Might want to do some cache management.\r\n\r\n this._ledger_time = message.ledger_time;\r\n this._ledger_hash = message.ledger_hash;\r\n this._ledger_current_index = message.ledger_index + 1;\r\n\r\n this.emit('ledger_closed', message, server);\r\n break;\r\n\r\n case 'transaction':\r\n // To get these events, just subscribe to them. A subscribes and\r\n // unsubscribes will be added as needed.\r\n // XXX If not trusted, need proof.\r\n\r\n // De-duplicate transactions that are immediately following each other\r\n var hash = message.transaction.hash;\r\n\r\n if (this._received_tx.hasOwnProperty(hash)) {\r\n break;\r\n }\r\n\r\n this._received_tx[hash] = true;\r\n\r\n this._trace('remote: tx: %s', message);\r\n\r\n // Process metadata\r\n message.mmeta = new Meta(message.meta);\r\n\r\n // Pass the event on to any related Account objects\r\n message.mmeta.getAffectedAccounts().forEach(function(account) {\r\n account = self._accounts[account];\r\n if (account) account.notify(message);\r\n });\r\n\r\n // Pass the event on to any related OrderBooks\r\n message.mmeta.getAffectedBooks().forEach(function(book) {\r\n book = self._books[book];\r\n if (book) book.notify(message);\r\n });\r\n\r\n this.emit('transaction', message);\r\n this.emit('transaction_all', message);\r\n break;\r\n\r\n case 'path_find':\r\n // Pass the event to the currently open PathFind object\r\n if (this._cur_path_find) {\r\n this._cur_path_find.notify_update(message);\r\n }\r\n\r\n this.emit('path_find_all', message);\r\n break;\r\n case 'serverStatus':\r\n self.emit('server_status', message);\r\n\r\n var load_changed = message.hasOwnProperty('load_base')\r\n && message.hasOwnProperty('load_factor')\r\n && (message.load_base !== self._load_base || message.load_factor !== self._load_factor)\r\n ;\r\n\r\n if (load_changed) {\r\n self._load_base = message.load_base;\r\n self._load_factor = message.load_factor;\r\n var obj = {\r\n load_base: self._load_base,\r\n load_factor: self._load_factor,\r\n fee_units: self.fee_tx_unit()\r\n }\r\n self.emit('load', obj);\r\n self.emit('load_changed', obj);\r\n }\r\n break;\r\n\r\n // All other messages\r\n default:\r\n this._trace('remote: ' + message.type + ': %s', message);\r\n this.emit('net_' + message.type, message);\r\n break;\r\n }\r\n};\r\n\r\nRemote.prototype.ledger_hash = function () {\r\n return this._ledger_hash;\r\n};\r\n\r\nRemote.prototype._set_primary_server = function (server) {\r\n if (this._primary_server) {\r\n this._primary_server._primary = false;\r\n }\r\n this._primary_server = server;\r\n this._primary_server._primary = true;\r\n};\r\n\r\nRemote.prototype._server_is_available = function (server) {\r\n return server && server._connected;\r\n};\r\n\r\nRemote.prototype._next_server = function () {\r\n var result = null;\r\n\r\n for (var i=0; i<this._servers.length; i++) {\r\n var server = this._servers[i];\r\n if (this._server_is_available(server)) {\r\n result = server;\r\n break;\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\nRemote.prototype._get_server = function () {\r\n var server;\r\n\r\n if (this._server_is_available(this._primary_server)) {\r\n server = this._primary_server;\r\n } else {\r\n server = this._next_server();\r\n if (server) {\r\n this._set_primary_server(server);\r\n }\r\n }\r\n\r\n return server;\r\n};\r\n\r\n// Send a request.\r\n// <-> request: what to send, consumed.\r\nRemote.prototype.request = function (request) {\r\n if (!this._servers.length) {\r\n request.emit('error', new Error('No servers available'));\r\n } else if (!this._connected) {\r\n this.once('connect', this.request.bind(this, request));\r\n } else if (request.server === null) {\r\n this.emit('error', new Error('Server does not exist'));\r\n } else {\r\n var server = request.server || this._get_server();\r\n if (server) {\r\n server.request(request);\r\n } else {\r\n request.emit('error', new Error('No servers available'));\r\n }\r\n }\r\n};\r\n\r\nRemote.prototype.request_server_info = function(callback) {\r\n return new Request(this, 'server_info').callback(callback);\r\n};\r\n\r\n// XXX This is a bad command. Some varients don't scale.\r\n// XXX Require the server to be trusted.\r\nRemote.prototype.request_ledger = function (ledger, opts, callback) {\r\n //utils.assert(this.trusted);\r\n\r\n var request = new Request(this, 'ledger');\r\n\r\n if (ledger) {\r\n // DEPRECATED: use .ledger_hash() or .ledger_index()\r\n //console.log('request_ledger: ledger parameter is deprecated');\r\n request.message.ledger = ledger;\r\n }\r\n\r\n var props = [\r\n 'full'\r\n , 'expand'\r\n , 'transactions'\r\n , 'accounts'\r\n ];\r\n\r\n switch (typeof opts) {\r\n case 'object':\r\n for (var key in opts) {\r\n if (~props.indexOf(key)) {\r\n request.message[key] = true;\r\n }\r\n }\r\n break;\r\n\r\n case 'function':\r\n callback = opts;\r\n opts = void(0);\r\n break;\r\n\r\n default:\r\n //DEPRECATED\r\n console.log('request_ledger: full parameter is deprecated');\r\n request.message.full = true;\r\n break;\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// Only for unit testing.\r\nRemote.prototype.request_ledger_hash = function (callback) {\r\n //utils.assert(this.trusted); // If not trusted, need to check proof.\r\n\r\n return new Request(this, 'ledger_closed').callback(callback);\r\n};\r\n\r\n// .ledger()\r\n// .ledger_index()\r\nRemote.prototype.request_ledger_header = function (callback) {\r\n return new Request(this, 'ledger_header').callback(callback);\r\n};\r\n\r\n// Get the current proposed ledger entry. May be closed (and revised) at any time (even before returning).\r\n// Only for unit testing.\r\nRemote.prototype.request_ledger_current = function (callback) {\r\n return new Request(this, 'ledger_current').callback(callback);\r\n};\r\n\r\n// --> type : the type of ledger entry.\r\n// .ledger()\r\n// .ledger_index()\r\n// .offer_id()\r\nRemote.prototype.request_ledger_entry = function (type, callback) {\r\n //utils.assert(this.trusted); // If not trusted, need to check proof, maybe talk packet protocol.\r\n\r\n var self = this;\r\n var request = new Request(this, 'ledger_entry');\r\n\r\n // Transparent caching. When .request() is invoked, look in the Remote object for the result.\r\n // If not found, listen, cache result, and emit it.\r\n //\r\n // Transparent caching:\r\n if (type === 'account_root') {\r\n request.request_default = request.request;\r\n\r\n request.request = function () { // Intercept default request.\r\n var bDefault = true;\r\n // .self = Remote\r\n // this = Request\r\n\r\n // console.log('request_ledger_entry: caught');\r\n\r\n //if (self._ledger_hash) {\r\n // A specific ledger is requested.\r\n // XXX Add caching.\r\n // else if (req.ledger_index)\r\n // else if ('ripple_state' === request.type) // YYY Could be cached per ledger.\r\n //}\r\n\r\n if (!self._ledger_hash && type === 'account_root') {\r\n var cache = self.ledgers.current.account_root;\r\n\r\n if (!cache) {\r\n cache = self.ledgers.current.account_root = {};\r\n }\r\n\r\n var node = self.ledgers.current.account_root[request.message.account_root];\r\n\r\n if (node) {\r\n // Emulate fetch of ledger entry.\r\n // console.log('request_ledger_entry: emulating');\r\n // YYY Missing lots of fields.\r\n request.emit('success', { node: node });\r\n bDefault = false;\r\n } else { // Was not cached.\r\n // XXX Only allow with trusted mode. Must sync response with advance.\r\n switch (type) {\r\n case 'account_root':\r\n request.once('success', function (message) {\r\n // Cache node.\r\n // console.log('request_ledger_entry: caching');\r\n self.ledgers.current.account_root[message.node.Account] = message.node;\r\n });\r\n break;\r\n\r\n default:\r\n // This type not cached.\r\n // console.log('request_ledger_entry: non-cached type');\r\n }\r\n }\r\n }\r\n\r\n if (bDefault) {\r\n // console.log('request_ledger_entry: invoking');\r\n request.request_default();\r\n }\r\n };\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// .accounts(accounts, realtime)\r\nRemote.prototype.request_subscribe = function (streams, callback) {\r\n var request = new Request(this, 'subscribe');\r\n\r\n if (streams) {\r\n request.message.streams = Array.isArray(streams) ? streams : [ streams ];\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// .accounts(accounts, realtime)\r\nRemote.prototype.request_unsubscribe = function (streams, callback) {\r\n var request = new Request(this, 'unsubscribe');\r\n\r\n if (streams) {\r\n request.message.streams = Array.isArray(streams) ? streams : [ streams ];\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// .ledger_choose()\r\n// .ledger_hash()\r\n// .ledger_index()\r\nRemote.prototype.request_transaction =\r\nRemote.prototype.request_transaction_entry = function (hash, ledger_hash, callback) {\r\n //utils.assert(this.trusted); // If not trusted, need to check proof, maybe talk packet protocol.\r\n var request = new Request(this, 'transaction_entry');\r\n\r\n request.tx_hash(hash);\r\n\r\n switch (typeof ledger_hash) {\r\n case 'string':\r\n request.ledger_hash(ledger_hash);\r\n break;\r\n default:\r\n request.ledger_index('validated');\r\n callback = ledger_hash;\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// DEPRECATED: use request_transaction_entry\r\nRemote.prototype.request_tx = function (hash, callback) {\r\n var request = new Request(this, 'tx');\r\n request.message.transaction = hash;\r\n request.callback(callback);\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_account_info = function (accountID, callback) {\r\n var request = new Request(this, 'account_info');\r\n request.message.ident = UInt160.json_rewrite(accountID); // DEPRECATED\r\n request.message.account = UInt160.json_rewrite(accountID);\r\n request.callback(callback);\r\n return request;\r\n};\r\n\r\nRemote.account_request = function(type, accountID, account_index, ledger, callback) {\r\n if (typeof accountID === 'object') {\r\n var options = accountID;\r\n callback = account_index;\r\n ledger = options.ledger;\r\n account_index = options.account_index;\r\n accoutID = options.accountID;\r\n }\r\n\r\n var request = new Request(this, type);\r\n\r\n request.message.account = UInt160.json_rewrite(accountID);\r\n\r\n if (account_index) {\r\n request.message.index = account_index;\r\n }\r\n\r\n request.ledger_choose(ledger);\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// --> account_index: sub_account index (optional)\r\n// --> current: true, for the current ledger.\r\nRemote.prototype.request_account_lines = function (accountID, account_index, ledger, callback) {\r\n // XXX Does this require the server to be trusted?\r\n //utils.assert(this.trusted);\r\n var args = Array.prototype.slice.call(arguments);\r\n args.unshift('account_lines');\r\n return Remote.account_request.apply(this, args);\r\n};\r\n\r\n// --> account_index: sub_account index (optional)\r\n// --> current: true, for the current ledger.\r\nRemote.prototype.request_account_offers = function (accountID, account_index, ledger, callback) {\r\n var args = Array.prototype.arguments.slice(arguments);\r\n args.unshift('account_offers');\r\n return Remote.account_request.apply(this, args);\r\n};\r\n\r\n/*\r\n account: account,\r\n ledger_index_min: ledger_index, // optional, defaults to -1 if ledger_index_max is specified.\r\n ledger_index_max: ledger_index, // optional, defaults to -1 if ledger_index_min is specified.\r\n binary: boolean, // optional, defaults to false\r\n count: boolean, // optional, defaults to false\r\n descending: boolean, // optional, defaults to false\r\n offset: integer, // optional, defaults to 0\r\n limit: integer // optional\r\n*/\r\n\r\nRemote.prototype.request_account_tx = function (options, callback) {\r\n // XXX Does this require the server to be trusted?\r\n //utils.assert(this.trusted);\r\n\r\n var request = new Request(this, 'account_tx');\r\n\r\n var request_fields = [\r\n 'account'\r\n , 'ledger_index_min' //earliest\r\n , 'ledger_index_max' //latest\r\n , 'binary' //false\r\n , 'count' //false\r\n , 'descending' //false\r\n , 'offset' //0\r\n , 'limit'\r\n\r\n //extended account_tx\r\n , 'forward' //false\r\n , 'marker'\r\n ];\r\n\r\n for (var key in options) {\r\n if (~request_fields.indexOf(key)) {\r\n request.message[key] = options[key];\r\n }\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n/**\r\n * Request the overall transaction history.\r\n *\r\n * Returns a list of transactions that happened recently on the network. The\r\n * default number of transactions to be returned is 20.\r\n */\r\nRemote.prototype.request_tx_history = function (start, callback) {\r\n // XXX Does this require the server to be trusted?\r\n //utils.assert(this.trusted);\r\n\r\n var request = new Request(this, 'tx_history');\r\n\r\n request.message.start = start;\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_book_offers = function (gets, pays, taker, callback) {\r\n if (typeof gets === 'object') {\r\n var options = gets;\r\n taker = options.taker;\r\n pays = options.pays;\r\n gets = options.gets;\r\n }\r\n\r\n var request = new Request(this, 'book_offers');\r\n\r\n request.message.taker_gets = {\r\n currency: Currency.json_rewrite(gets.currency)\r\n };\r\n\r\n if (request.message.taker_gets.currency !== 'XRP') {\r\n request.message.taker_gets.issuer = UInt160.json_rewrite(gets.issuer);\r\n }\r\n\r\n request.message.taker_pays = {\r\n currency: Currency.json_rewrite(pays.currency)\r\n };\r\n\r\n if (request.message.taker_pays.currency !== 'XRP') {\r\n request.message.taker_pays.issuer = UInt160.json_rewrite(pays.issuer);\r\n }\r\n\r\n request.message.taker = taker ? taker : UInt160.ACCOUNT_ONE;\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_wallet_accounts = function (seed, callback) {\r\n utils.assert(this.trusted); // Don't send secrets.\r\n var request = new Request(this, 'wallet_accounts');\r\n request.message.seed = seed;\r\n return request.callback(callback);\r\n};\r\n\r\nRemote.prototype.request_sign = function (secret, tx_json, callback) {\r\n utils.assert(this.trusted); // Don't send secrets.\r\n var request = new Request(this, 'sign');\r\n request.message.secret = secret;\r\n request.message.tx_json = tx_json;\r\n request.callback(callback);\r\n return request;\r\n};\r\n\r\n// Submit a transaction.\r\nRemote.prototype.request_submit = function (callback) {\r\n return new Request(this, 'submit').callback(callback);\r\n};\r\n\r\n//\r\n// Higher level functions.\r\n//\r\n\r\n/**\r\n * Create a subscribe request with current subscriptions.\r\n *\r\n * Other classes can add their own subscriptions to this request by listening to\r\n * the server_subscribe event.\r\n *\r\n * This function will create and return the request, but not submit it.\r\n */\r\nRemote.prototype._server_prepare_subscribe = function (callback) {\r\n var self = this;\r\n\r\n var feeds = [ 'ledger', 'server' ];\r\n\r\n if (this._transaction_subs) {\r\n feeds.push('transactions');\r\n }\r\n\r\n var request = this.request_subscribe(feeds);\r\n\r\n request.once('success', function (message) {\r\n self._stand_alone = !!message.stand_alone;\r\n self._testnet = !!message.testnet;\r\n\r\n if (typeof message.random === 'string') {\r\n var rand = message.random.match(/[0-9A-F]{8}/ig);\r\n while (rand && rand.length) {\r\n sjcl.random.addEntropy(parseInt(rand.pop(), 16));\r\n }\r\n self.emit('random', utils.hexToArray(message.random));\r\n }\r\n\r\n if (message.ledger_hash && message.ledger_index) {\r\n self._ledger_time = message.ledger_time;\r\n self._ledger_hash = message.ledger_hash;\r\n self._ledger_current_index = message.ledger_index+1;\r\n self.emit('ledger_closed', message);\r\n }\r\n\r\n // FIXME Use this to estimate fee.\r\n // XXX When we have multiple server support, most of this should be tracked\r\n // by the Server objects and then aggregated/interpreted by Remote.\r\n self._load_base = message.load_base || 256;\r\n self._load_factor = message.load_factor || 256;\r\n self._fee_ref = message.fee_ref;\r\n self._fee_base = message.fee_base;\r\n self._reserve_base = message.reserve_base;\r\n self._reserve_inc = message.reserve_inc;\r\n\r\n self.emit('subscribed');\r\n });\r\n\r\n request.on('error', function (err) {\r\n // XXX We need a better global error handling\r\n //console.log(err);\r\n });\r\n\r\n self.emit('prepare_subscribe', request);\r\n\r\n request.callback(callback);\r\n\r\n // XXX Could give error events, maybe even time out.\r\n\r\n return request;\r\n};\r\n\r\n// For unit testing: ask the remote to accept the current ledger.\r\n// - To be notified when the ledger is accepted, server_subscribe() then listen to 'ledger_hash' events.\r\n// A good way to be notified of the result of this is:\r\n// remote.once('ledger_closed', function (ledger_closed, ledger_index) { ... } );\r\nRemote.prototype.ledger_accept = function (callback) {\r\n if (this._stand_alone) {\r\n var request = new Request(this, 'ledger_accept');\r\n request.request();\r\n request.callback(callback);\r\n } else {\r\n this.emit('error', new RippleError('notStandAlone'));\r\n }\r\n return this;\r\n};\r\n\r\n// Return a request to refresh the account balance.\r\nRemote.prototype.request_account_balance = function (account, ledger, callback) {\r\n if (typeof account === 'object') {\r\n callback = ledger;\r\n ledger = account.ledger;\r\n account = account.account;\r\n }\r\n\r\n var request = this.request_ledger_entry('account_root');\r\n request.account_root(account);\r\n request.ledger_choose(ledger);\r\n request.once('success', function (message) {\r\n request.emit('account_balance', Amount.from_json(message.node.Balance));\r\n });\r\n request.callback(callback, 'account_balance');\r\n return request;\r\n};\r\n\r\n// Return a request to return the account flags.\r\nRemote.prototype.request_account_flags = function (account, ledger, callback) {\r\n if (typeof account === 'object') {\r\n callback = ledger;\r\n ledger = account.ledger;\r\n account = account.account;\r\n }\r\n\r\n var request = this.request_ledger_entry('account_root');\r\n request.account_root(account);\r\n request.ledger_choose(ledger);\r\n request.once('success', function (message) {\r\n request.emit('account_flags', message.node.Flags);\r\n });\r\n request.callback(callback, 'account_flags');\r\n return request;\r\n};\r\n\r\n// Return a request to emit the owner count.\r\nRemote.prototype.request_owner_count = function (account, ledger, callback) {\r\n if (typeof account === 'object') {\r\n callback = ledger;\r\n ledger = account.ledger;\r\n account = account.account;\r\n }\r\n\r\n var request = this.request_ledger_entry('account_root');\r\n request.account_root(account);\r\n request.ledger_choose(ledger);\r\n request.once('success', function (message) {\r\n request.emit('owner_count', message.node.OwnerCount);\r\n });\r\n request.callback(callback, 'owner_count');\r\n\r\n return request;\r\n};\r\n\r\nRemote.prototype.get_account = function(accountID) {\r\n return this._accounts[UInt160.json_rewrite(accountID)];\r\n};\r\n\r\nRemote.prototype.add_account = function(accountID) {\r\n var account = new Account(this, accountID);\r\n if (account.is_valid()) {\r\n this._accounts[accountID] = account;\r\n }\r\n return account;\r\n};\r\n\r\nRemote.prototype.account = function (accountID) {\r\n var account = this.get_account(accountID);\r\n return account ? account : this.add_account(accountID);\r\n};\r\n\r\nRemote.prototype.path_find = function (src_account, dst_account, dst_amount, src_currencies) {\r\n if (typeof src_account === 'object') {\r\n var options = src_account;\r\n src_currencies = options.src_currencies;\r\n dst_amount = options.dst_amount;\r\n dst_account = options.dst_account;\r\n src_account = options.src_account;\r\n }\r\n\r\n var path_find = new PathFind(this, src_account, dst_account, dst_amount, src_currencies);\r\n\r\n if (this._cur_path_find) {\r\n this._cur_path_find.notify_superceded();\r\n }\r\n\r\n path_find.create();\r\n\r\n this._cur_path_find = path_find;\r\n\r\n return path_find;\r\n};\r\n\r\nRemote.prepare_trade = function(currency, issuer) {\r\n return currency + (currency === 'XRP' ? '' : ('/' + issuer));\r\n};\r\n\r\nRemote.prototype.book = function (currency_gets, issuer_gets, currency_pays, issuer_pays) {\r\n if (typeof currency_gets === 'object') {\r\n var options = currency_gets;\r\n issuer_pays = options.issuer_pays;\r\n currency_pays = options.currency_pays;\r\n issuer_gets = options.issuer_gets;\r\n currency_gets = options.currency_gets;\r\n }\r\n\r\n var gets = Remote.prepare_trade(currency_gets, issuer_gets);\r\n var pays = Remote.prepare_trade(currency_pays, issuer_pays);\r\n var key = gets + ':' + pays;\r\n var book;\r\n\r\n if (!this._books.hasOwnProperty(key)) {\r\n book = new OrderBook(this, currency_gets, issuer_gets, currency_pays, issuer_pays);\r\n if (book.is_valid()) {\r\n this._books[key] = book;\r\n }\r\n }\r\n\r\n return this._books[key];\r\n};\r\n\r\n// Return the next account sequence if possible.\r\n// <-- undefined or Sequence\r\nRemote.prototype.account_seq = function (account, advance) {\r\n var account = UInt160.json_rewrite(account);\r\n var account_info = this.accounts[account];\r\n var seq;\r\n\r\n if (account_info && account_info.seq) {\r\n seq = account_info.seq;\r\n var change = { ADVANCE: 1, REWIND: -1 }[advance.toUpperCase()] || 0;\r\n account_info.seq += change;\r\n }\r\n\r\n return seq;\r\n};\r\n\r\nRemote.prototype.set_account_seq = function (account, seq) {\r\n var account = UInt160.json_rewrite(account);\r\n\r\n if (!this.accounts.hasOwnProperty(account)) {\r\n this.accounts[account] = { };\r\n }\r\n\r\n this.accounts[account].seq = seq;\r\n}\r\n\r\n// Return a request to refresh accounts[account].seq.\r\nRemote.prototype.account_seq_cache = function (account, ledger, callback) {\r\n if (typeof account === 'object') {\r\n var options = account;\r\n callback = ledger;\r\n ledger = options.ledger;\r\n account = options.account;\r\n }\r\n\r\n var self = this;\r\n\r\n if (!this.accounts.hasOwnProperty(account)) {\r\n this.accounts[account] = { };\r\n }\r\n\r\n var account_info = this.accounts[account];\r\n var request = account_info.caching_seq_request;\r\n\r\n if (!request) {\r\n // console.log('starting: %s', account);\r\n request = this.request_ledger_entry('account_root');\r\n request.account_root(account);\r\n request.ledger_choose(ledger);\r\n\r\n function account_root_success(message) {\r\n delete account_info.caching_seq_request;\r\n\r\n var seq = message.node.Sequence;\r\n account_info.seq = seq;\r\n\r\n // console.log('caching: %s %d', account, seq);\r\n // If the caller also waits for 'success', they might run before this.\r\n request.emit('success_account_seq_cache', message);\r\n }\r\n\r\n function account_root_error(message) {\r\n // console.log('error: %s', account);\r\n delete account_info.caching_seq_request;\r\n\r\n request.emit('error_account_seq_cache', message);\r\n }\r\n\r\n request.once('success', account_root_success);\r\n request.once('error', account_root_error);\r\n\r\n account_info.caching_seq_request = request;\r\n }\r\n\r\n request.callback(callback, 'success_account_seq_cache', 'error_account_seq_cache');\r\n\r\n return request;\r\n};\r\n\r\n// Mark an account's root node as dirty.\r\nRemote.prototype.dirty_account_root = function (account) {\r\n var account = UInt160.json_rewrite(account);\r\n delete this.ledgers.current.account_root[account];\r\n};\r\n\r\n// Store a secret - allows the Remote to automatically fill out auth information.\r\nRemote.prototype.set_secret = function (account, secret) {\r\n this.secrets[account] = secret;\r\n};\r\n\r\n\r\n// Return a request to get a ripple balance.\r\n//\r\n// --> account: String\r\n// --> issuer: String\r\n// --> currency: String\r\n// --> current: bool : true = current ledger\r\n//\r\n// If does not exist: emit('error', 'error' : 'remoteError', 'remote' : { 'error' : 'entryNotFound' })\r\nRemote.prototype.request_ripple_balance = function (account, issuer, currency, ledger, callback) {\r\n if (typeof account === 'object') {\r\n var options = account;\r\n callback = issuer;\r\n ledger = options.ledger;\r\n currency = options.currency;\r\n issuer = options.issuer;\r\n account = options.account;\r\n }\r\n\r\n var request = this.request_ledger_entry('ripple_state'); // YYY Could be cached per ledger.\r\n\r\n request.ripple_state(account, issuer, currency);\r\n request.ledger_choose(ledger);\r\n request.once('success', function(message) {\r\n var node = message.node;\r\n var lowLimit = Amount.from_json(node.LowLimit);\r\n var highLimit = Amount.from_json(node.HighLimit);\r\n // The amount the low account holds of issuer.\r\n var balance = Amount.from_json(node.Balance);\r\n // accountHigh implies: for account: balance is negated, highLimit is the limit set by account.\r\n var accountHigh = UInt160.from_json(account).equals(highLimit.issuer());\r\n\r\n request.emit('ripple_state', {\r\n account_balance : ( accountHigh ? balance.negate() : balance.clone()).parse_issuer(account),\r\n peer_balance : (!accountHigh ? balance.negate() : balance.clone()).parse_issuer(issuer),\r\n\r\n account_limit : ( accountHigh ? highLimit : lowLimit).clone().parse_issuer(issuer),\r\n peer_limit : (!accountHigh ? highLimit : lowLimit).clone().parse_issuer(account),\r\n\r\n account_quality_in : ( accountHigh ? node.HighQualityIn : node.LowQualityIn),\r\n peer_quality_in : (!accountHigh ? node.HighQualityIn : node.LowQualityIn),\r\n\r\n account_quality_out : ( accountHigh ? node.HighQualityOut : node.LowQualityOut),\r\n peer_quality_out : (!accountHigh ? node.HighQualityOut : node.LowQualityOut),\r\n });\r\n });\r\n\r\n request.callback(callback, 'ripple_state');\r\n\r\n return request;\r\n};\r\n\r\nRemote.prepare_currencies = function(ci) {\r\n var ci_new = { };\r\n\r\n if (ci.hasOwnProperty('issuer')) {\r\n ci_new.issuer = UInt160.json_rewrite(ci.issuer);\r\n }\r\n\r\n if (ci.hasOwnProperty('currency')) {\r\n ci_new.currency = Currency.json_rewrite(ci.currency);\r\n }\r\n\r\n return ci_new;\r\n};\r\n\r\nRemote.prototype.request_ripple_path_find = function (src_account, dst_account, dst_amount, src_currencies, callback) {\r\n if (typeof src_account === 'object') {\r\n var options = src_account;\r\n callback = dst_account;\r\n src_currencies = options.src_currencies;\r\n dst_amount = options.dst_amount;\r\n dst_account = options.dst_account;\r\n src_account = options.src_account;\r\n }\r\n\r\n var request = new Request(this, 'ripple_path_find');\r\n\r\n request.message.source_account = UInt160.json_rewrite(src_account);\r\n request.message.destination_account = UInt160.json_rewrite(dst_account);\r\n request.message.destination_amount = Amount.json_rewrite(dst_amount);\r\n\r\n if (src_currencies) {\r\n request.message.source_currencies = src_currencies.map(Remote.prepare_currencies);\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_path_find_create = function (src_account, dst_account, dst_amount, src_currencies, callback) {\r\n if (typeof src_account === 'object') {\r\n var options = src_account;\r\n callback = dst_account;\r\n src_currencies = options.src_currencies;\r\n dst_amount = options.dst_amount;\r\n dst_account = options.dst_account;\r\n src_account = options.src_account;\r\n }\r\n\r\n var request = new Request(this, 'path_find');\r\n\r\n request.message.subcommand = 'create';\r\n request.message.source_account = UInt160.json_rewrite(src_account);\r\n request.message.destination_account = UInt160.json_rewrite(dst_account);\r\n request.message.destination_amount = Amount.json_rewrite(dst_amount);\r\n\r\n if (src_currencies) {\r\n request.message.source_currencies = src_currencies.map(Remote.prepare_currencies);\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_path_find_close = function () {\r\n var request = new Request(this, 'path_find');\r\n request.message.subcommand = 'close';\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_unl_list = function (callback) {\r\n return new Request(this, 'unl_list').callback(callback);\r\n};\r\n\r\nRemote.prototype.request_unl_add = function (addr, comment, callback) {\r\n var request = new Request(this, 'unl_add');\r\n\r\n request.message.node = addr;\r\n\r\n if (comment) {\r\n request.message.comment = note;\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\n// --> node: <domain> | <public_key>\r\nRemote.prototype.request_unl_delete = function (node, callback) {\r\n var request = new Request(this, 'unl_delete');\r\n request.message.node = node;\r\n request.callback(callback);\r\n return request;\r\n};\r\n\r\nRemote.prototype.request_peers = function (callback) {\r\n return new Request(this, 'peers').callback(callback);\r\n};\r\n\r\nRemote.prototype.request_connect = function (ip, port, callback) {\r\n var request = new Request(this, 'connect');\r\n\r\n request.message.ip = ip;\r\n\r\n if (port) {\r\n request.message.port = port;\r\n }\r\n\r\n request.callback(callback);\r\n\r\n return request;\r\n};\r\n\r\nRemote.prototype.transaction = function (source, destination, amount, callback) {\r\n var tx = new Transaction(this);\r\n\r\n if (arguments.length >= 3) {\r\n tx = tx.payment(source, destination, amount);\r\n if (typeof callback === 'function') {\r\n tx.submit(callback);\r\n }\r\n }\r\n\r\n return tx;\r\n};\r\n\r\n/**\r\n * Calculate a transaction fee for a number of tx fee units.\r\n *\r\n * This takes into account the last known network and local load fees.\r\n *\r\n * @return {Amount} Final fee in XRP for specified number of fee units.\r\n */\r\nRemote.prototype.fee_tx = function (units) {\r\n var fee_unit = this.fee_tx_unit();\r\n return Amount.from_json(String(Math.ceil(units * fee_unit)));\r\n};\r\n\r\n/**\r\n * Get the current recommended transaction fee unit.\r\n *\r\n * Multiply this value with the number of fee units in order to calculate the\r\n * recommended fee for the transaction you are trying to submit.\r\n *\r\n * @return {Number} Recommended amount for one fee unit as float.\r\n */\r\nRemote.prototype.fee_tx_unit = function () {\r\n var fee_unit = this._fee_base / this._fee_ref;\r\n\r\n // Apply load fees\r\n fee_unit *= this._load_factor / this._load_base;\r\n\r\n // Apply fee cushion (a safety margin in case fees rise since we were last updated\r\n fee_unit *= this.fee_cushion;\r\n\r\n return fee_unit;\r\n};\r\n\r\n/**\r\n * Get the current recommended reserve base.\r\n *\r\n * Returns the base reserve with load fees and safety margin applied.\r\n */\r\nRemote.prototype.reserve = function (owner_count) {\r\n var reserve_base = Amount.from_json(String(this._reserve_base));\r\n var reserve_inc = Amount.from_json(String(this._reserve_inc));\r\n var owner_count = owner_count || 0;\r\n\r\n if (owner_count < 0) {\r\n throw new Error('Owner count must not be negative.');\r\n }\r\n\r\n return reserve_base.add(reserve_inc.product_human(owner_count));\r\n};\r\n\r\nRemote.prototype.ping = function(host, callback) {\r\n var request = new Request(this, 'ping');\r\n\r\n switch (typeof host) {\r\n case 'function':\r\n callback = host;\r\n break;\r\n case 'string':\r\n request.set_server(host);\r\n break;\r\n }\r\n\r\n var then = Date.now();\r\n\r\n request.once('success', function() {\r\n request.emit('pong', Date.now() - then);\r\n });\r\n\r\n request.callback(callback, 'pong');\r\n\r\n return request;\r\n};\r\n\r\nexports.Remote = Remote;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 1\n// module.readableIdentifier = ./src/js/ripple/remote.js\n//@ sourceURL=webpack-module:///./src/js/ripple/remote.js");
/***/ },
/***/ 2:
/***/ function(module, exports, require) {
eval("// Represent Ripple amounts and currencies.\r\n// - Numbers in hex are big-endian.\r\n\r\nvar sjcl = require(10);\r\nvar bn\t = sjcl.bn;\r\nvar utils = require(9);\r\nvar jsbn = require(20);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\n\r\nvar UInt160 = require(15).UInt160,\r\n Seed = require(21).Seed,\r\n Currency = require(3).Currency;\r\n\r\nvar consts = exports.consts = {\r\n 'currency_xns' : 0,\r\n 'currency_one' : 1,\r\n 'xns_precision' : 6,\r\n\r\n // BigInteger values prefixed with bi_.\r\n 'bi_5'\t : new BigInteger('5'),\r\n 'bi_7'\t : new BigInteger('7'),\r\n 'bi_10'\t : new BigInteger('10'),\r\n 'bi_1e14' : new BigInteger(String(1e14)),\r\n 'bi_1e16' : new BigInteger(String(1e16)),\r\n 'bi_1e17' : new BigInteger(String(1e17)),\r\n 'bi_1e32' : new BigInteger('100000000000000000000000000000000'),\r\n 'bi_man_max_value' : new BigInteger('9999999999999999'),\r\n 'bi_man_min_value' : new BigInteger('1000000000000000'),\r\n 'bi_xns_max'\t : new BigInteger(\"9000000000000000000\"),\t // Json wire limit.\r\n 'bi_xns_min'\t : new BigInteger(\"-9000000000000000000\"),\t // Json wire limit.\r\n 'bi_xns_unit'\t : new BigInteger('1000000'),\r\n\r\n 'cMinOffset' : -96,\r\n 'cMaxOffset' : 80,\r\n};\r\n\r\n\r\n//\r\n// Amount class in the style of Java's BigInteger class\r\n// http://docs.oracle.com/javase/1.3/docs/api/java/math/BigInteger.html\r\n//\r\n\r\nvar Amount = function () {\r\n // Json format:\r\n // integer : XRP\r\n // { 'value' : ..., 'currency' : ..., 'issuer' : ...}\r\n\r\n this._value\t = new BigInteger();\t// NaN for bad value. Always positive.\r\n this._offset\t = 0;\t // Always 0 for XRP.\r\n this._is_native = true;\t\t// Default to XRP. Only valid if value is not NaN.\r\n this._is_negative = false;\r\n\r\n this._currency = new Currency();\r\n this._issuer\t = new UInt160();\r\n};\r\n\r\n// Given \"100/USD/mtgox\" return the a string with mtgox remapped.\r\nAmount.text_full_rewrite = function (j) {\r\n return Amount.from_json(j).to_text_full();\r\n}\r\n\r\n// Given \"100/USD/mtgox\" return the json.\r\nAmount.json_rewrite = function (j) {\r\n return Amount.from_json(j).to_json();\r\n};\r\n\r\nAmount.from_number = function (n) {\r\n return (new Amount()).parse_number(n);\r\n};\r\n\r\nAmount.from_json = function (j) {\r\n return (new Amount()).parse_json(j);\r\n};\r\n\r\nAmount.from_quality = function (q, c, i) {\r\n return (new Amount()).parse_quality(q, c, i);\r\n};\r\n\r\nAmount.from_human = function (j) {\r\n return (new Amount()).parse_human(j);\r\n};\r\n\r\nAmount.is_valid = function (j) {\r\n return Amount.from_json(j).is_valid();\r\n};\r\n\r\nAmount.is_valid_full = function (j) {\r\n return Amount.from_json(j).is_valid_full();\r\n};\r\n\r\nAmount.NaN = function () {\r\n var result = new Amount();\r\n\r\n result._value = NaN;\r\n\r\n return result;\r\n};\r\n\r\n// Returns a new value which is the absolute value of this.\r\nAmount.prototype.abs = function () {\r\n return this.clone(this.is_negative());\r\n};\r\n\r\n// Result in terms of this' currency and issuer.\r\nAmount.prototype.add = function (v) {\r\n var result;\r\n\r\n v = Amount.from_json(v);\r\n\r\n if (!this.is_comparable(v)) {\r\n result = Amount.NaN();\r\n }\r\n else if (v.is_zero()) {\r\n result = this; \r\n }\r\n else if (this.is_zero()) {\r\n result = v.clone();\r\n result._is_native = this._is_native;\r\n result._currency = this._currency;\r\n result._issuer = this._issuer;\r\n }\r\n else if (this._is_native) {\r\n result = new Amount();\r\n\r\n var v1 = this._is_negative ? this._value.negate() : this._value;\r\n var v2 = v._is_negative ? v._value.negate() : v._value;\r\n var s = v1.add(v2);\r\n\r\n result._is_negative = s.compareTo(BigInteger.ZERO) < 0;\r\n result._value = result._is_negative ? s.negate() : s;\r\n result._currency = this._currency;\r\n result._issuer = this._issuer;\r\n }\r\n else\r\n {\r\n var v1 = this._is_negative ? this._value.negate() : this._value;\r\n var o1 = this._offset;\r\n var v2 = v._is_negative ? v._value.negate() : v._value;\r\n var o2 = v._offset;\r\n\r\n while (o1 < o2) {\r\n v1 = v1.divide(consts.bi_10);\r\n o1 += 1;\r\n }\r\n\r\n while (o2 < o1) {\r\n v2 = v2.divide(consts.bi_10);\r\n o2 += 1;\r\n }\r\n\r\n result = new Amount();\r\n result._is_native = false;\r\n result._offset = o1;\r\n result._value = v1.add(v2);\r\n result._is_negative = result._value.compareTo(BigInteger.ZERO) < 0;\r\n\r\n if (result._is_negative) {\r\n result._value = result._value.negate();\r\n }\r\n\r\n result._currency = this._currency;\r\n result._issuer = this._issuer;\r\n\r\n result.canonicalize();\r\n }\r\n\r\n return result;\r\n};\r\n\r\nAmount.prototype.canonicalize = function () {\r\n if (!(this._value instanceof BigInteger))\r\n {\r\n // NaN.\r\n // nothing\r\n }\r\n else if (this._is_native) {\r\n // Native.\r\n\r\n if (this._value.equals(BigInteger.ZERO)) {\r\n this._offset = 0;\r\n this._is_negative = false;\r\n }\r\n else {\r\n // Normalize _offset to 0.\r\n\r\n while (this._offset < 0) {\r\n this._value = this._value.divide(consts.bi_10);\r\n this._offset += 1;\r\n }\r\n\r\n while (this._offset > 0) {\r\n this._value = this._value.multiply(consts.bi_10);\r\n this._offset -= 1;\r\n }\r\n }\r\n\r\n // XXX Make sure not bigger than supported. Throw if so.\r\n }\r\n else if (this.is_zero()) {\r\n this._offset = -100;\r\n this._is_negative = false;\r\n }\r\n else\r\n {\r\n // Normalize mantissa to valid range.\r\n\r\n while (this._value.compareTo(consts.bi_man_min_value) < 0) {\r\n this._value = this._value.multiply(consts.bi_10);\r\n this._offset -= 1;\r\n }\r\n\r\n while (this._value.compareTo(consts.bi_man_max_value) > 0) {\r\n this._value = this._value.divide(consts.bi_10);\r\n this._offset += 1;\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\nAmount.prototype.clone = function (negate) {\r\n return this.copyTo(new Amount(), negate);\r\n};\r\n\r\nAmount.prototype.compareTo = function (v) {\r\n var result;\r\n\r\n if (!this.is_comparable(v)) {\r\n result = Amount.NaN();\r\n }\r\n else if (this._is_negative !== v._is_negative) {\r\n // Different sign.\r\n result = this._is_negative ? -1 : 1;\r\n }\r\n else if (this._value.equals(BigInteger.ZERO)) {\r\n // Same sign: positive.\r\n result = v._value.equals(BigInteger.ZERO) ? 0 : -1;\r\n }\r\n else if (v._value.equals(BigInteger.ZERO)) {\r\n // Same sign: positive.\r\n result = 1;\r\n }\r\n else if (!this._is_native && this._offset > v._offset) {\r\n result = this._is_negative ? -1 : 1;\r\n }\r\n else if (!this._is_native && this._offset < v._offset) {\r\n result = this._is_negative ? 1 : -1;\r\n }\r\n else {\r\n result = this._value.compareTo(v._value);\r\n\r\n if (result > 0)\r\n result = this._is_negative ? -1 : 1;\r\n else if (result < 0)\r\n result = this._is_negative ? 1 : -1;\r\n }\r\n\r\n return result;\r\n};\r\n\r\n// Make d a copy of this. Returns d.\r\n// Modification of objects internally refered to is not allowed.\r\nAmount.prototype.copyTo = function (d, negate) {\r\n if ('object' === typeof this._value)\r\n {\r\n this._value.copyTo(d._value);\r\n }\r\n else\r\n {\r\n d._value = this._value;\r\n }\r\n\r\n d._offset\t = this._offset;\r\n d._is_native\t = this._is_native;\r\n d._is_negative = negate\r\n\t\t\t? !this._is_negative // Negating.\r\n\t\t\t: this._is_negative; // Just copying.\r\n\r\n d._currency = this._currency;\r\n d._issuer = this._issuer;\r\n\r\n // Prevent negative zero\r\n if (d.is_zero()) d._is_negative = false;\r\n\r\n return d;\r\n};\r\n\r\nAmount.prototype.currency = function () {\r\n return this._currency;\r\n};\r\n\r\nAmount.prototype.equals = function (d, ignore_issuer) {\r\n if (\"string\" === typeof d) {\r\n return this.equals(Amount.from_json(d));\r\n }\r\n\r\n if (this === d) return true;\r\n\r\n if (d instanceof Amount) {\r\n if (!this.is_valid() || !d.is_valid()) return false;\r\n if (this._is_native !== d._is_native) return false;\r\n\r\n if (!this._value.equals(d._value) || this._offset !== d._offset) {\r\n return false;\r\n }\r\n\r\n if (this._is_negative !== d._is_negative) return false;\r\n\r\n if (!this._is_native) {\r\n if (!this._currency.equals(d._currency)) return false;\r\n if (!ignore_issuer && !this._issuer.equals(d._issuer)) return false;\r\n }\r\n return true;\r\n } else return false;\r\n};\r\n\r\n// Result in terms of this' currency and issuer.\r\nAmount.prototype.divide = function (d) {\r\n var result;\r\n\r\n if (d.is_zero()) {\r\n throw \"divide by zero\";\r\n }\r\n else if (this.is_zero()) {\r\n result = this;\r\n }\r\n else if (!this.is_valid()) {\r\n throw new Error(\"Invalid dividend\");\r\n }\r\n else if (!d.is_valid()) {\r\n throw new Error(\"Invalid divisor\");\r\n }\r\n else {\r\n var _n = this;\r\n\r\n if (_n.is_native()) {\r\n _n = _n.clone();\r\n\r\n while (_n._value.compareTo(consts.bi_man_min_value) < 0) {\r\n _n._value = _n._value.multiply(consts.bi_10);\r\n _n._offset -= 1;\r\n }\r\n }\r\n\r\n var _d = d;\r\n\r\n if (_d.is_native()) {\r\n _d = _d.clone();\r\n\r\n while (_d._value.compareTo(consts.bi_man_min_value) < 0) {\r\n _d._value = _d._value.multiply(consts.bi_10);\r\n _d._offset -= 1;\r\n }\r\n }\r\n\r\n result = new Amount();\r\n result._offset = _n._offset - _d._offset - 17;\r\n result._value = _n._value.multiply(consts.bi_1e17).divide(_d._value).add(consts.bi_5);\r\n result._is_native = _n._is_native;\r\n result._is_negative = _n._is_negative !== _d._is_negative;\r\n result._currency = _n._currency;\r\n result._issuer = _n._issuer;\r\n\r\n result.canonicalize();\r\n }\r\n\r\n return result;\r\n};\r\n\r\n/**\r\n * Calculate a ratio between two amounts.\r\n *\r\n * This function calculates a ratio - such as a price - between two Amount\r\n * objects.\r\n *\r\n * The return value will have the same type (currency) as the numerator. This is\r\n * a simplification, which should be sane in most cases. For example, a USD/XRP\r\n * price would be rendered as USD.\r\n *\r\n * @example\r\n * var price = buy_amount.ratio_human(sell_amount);\r\n *\r\n * @this {Amount} The numerator (top half) of the fraction.\r\n * @param {Amount} denominator The denominator (bottom half) of the fraction.\r\n * @return {Amount} The resulting ratio. Unit will be the same as numerator.\r\n */\r\nAmount.prototype.ratio_human = function (denominator) {\r\n if (\"number\" === typeof denominator && parseInt(denominator) === denominator) {\r\n // Special handling of integer arguments\r\n denominator = Amount.from_json(\"\" + denominator + \".0\");\r\n } else {\r\n denominator = Amount.from_json(denominator);\r\n }\r\n\r\n var numerator = this;\r\n denominator = Amount.from_json(denominator);\r\n\r\n // If either operand is NaN, the result is NaN.\r\n if (!numerator.is_valid() || !denominator.is_valid()) {\r\n return Amount.NaN();\r\n }\r\n\r\n // Special case: The denominator is a native (XRP) amount.\r\n //\r\n // In that case, it's going to be expressed as base units (1 XRP =\r\n // 10^xns_precision base units).\r\n //\r\n // However, the unit of the denominator is lost, so when the resulting ratio\r\n // is printed, the ratio is going to be too small by a factor of\r\n // 10^xns_precision.\r\n //\r\n // To compensate, we multiply the numerator by 10^xns_precision.\r\n if (denominator._is_native) {\r\n numerator = numerator.clone();\r\n numerator._value = numerator._value.multiply(consts.bi_xns_unit);\r\n numerator.canonicalize();\r\n }\r\n\r\n return numerator.divide(denominator);\r\n};\r\n\r\n/**\r\n * Calculate a product of two amounts.\r\n *\r\n * This function allows you to calculate a product between two amounts which\r\n * retains XRPs human/external interpretation (i.e. 1 XRP = 1,000,000 base\r\n * units).\r\n *\r\n * Intended use is to calculate something like: 10 USD * 10 XRP/USD = 100 XRP\r\n *\r\n * @example\r\n * var sell_amount = buy_amount.product_human(price);\r\n *\r\n * @see Amount#ratio_human\r\n *\r\n * @this {Amount} The first factor of the product.\r\n * @param {Amount} factor The second factor of the product.\r\n * @return {Amount} The product. Unit will be the same as the first factor.\r\n */\r\nAmount.prototype.product_human = function (factor) {\r\n if (\"number\" === typeof factor && parseInt(factor) === factor) {\r\n // Special handling of integer arguments\r\n factor = Amount.from_json(\"\" + factor + \".0\");\r\n } else {\r\n factor = Amount.from_json(factor);\r\n }\r\n\r\n // If either operand is NaN, the result is NaN.\r\n if (!this.is_valid() || !factor.is_valid()) {\r\n return Amount.NaN();\r\n }\r\n\r\n var product = this.multiply(factor);\r\n\r\n // Special case: The second factor is a native (XRP) amount expressed as base\r\n // units (1 XRP = 10^xns_precision base units).\r\n //\r\n // See also Amount#ratio_human.\r\n if (factor._is_native) {\r\n product._value = product._value.divide(consts.bi_xns_unit);\r\n product.canonicalize();\r\n }\r\n\r\n return product;\r\n}\r\n\r\n// True if Amounts are valid and both native or non-native.\r\nAmount.prototype.is_comparable = function (v) {\r\n return this._value instanceof BigInteger\r\n && v._value instanceof BigInteger\r\n && this._is_native === v._is_native;\r\n};\r\n\r\nAmount.prototype.is_native = function () {\r\n return this._is_native;\r\n};\r\n\r\nAmount.prototype.is_negative = function () {\r\n return this._value instanceof BigInteger\r\n ? this._is_negative\r\n : false; // NaN is not negative\r\n};\r\n\r\nAmount.prototype.is_positive = function () {\r\n return !this.is_zero() && !this.is_negative();\r\n};\r\n\r\n// Only checks the value. Not the currency and issuer.\r\nAmount.prototype.is_valid = function () {\r\n return this._value instanceof BigInteger;\r\n};\r\n\r\nAmount.prototype.is_valid_full = function () {\r\n return this.is_valid() && this._currency.is_valid() && this._issuer.is_valid();\r\n};\r\n\r\nAmount.prototype.is_zero = function () {\r\n return this._value instanceof BigInteger\r\n ? this._value.equals(BigInteger.ZERO)\r\n : false;\r\n};\r\n\r\nAmount.prototype.issuer = function () {\r\n return this._issuer;\r\n};\r\n\r\n// Result in terms of this' currency and issuer.\r\n// XXX Diverges from cpp.\r\nAmount.prototype.multiply = function (v) {\r\n var result;\r\n\r\n if (this.is_zero()) {\r\n result = this;\r\n }\r\n else if (v.is_zero()) {\r\n result = this.clone();\r\n result._value = BigInteger.ZERO;\r\n }\r\n else {\r\n var v1 = this._value;\r\n var o1 = this._offset;\r\n var v2 = v._value;\r\n var o2 = v._offset;\r\n\r\n if (this.is_native()) {\r\n while (v1.compareTo(consts.bi_man_min_value) < 0) {\r\n v1 = v1.multiply(consts.bi_10);\r\n o1 -= 1;\r\n }\r\n }\r\n\r\n if (v.is_native()) {\r\n while (v2.compareTo(consts.bi_man_min_value) < 0) {\r\n v2 = v2.multiply(consts.bi_10);\r\n o2 -= 1;\r\n }\r\n }\r\n\r\n result = new Amount();\r\n result._offset = o1 + o2 + 14;\r\n result._value = v1.multiply(v2).divide(consts.bi_1e14).add(consts.bi_7);\r\n result._is_native = this._is_native;\r\n result._is_negative = this._is_negative !== v._is_negative;\r\n result._currency = this._currency;\r\n result._issuer = this._issuer;\r\n\r\n result.canonicalize();\r\n }\r\n\r\n return result;\r\n};\r\n\r\n// Return a new value.\r\nAmount.prototype.negate = function () {\r\n return this.clone('NEGATE');\r\n};\r\n\r\n/**\r\n * Invert this amount and return the new value.\r\n *\r\n * Creates a new Amount object as a copy of the current one (including the same\r\n * unit (currency & issuer), inverts it (1/x) and returns the result.\r\n */\r\nAmount.prototype.invert = function () {\r\n var one = this.clone();\r\n one._value = BigInteger.ONE;\r\n one._offset = 0;\r\n one._is_negative = false;\r\n one.canonicalize();\r\n return one.ratio_human(this);\r\n};\r\n\r\n/**\r\n * Tries to correctly interpret an amount as entered by a user.\r\n *\r\n * Examples:\r\n *\r\n * XRP 250 => 250000000/XRP\r\n * 25.2 XRP => 25200000/XRP\r\n * USD 100.40 => 100.4/USD/?\r\n * 100 => 100000000/XRP\r\n */\r\nAmount.prototype.parse_human = function (j) {\r\n // Cast to string\r\n j = \"\"+j;\r\n\r\n // Parse\r\n var m = j.match(/^\\s*([a-z]{3})?\\s*(-)?(\\d+)(?:\\.(\\d*))?\\s*([a-z]{3})?\\s*$/i);\r\n\r\n if (m) {\r\n var currency = m[1] || m[5] || \"XRP\",\r\n integer = m[3] || \"0\",\r\n fraction = m[4] || \"\",\r\n precision = null;\r\n\r\n currency = currency.toUpperCase();\r\n\r\n this._value = new BigInteger(integer);\r\n this.set_currency(currency);\r\n\r\n // XRP have exactly six digits of precision\r\n if (currency === 'XRP') {\r\n fraction = fraction.slice(0, 6);\r\n while (fraction.length < 6) {\r\n fraction += \"0\";\r\n }\r\n this._is_native = true;\r\n this._value = this._value.multiply(consts.bi_xns_unit).add(new BigInteger(fraction));\r\n }\r\n // Other currencies have arbitrary precision\r\n else {\r\n while (fraction[fraction.length - 1] === \"0\") {\r\n fraction = fraction.slice(0, fraction.length - 1);\r\n }\r\n\r\n precision = fraction.length;\r\n\r\n this._is_native = false;\r\n var multiplier = consts.bi_10.clone().pow(precision);\r\n this._value \t= this._value.multiply(multiplier).add(new BigInteger(fraction));\r\n this._offset \t= -precision;\r\n\r\n this.canonicalize();\r\n }\r\n\r\n this._is_negative = !!m[2];\r\n } else {\r\n this._value\t = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nAmount.prototype.parse_issuer = function (issuer) {\r\n this._issuer = UInt160.from_json(issuer);\r\n\r\n return this;\r\n};\r\n\r\n// --> h: 8 hex bytes quality or 32 hex bytes directory index.\r\nAmount.prototype.parse_quality = function (q, c, i) {\r\n this._is_negative = false;\r\n this._value = new BigInteger(q.substring(q.length-14), 16);\r\n this._offset = parseInt(q.substring(q.length-16, q.length-14), 16)-100;\r\n this._currency = Currency.from_json(c);\r\n this._issuer = UInt160.from_json(i);\r\n this._is_native = this._currency.is_native();\r\n\r\n this.canonicalize();\r\n\r\n return this;\r\n}\r\n\r\nAmount.prototype.parse_number = function (n) {\r\n this._is_native = false;\r\n this._currency = Currency.from_json(1);\r\n this._issuer = UInt160.from_json(1);\r\n this._is_negative = n < 0 ? 1 : 0;\r\n this._value = new BigInteger(String(this._is_negative ? -n : n));\r\n this._offset = 0;\r\n\r\n this.canonicalize();\r\n\r\n return this;\r\n};\r\n\r\n// <-> j\r\nAmount.prototype.parse_json = function (j) {\r\n if ('string' === typeof j) {\r\n // .../.../... notation is not a wire format. But allowed for easier testing.\r\n var m = j.match(/^([^/]+)\\/(...)(?:\\/(.+))?$/);\r\n\r\n if (m) {\r\n this._currency = Currency.from_json(m[2]);\r\n if (m[3]) {\r\n this._issuer = UInt160.from_json(m[3]);\r\n } else {\r\n this._issuer = UInt160.from_json('1');\r\n }\r\n this.parse_value(m[1]);\r\n }\r\n else {\r\n this.parse_native(j);\r\n this._currency = Currency.from_json(\"0\");\r\n this._issuer = UInt160.from_json(\"0\");\r\n }\r\n }\r\n else if ('number' === typeof j) {\r\n this.parse_json(\"\"+j);\r\n }\r\n else if ('object' === typeof j && j instanceof Amount) {\r\n j.copyTo(this);\r\n }\r\n else if ('object' === typeof j && 'value' in j) {\r\n // Parse the passed value to sanitize and copy it.\r\n\r\n this._currency.parse_json(j.currency); // Never XRP.\r\n if (\"string\" === typeof j.issuer) this._issuer.parse_json(j.issuer);\r\n this.parse_value(j.value);\r\n }\r\n else {\r\n this._value\t = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\n// Parse a XRP value from untrusted input.\r\n// - integer = raw units\r\n// - float = with precision 6\r\n// XXX Improvements: disallow leading zeros.\r\nAmount.prototype.parse_native = function (j) {\r\n var m;\r\n\r\n if ('string' === typeof j)\r\n m = j.match(/^(-?)(\\d*)(\\.\\d{0,6})?$/);\r\n\r\n if (m) {\r\n if (undefined === m[3]) {\r\n // Integer notation\r\n\r\n this._value\t = new BigInteger(m[2]);\r\n }\r\n else {\r\n // Float notation : values multiplied by 1,000,000.\r\n\r\n var int_part\t = (new BigInteger(m[2])).multiply(consts.bi_xns_unit);\r\n var fraction_part = (new BigInteger(m[3])).multiply(new BigInteger(String(Math.pow(10, 1+consts.xns_precision-m[3].length))));\r\n\r\n this._value\t = int_part.add(fraction_part);\r\n }\r\n\r\n this._is_native = true;\r\n this._offset = 0;\r\n this._is_negative = !!m[1] && this._value.compareTo(BigInteger.ZERO) !== 0;\r\n\r\n if (this._value.compareTo(consts.bi_xns_max) > 0)\r\n {\r\n this._value\t = NaN;\r\n }\r\n }\r\n else {\r\n this._value\t = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\n// Parse a non-native value for the json wire format.\r\n// Requires _currency to be set!\r\nAmount.prototype.parse_value = function (j) {\r\n this._is_native = false;\r\n\r\n if ('number' === typeof j) {\r\n this._is_negative = j < 0;\r\n this._value\t = new BigInteger(Math.abs(j));\r\n this._offset = 0;\r\n\r\n this.canonicalize();\r\n }\r\n else if ('string' === typeof j) {\r\n var\ti = j.match(/^(-?)(\\d+)$/);\r\n var\td = !i && j.match(/^(-?)(\\d*)\\.(\\d*)$/);\r\n var\te = !e && j.match(/^(-?)(\\d*)e(-?\\d+)$/);\r\n\r\n if (e) {\r\n // e notation\r\n\r\n this._value\t= new BigInteger(e[2]);\r\n this._offset \t= parseInt(e[3]);\r\n this._is_negative\t= !!e[1];\r\n\r\n this.canonicalize();\r\n }\r\n else if (d) {\r\n // float notation\r\n\r\n var integer\t= new BigInteger(d[2]);\r\n var fraction \t= new BigInteger(d[3]);\r\n var precision\t= d[3].length;\r\n\r\n this._value \t= integer.multiply(consts.bi_10.clone().pow(precision)).add(fraction);\r\n this._offset \t= -precision;\r\n this._is_negative = !!d[1];\r\n\r\n this.canonicalize();\r\n }\r\n else if (i) {\r\n // integer notation\r\n\r\n this._value\t= new BigInteger(i[2]);\r\n this._offset \t= 0;\r\n this._is_negative = !!i[1];\r\n\r\n this.canonicalize();\r\n }\r\n else {\r\n this._value\t= NaN;\r\n }\r\n }\r\n else if (j instanceof BigInteger) {\r\n this._value\t = j;\r\n }\r\n else {\r\n this._value\t = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nAmount.prototype.set_currency = function (c) {\r\n this._currency = Currency.from_json(c);\r\n this._is_native = this._currency.is_native();\r\n\r\n return this;\r\n};\r\n\r\nAmount.prototype.set_issuer = function (issuer) {\r\n if (issuer instanceof UInt160) {\r\n this._issuer = issuer;\r\n } else {\r\n this._issuer = UInt160.from_json(issuer);\r\n }\r\n\r\n return this;\r\n};\r\n\r\n// Result in terms of this' currency and issuer.\r\nAmount.prototype.subtract = function (v) {\r\n // Correctness over speed, less code has less bugs, reuse add code.\r\n return this.add(Amount.from_json(v).negate());\r\n};\r\n\r\nAmount.prototype.to_number = function (allow_nan) {\r\n var s = this.to_text(allow_nan);\r\n\r\n return ('string' === typeof s) ? Number(s) : s;\r\n}\r\n\r\n// Convert only value to JSON wire format.\r\nAmount.prototype.to_text = function (allow_nan) {\r\n if (!(this._value instanceof BigInteger)) {\r\n // Never should happen.\r\n return allow_nan ? NaN : \"0\";\r\n }\r\n else if (this._is_native) {\r\n if (this._value.compareTo(consts.bi_xns_max) > 0)\r\n {\r\n // Never should happen.\r\n return allow_nan ? NaN : \"0\";\r\n }\r\n else\r\n {\r\n return (this._is_negative ? \"-\" : \"\") + this._value.toString();\r\n }\r\n }\r\n else if (this.is_zero())\r\n {\r\n return \"0\";\r\n }\r\n else if (this._offset && (this._offset < -25 || this._offset > -4))\r\n {\r\n // Use e notation.\r\n // XXX Clamp output.\r\n\r\n return (this._is_negative ? \"-\" : \"\") + this._value.toString() + \"e\" + this._offset;\r\n }\r\n else\r\n {\r\n var val = \"000000000000000000000000000\" + this._value.toString() + \"00000000000000000000000\";\r\n var\tpre = val.substring(0, this._offset + 43);\r\n var\tpost = val.substring(this._offset + 43);\r\n var\ts_pre = pre.match(/[1-9].*$/);\t // Everything but leading zeros.\r\n var\ts_post = post.match(/[1-9]0*$/); // Last non-zero plus trailing zeros.\r\n\r\n return (this._is_negative ? \"-\" : \"\")\r\n + (s_pre ? s_pre[0] : \"0\")\r\n + (s_post ? \".\" + post.substring(0, 1+post.length-s_post[0].length) : \"\");\r\n }\r\n};\r\n\r\n/**\r\n * Format only value in a human-readable format.\r\n *\r\n * @example\r\n * var pretty = amount.to_human({precision: 2});\r\n *\r\n * @param opts Options for formatter.\r\n * @param opts.precision {Number} Max. number of digits after decimal point.\r\n * @param opts.min_precision {Number} Min. number of digits after dec. point.\r\n * @param opts.skip_empty_fraction {Boolean} Don't show fraction if it is zero,\r\n * even if min_precision is set.\r\n * @param opts.max_sig_digits {Number} Maximum number of significant digits.\r\n * Will cut fractional part, but never integer part.\r\n * @param opts.group_sep {Boolean|String} Whether to show a separator every n\r\n * digits, if a string, that value will be used as the separator. Default: \",\"\r\n * @param opts.group_width {Number} How many numbers will be grouped together,\r\n * default: 3.\r\n * @param opts.signed {Boolean|String} Whether negative numbers will have a\r\n * prefix. If String, that string will be used as the prefix. Default: \"-\"\r\n */\r\nAmount.prototype.to_human = function (opts)\r\n{\r\n opts = opts || {};\r\n\r\n if (!this.is_valid()) return \"\";\r\n\r\n // Default options\r\n if (\"undefined\" === typeof opts.signed) opts.signed = true;\r\n if (\"undefined\" === typeof opts.group_sep) opts.group_sep = true;\r\n opts.group_width = opts.group_width || 3;\r\n\r\n var order = this._is_native ? consts.xns_precision : -this._offset;\r\n var denominator = consts.bi_10.clone().pow(order);\r\n var int_part = this._value.divide(denominator).toString(10);\r\n var fraction_part = this._value.mod(denominator).toString(10);\r\n\r\n // Add leading zeros to fraction\r\n while (fraction_part.length < order) {\r\n fraction_part = \"0\" + fraction_part;\r\n }\r\n\r\n int_part = int_part.replace(/^0*/, '');\r\n fraction_part = fraction_part.replace(/0*$/, '');\r\n\r\n if (fraction_part.length || !opts.skip_empty_fraction) {\r\n // Enforce the maximum number of decimal digits (precision)\r\n if (\"number\" === typeof opts.precision) {\r\n fraction_part = fraction_part.slice(0, opts.precision);\r\n }\r\n\r\n // Limit the number of significant digits (max_sig_digits)\r\n if (\"number\" === typeof opts.max_sig_digits) {\r\n // First, we count the significant digits we have.\r\n // A zero in the integer part does not count.\r\n var int_is_zero = +int_part === 0;\r\n var digits = int_is_zero ? 0 : int_part.length;\r\n\r\n // Don't count leading zeros in the fractional part if the integer part is\r\n // zero.\r\n var sig_frac = int_is_zero ? fraction_part.replace(/^0*/, '') : fraction_part;\r\n digits += sig_frac.length;\r\n\r\n // Now we calculate where we are compared to the maximum\r\n var rounding = digits - opts.max_sig_digits;\r\n\r\n // If we're under the maximum we want to cut no (=0) digits\r\n rounding = Math.max(rounding, 0);\r\n\r\n // If we're over the maximum we still only want to cut digits from the\r\n // fractional part, not from the integer part.\r\n rounding = Math.min(rounding, fraction_part.length);\r\n\r\n // Now we cut `rounding` digits off the right.\r\n if (rounding > 0) fraction_part = fraction_part.slice(0, -rounding);\r\n }\r\n\r\n // Enforce the minimum number of decimal digits (min_precision)\r\n if (\"number\" === typeof opts.min_precision) {\r\n while (fraction_part.length < opts.min_precision) {\r\n fraction_part += \"0\";\r\n }\r\n }\r\n }\r\n\r\n if (opts.group_sep) {\r\n if (\"string\" !== typeof opts.group_sep) {\r\n opts.group_sep = ',';\r\n }\r\n int_part = utils.chunkString(int_part, opts.group_width, true).join(opts.group_sep);\r\n }\r\n\r\n var formatted = '';\r\n if (opts.signed && this._is_negative) {\r\n if (\"string\" !== typeof opts.signed) {\r\n opts.signed = '-';\r\n }\r\n formatted += opts.signed;\r\n }\r\n formatted += int_part.length ? int_part : '0';\r\n formatted += fraction_part.length ? '.'+fraction_part : '';\r\n\r\n return formatted;\r\n};\r\n\r\nAmount.prototype.to_human_full = function (opts) {\r\n opts = opts || {};\r\n\r\n var a = this.to_human(opts);\r\n var c = this._currency.to_human();\r\n var i = this._issuer.to_json(opts);\r\n\r\n var o;\r\n\r\n if (this._is_native)\r\n {\r\n o = a + \"/\" + c;\r\n }\r\n else\r\n {\r\n o = a + \"/\" + c + \"/\" + i;\r\n }\r\n\r\n return o;\r\n};\r\n\r\nAmount.prototype.to_json = function () {\r\n if (this._is_native) {\r\n return this.to_text();\r\n }\r\n else\r\n {\r\n var amount_json = {\r\n 'value' : this.to_text(),\r\n 'currency' : this._currency.to_json()\r\n };\r\n if (this._issuer.is_valid()) {\r\n amount_json.issuer = this._issuer.to_json();\r\n }\r\n return amount_json;\r\n }\r\n};\r\n\r\nAmount.prototype.to_text_full = function (opts) {\r\n return this._value instanceof BigInteger\r\n ? this._is_native\r\n ? this.to_human() + \"/XRP\"\r\n : this.to_text() + \"/\" + this._currency.to_json() + \"/\" + this._issuer.to_json(opts)\r\n : NaN;\r\n};\r\n\r\n// For debugging.\r\nAmount.prototype.not_equals_why = function (d, ignore_issuer) {\r\n if (\"string\" === typeof d) {\r\n return this.not_equals_why(Amount.from_json(d));\r\n }\r\n\r\n if (this === d) return false;\r\n\r\n if (d instanceof Amount) {\r\n if (!this.is_valid() || !d.is_valid()) return \"Invalid amount.\";\r\n if (this._is_native !== d._is_native) return \"Native mismatch.\";\r\n\r\n var type = this._is_native ? \"XRP\" : \"Non-XRP\";\r\n\r\n if (!this._value.equals(d._value) || this._offset !== d._offset) {\r\n return type+\" value differs.\";\r\n }\r\n\r\n if (this._is_negative !== d._is_negative) return type+\" sign differs.\";\r\n\r\n if (!this._is_native) {\r\n if (!this._currency.equals(d._currency)) return \"Non-XRP currency differs.\";\r\n if (!ignore_issuer && !this._issuer.equals(d._issuer)) {\r\n return \"Non-XRP issuer differs: \" + d._issuer.to_json() + \"/\" + this._issuer.to_json();\r\n }\r\n }\r\n return false;\r\n } else return \"Wrong constructor.\";\r\n};\r\n\r\nexports.Amount\t = Amount;\r\n\r\n// DEPRECATED: Include the corresponding files instead.\r\nexports.Currency = Currency;\r\nexports.Seed = Seed;\r\nexports.UInt160\t = UInt160;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 2\n// module.readableIdentifier = ./src/js/ripple/amount.js\n//@ sourceURL=webpack-module:///./src/js/ripple/amount.js");
/***/ },
/***/ 3:
/***/ function(module, exports, require) {
eval("\r\n//\r\n// Currency support\r\n//\r\n\r\n// XXX Internal form should be UInt160.\r\nvar Currency = function () {\r\n // Internal form: 0 = XRP. 3 letter-code.\r\n // XXX Internal should be 0 or hex with three letter annotation when valid.\r\n\r\n // Json form:\r\n // '', 'XRP', '0': 0\r\n // 3-letter code: ...\r\n // XXX Should support hex, C++ doesn't currently allow it.\r\n\r\n this._value = NaN;\r\n}\r\n\r\n// Given \"USD\" return the json.\r\nCurrency.json_rewrite = function (j) {\r\n return Currency.from_json(j).to_json();\r\n};\r\n\r\nCurrency.from_json = function (j) {\r\n if (j instanceof Currency) {\r\n return j.clone();\r\n } else {\r\n return new Currency().parse_json(j);\r\n }\r\n};\r\n\r\nCurrency.from_bytes = function (j) {\r\n if (j instanceof Currency) {\r\n return j.clone();\r\n } else {\r\n return new Currency().parse_bytes(j);\r\n }\r\n};\r\n\r\nCurrency.is_valid = function (j) {\r\n return Currency.from_json(j).is_valid();\r\n};\r\n\r\nCurrency.prototype.clone = function() {\r\n return this.copyTo(new Currency());\r\n};\r\n\r\n// Returns copy.\r\nCurrency.prototype.copyTo = function (d) {\r\n d._value = this._value;\r\n\r\n return d;\r\n};\r\n\r\nCurrency.prototype.equals = function (d) {\r\n return ('string' !== typeof this._value && isNaN(this._value))\r\n || ('string' !== typeof d._value && isNaN(d._value)) ? false : this._value === d._value;\r\n};\r\n\r\n// this._value = NaN on error.\r\nCurrency.prototype.parse_json = function (j) {\r\n if (j instanceof Currency) {\r\n this._value = j;\r\n } else if ('string' === typeof j) {\r\n if (j === \"\" || j === \"0\" || j === \"XRP\") {\r\n // XRP is never allowed as a Currency object\r\n this._value = 0;\r\n } else if (j.length === 3) {\r\n this._value = j;\r\n } else {\r\n this._value = NaN;\r\n }\r\n } else if ('number' === typeof j) {\r\n // XXX This is a hack\r\n this._value = j;\r\n } else if ('string' != typeof j || 3 !== j.length) {\r\n this._value = NaN;\r\n } else {\r\n this._value = j;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nCurrency.prototype.parse_bytes = function (byte_array) {\r\n if (Array.isArray(byte_array) && byte_array.length == 20) {\r\n var result;\r\n // is it 0 everywhere except 12, 13, 14?\r\n var isZeroExceptInStandardPositions = true;\r\n for (var i=0; i<20; i++) {\r\n isZeroExceptInStandardPositions = isZeroExceptInStandardPositions && (i===12 || i===13 || i===14 || byte_array[0]===0)\r\n }\r\n if (isZeroExceptInStandardPositions) {\r\n var currencyCode = String.fromCharCode(byte_array[12]) + String.fromCharCode(byte_array[13]) + String.fromCharCode(byte_array[14]);\r\n if (/^[A-Z0-9]{3}$/.test(currencyCode) && currencyCode !== \"XRP\" ) {\r\n this._value = currencyCode;\r\n } else if (currencyCode === \"\\0\\0\\0\") {\r\n this._value = 0;\r\n } else {\r\n this._value = NaN;\r\n }\r\n } else {\r\n // XXX Should support non-standard currency codes\r\n this._value = NaN;\r\n }\r\n } else {\r\n this._value = NaN;\r\n }\r\n return this;\r\n};\r\n\r\nCurrency.prototype.is_native = function () {\r\n return !isNaN(this._value) && !this._value;\r\n};\r\n\r\nCurrency.prototype.is_valid = function () {\r\n return 'string' === typeof this._value || !isNaN(this._value);\r\n};\r\n\r\nCurrency.prototype.to_json = function () {\r\n return this._value ? this._value : \"XRP\";\r\n};\r\n\r\nCurrency.prototype.to_human = function () {\r\n return this._value ? this._value : \"XRP\";\r\n};\r\n\r\nexports.Currency = Currency;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 3\n// module.readableIdentifier = ./src/js/ripple/currency.js\n//@ sourceURL=webpack-module:///./src/js/ripple/currency.js");
/***/ },
/***/ 4:
/***/ function(module, exports, require) {
eval("\r\nvar sjcl = require(10);\r\nvar utils = require(9);\r\nvar jsbn = require(20);\r\nvar extend = require(29);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\nvar nbi = jsbn.nbi;\r\n\r\nvar Base = {};\r\n\r\nvar alphabets\t= Base.alphabets = {\r\n 'ripple' : \"rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz\",\r\n 'tipple' : \"RPShNAF39wBUDnEGHJKLM4pQrsT7VWXYZ2bcdeCg65jkm8ofqi1tuvaxyz\",\r\n 'bitcoin' : \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\r\n};\r\n\r\nextend(Base, {\r\n 'VER_NONE' : 1,\r\n 'VER_NODE_PUBLIC' : 28,\r\n 'VER_NODE_PRIVATE' : 32,\r\n 'VER_ACCOUNT_ID' : 0,\r\n 'VER_ACCOUNT_PUBLIC' : 35,\r\n 'VER_ACCOUNT_PRIVATE' : 34,\r\n 'VER_FAMILY_GENERATOR' : 41,\r\n 'VER_FAMILY_SEED' : 33\r\n});\r\n\r\nvar sha256 = function (bytes) {\r\n return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));\r\n};\r\n\r\nvar sha256hash = function (bytes) {\r\n return sha256(sha256(bytes));\r\n};\r\n\r\n// --> input: big-endian array of bytes.\r\n// <-- string at least as long as input.\r\nBase.encode = function (input, alpha) {\r\n var alphabet\t= alphabets[alpha || 'ripple'];\r\n var bi_base\t= new BigInteger(String(alphabet.length));\r\n var bi_q\t= nbi();\r\n var bi_r\t= nbi();\r\n var bi_value\t= new BigInteger(input);\r\n var buffer\t= [];\r\n\r\n while (bi_value.compareTo(BigInteger.ZERO) > 0)\r\n {\r\n bi_value.divRemTo(bi_base, bi_q, bi_r);\r\n bi_q.copyTo(bi_value);\r\n\r\n buffer.push(alphabet[bi_r.intValue()]);\r\n }\r\n\r\n var i;\r\n\r\n for (i = 0; i != input.length && !input[i]; i += 1) {\r\n buffer.push(alphabet[0]);\r\n }\r\n\r\n return buffer.reverse().join(\"\");\r\n};\r\n\r\n// --> input: String\r\n// <-- array of bytes or undefined.\r\nBase.decode = function (input, alpha) {\r\n if (\"string\" !== typeof input) return undefined;\r\n\r\n var alphabet\t= alphabets[alpha || 'ripple'];\r\n var bi_base\t= new BigInteger(String(alphabet.length));\r\n var bi_value\t= nbi();\r\n var i;\r\n\r\n for (i = 0; i != input.length && input[i] === alphabet[0]; i += 1)\r\n ;\r\n\r\n for (; i != input.length; i += 1) {\r\n var\tv = alphabet.indexOf(input[i]);\r\n\r\n if (v < 0)\r\n return undefined;\r\n\r\n var r = nbi();\r\n\r\n r.fromInt(v);\r\n\r\n bi_value = bi_value.multiply(bi_base).add(r);\r\n }\r\n\r\n // toByteArray:\r\n // - Returns leading zeros!\r\n // - Returns signed bytes!\r\n var bytes = bi_value.toByteArray().map(function (b) { return b ? b < 0 ? 256+b : b : 0; });\r\n var extra = 0;\r\n\r\n while (extra != bytes.length && !bytes[extra])\r\n extra += 1;\r\n\r\n if (extra)\r\n bytes = bytes.slice(extra);\r\n\r\n var zeros = 0;\r\n\r\n while (zeros !== input.length && input[zeros] === alphabet[0])\r\n zeros += 1;\r\n\r\n return [].concat(utils.arraySet(zeros, 0), bytes);\r\n};\r\n\r\nBase.verify_checksum = function (bytes) {\r\n var computed\t= sha256hash(bytes.slice(0, -4)).slice(0, 4);\r\n var checksum\t= bytes.slice(-4);\r\n\r\n for (var i = 0; i < 4; i++)\r\n if (computed[i] !== checksum[i])\r\n return false;\r\n\r\n return true;\r\n};\r\n\r\n// --> input: Array\r\n// <-- String\r\nBase.encode_check = function (version, input, alphabet) {\r\n var buffer = [].concat(version, input);\r\n var check = sha256(sha256(buffer)).slice(0, 4);\r\n\r\n return Base.encode([].concat(buffer, check), alphabet);\r\n}\r\n\r\n// --> input : String\r\n// <-- NaN || BigInteger\r\nBase.decode_check = function (version, input, alphabet) {\r\n var buffer = Base.decode(input, alphabet);\r\n\r\n if (!buffer || buffer.length < 5)\r\n return NaN;\r\n\r\n // Single valid version\r\n if (\"number\" === typeof version && buffer[0] !== version)\r\n return NaN;\r\n\r\n // Multiple allowed versions\r\n if (\"object\" === typeof version && Array.isArray(version)) {\r\n var match = false;\r\n for (var i = 0, l = version.length; i < l; i++) {\r\n match |= version[i] === buffer[0];\r\n }\r\n if (!match) return NaN;\r\n }\r\n\r\n if (!Base.verify_checksum(buffer))\r\n return NaN;\r\n\r\n // We'll use the version byte to add a leading zero, this ensures JSBN doesn't\r\n // intrepret the value as a negative number\r\n buffer[0] = 0;\r\n\r\n return new BigInteger(buffer.slice(0, -4), 256);\r\n}\r\n\r\nexports.Base = Base;\r\n\n\n// WEBPACK FOOTER\n// module.id = 4\n// module.readableIdentifier = ./src/js/ripple/base.js\n//@ sourceURL=webpack-module:///./src/js/ripple/base.js");
/***/ },
/***/ 5:
/***/ function(module, exports, require) {
eval("// Transactions\r\n//\r\n// Construction:\r\n// remote.transaction() // Build a transaction object.\r\n// .offer_create(...) // Set major parameters.\r\n// .set_flags() // Set optional parameters.\r\n// .on() // Register for events.\r\n// .submit(); // Send to network.\r\n//\r\n// Events:\r\n// 'success' : Transaction submitted without error.\r\n// 'error' : Error submitting transaction.\r\n// 'proposed' : Advisory proposed status transaction.\r\n// - A client should expect 0 to multiple results.\r\n// - Might not get back. The remote might just forward the transaction.\r\n// - A success could be reverted in final.\r\n// - local error: other remotes might like it.\r\n// - malformed error: local server thought it was malformed.\r\n// - The client should only trust this when talking to a trusted server.\r\n// 'final' : Final status of transaction.\r\n// - Only expect a final from dishonest servers after a tesSUCCESS or ter*.\r\n// 'lost' : Gave up looking for on ledger_closed.\r\n// 'pending' : Transaction was not found on ledger_closed.\r\n// 'state' : Follow the state of a transaction.\r\n// 'client_submitted' - Sent to remote\r\n// |- 'remoteError' - Remote rejected transaction.\r\n// \\- 'client_proposed' - Remote provisionally accepted transaction.\r\n// |- 'client_missing' - Transaction has not appeared in ledger as expected.\r\n// | |\\- 'client_lost' - No longer monitoring missing transaction.\r\n// |/\r\n// |- 'tesSUCCESS' - Transaction in ledger as expected.\r\n// |- 'ter...' - Transaction failed.\r\n// \\- 'tec...' - Transaction claimed fee only.\r\n//\r\n// Notes:\r\n// - All transactions including those with local and malformed errors may be\r\n// forwarded anyway.\r\n// - A malicous server can:\r\n// - give any proposed result.\r\n// - it may declare something correct as incorrect or something correct as incorrect.\r\n// - it may not communicate with the rest of the network.\r\n// - may or may not forward.\r\n//\r\n\r\nvar EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\n\r\nvar sjcl = require(10);\r\n\r\nvar Amount = require(2).Amount;\r\nvar Currency = require(2).Currency;\r\nvar UInt160 = require(2).UInt160;\r\nvar Seed = require(21).Seed;\r\nvar SerializedObject = require(7).SerializedObject;\r\nvar RippleError = require(19).RippleError;\r\n\r\nvar config = require(12);\r\n\r\n// A class to implement transactions.\r\n// - Collects parameters\r\n// - Allow event listeners to be attached to determine the outcome.\r\nfunction Transaction(remote) {\r\n EventEmitter.call(this);\r\n\r\n var self = this;\r\n\r\n this.remote = remote;\r\n this._secret = void(0);\r\n this._build_path = false;\r\n\r\n // Transaction data.\r\n this.tx_json = { Flags: 0 };\r\n\r\n this.hash = void(0);\r\n\r\n // ledger_current_index was this when transaction was submited.\r\n this.submit_index = void(0);\r\n\r\n // Under construction.\r\n this.state = void(0);\r\n\r\n this.finalized = false;\r\n this._previous_signing_hash = void(0);\r\n};\r\n\r\nutil.inherits(Transaction, EventEmitter);\r\n\r\n// XXX This needs to be determined from the network.\r\nTransaction.fee_units = {\r\n default: 10,\r\n};\r\n\r\nTransaction.flags = {\r\n AccountSet: {\r\n RequireDestTag: 0x00010000,\r\n OptionalDestTag: 0x00020000,\r\n RequireAuth: 0x00040000,\r\n OptionalAuth: 0x00080000,\r\n DisallowXRP: 0x00100000,\r\n AllowXRP: 0x00200000\r\n },\r\n\r\n OfferCreate: {\r\n Passive: 0x00010000,\r\n ImmediateOrCancel: 0x00020000,\r\n FillOrKill: 0x00040000,\r\n Sell: 0x00080000\r\n },\r\n\r\n Payment: {\r\n NoRippleDirect: 0x00010000,\r\n PartialPayment: 0x00020000,\r\n LimitQuality: 0x00040000\r\n },\r\n};\r\n\r\nTransaction.formats = require(8).tx;\r\n\r\nTransaction.HASH_SIGN = 0x53545800;\r\nTransaction.HASH_SIGN_TESTNET = 0x73747800;\r\n\r\nTransaction.prototype.consts = {\r\n telLOCAL_ERROR : -399,\r\n temMALFORMED : -299,\r\n tefFAILURE : -199,\r\n terRETRY : -99,\r\n tesSUCCESS : 0,\r\n tecCLAIMED : 100,\r\n};\r\n\r\nTransaction.prototype.isTelLocal = function (ter) {\r\n return ter >= this.consts.telLOCAL_ERROR && ter < this.consts.temMALFORMED;\r\n};\r\n\r\nTransaction.prototype.isTemMalformed = function (ter) {\r\n return ter >= this.consts.temMALFORMED && ter < this.consts.tefFAILURE;\r\n};\r\n\r\nTransaction.prototype.isTefFailure = function (ter) {\r\n return ter >= this.consts.tefFAILURE && ter < this.consts.terRETRY;\r\n};\r\n\r\nTransaction.prototype.isTerRetry = function (ter) {\r\n return ter >= this.consts.terRETRY && ter < this.consts.tesSUCCESS;\r\n};\r\n\r\nTransaction.prototype.isTepSuccess = function (ter) {\r\n return ter >= this.consts.tesSUCCESS;\r\n};\r\n\r\nTransaction.prototype.isTecClaimed = function (ter) {\r\n return ter >= this.consts.tecCLAIMED;\r\n};\r\n\r\nTransaction.prototype.isRejected = function (ter) {\r\n return this.isTelLocal(ter) || this.isTemMalformed(ter) || this.isTefFailure(ter);\r\n};\r\n\r\nTransaction.prototype.set_state = function (state) {\r\n if (this.state !== state) {\r\n this.state = state;\r\n this.emit('state', state);\r\n }\r\n};\r\n\r\n/**\r\n * TODO\r\n * Actually do this right\r\n */\r\n\r\nTransaction.prototype.get_fee = function() {\r\n return Transaction.fees['default'].to_json();\r\n};\r\n\r\n/**\r\n * Attempts to complete the transaction for submission.\r\n *\r\n * This function seeks to fill out certain fields, such as Fee and\r\n * SigningPubKey, which can be determined by the library based on network\r\n * information and other fields.\r\n */\r\nTransaction.prototype.complete = function () {\r\n if (this.remote && typeof this.tx_json.Fee === 'undefined') {\r\n if (this.remote.local_fee || !this.remote.trusted) {\r\n this.tx_json.Fee = this.remote.fee_tx(this.fee_units()).to_json();\r\n }\r\n }\r\n\r\n if (typeof this.tx_json.SigningPubKey === 'undefined' && (!this.remote || this.remote.local_signing)) {\r\n var seed = Seed.from_json(this._secret);\r\n var key = seed.get_key(this.tx_json.Account);\r\n this.tx_json.SigningPubKey = key.to_hex_pub();\r\n }\r\n\r\n return this.tx_json;\r\n};\r\n\r\nTransaction.prototype.serialize = function () {\r\n return SerializedObject.from_json(this.tx_json);\r\n};\r\n\r\nTransaction.prototype.signing_hash = function () {\r\n var prefix = Transaction[config.testnet ? 'HASH_SIGN_TESTNET' : 'HASH_SIGN'];\r\n return SerializedObject.from_json(this.tx_json).signing_hash(prefix);\r\n};\r\n\r\nTransaction.prototype.sign = function () {\r\n var seed = Seed.from_json(this._secret);\r\n var hash = this.signing_hash();\r\n\r\n var previously_signed = this.tx_json.TxnSignature\r\n && hash === this._previous_signing_hash;\r\n\r\n if (previously_signed) return;\r\n\r\n var key = seed.get_key(this.tx_json.Account);\r\n var sig = key.sign(hash, 0);\r\n var hex = sjcl.codec.hex.fromBits(sig).toUpperCase();\r\n\r\n this.tx_json.TxnSignature = hex;\r\n};\r\n\r\n//\r\n// Set options for Transactions\r\n//\r\n\r\n// --> build: true, to have server blindly construct a path.\r\n//\r\n// \"blindly\" because the sender has no idea of the actual cost except that is must be less than send max.\r\nTransaction.prototype.build_path = function (build) {\r\n this._build_path = build;\r\n return this;\r\n}\r\n\r\n// tag should be undefined or a 32 bit integer.\r\n// YYY Add range checking for tag.\r\nTransaction.prototype.destination_tag = function (tag) {\r\n if (tag !== void(0)) {\r\n this.tx_json.DestinationTag = tag;\r\n }\r\n return this;\r\n}\r\n\r\nTransaction._path_rewrite = function (path) {\r\n var path_new = path.map(function(node) {\r\n var node_new = { };\r\n\r\n if (node.hasOwnProperty('account')) {\r\n node_new.account = UInt160.json_rewrite(node.account);\r\n }\r\n\r\n if (node.hasOwnProperty('issuer')) {\r\n node_new.issuer = UInt160.json_rewrite(node.issuer);\r\n }\r\n\r\n if (node.hasOwnProperty('currency')) {\r\n node_new.currency = Currency.json_rewrite(node.currency);\r\n }\r\n\r\n return node_new;\r\n });\r\n\r\n return path_new;\r\n}\r\n\r\nTransaction.prototype.path_add = function (path) {\r\n this.tx_json.Paths = this.tx_json.Paths || [];\r\n this.tx_json.Paths.push(Transaction._path_rewrite(path));\r\n return this;\r\n}\r\n\r\n// --> paths: undefined or array of path\r\n// A path is an array of objects containing some combination of: account, currency, issuer\r\nTransaction.prototype.paths = function (paths) {\r\n for (var i=0, l=paths.length; i<l; i++) {\r\n this.path_add(paths[i]);\r\n }\r\n return this;\r\n};\r\n\r\n// If the secret is in the config object, it does not need to be provided.\r\nTransaction.prototype.secret = function (secret) {\r\n this._secret = secret;\r\n};\r\n\r\nTransaction.prototype.send_max = function (send_max) {\r\n if (send_max) {\r\n this.tx_json.SendMax = Amount.json_rewrite(send_max);\r\n }\r\n return this;\r\n};\r\n\r\n// tag should be undefined or a 32 bit integer.\r\n// YYY Add range checking for tag.\r\nTransaction.prototype.source_tag = function (tag) {\r\n if (tag) {\r\n this.tx_json.SourceTag = tag;\r\n }\r\n return this;\r\n};\r\n\r\n// --> rate: In billionths.\r\nTransaction.prototype.transfer_rate = function (rate) {\r\n this.tx_json.TransferRate = Number(rate);\r\n\r\n if (this.tx_json.TransferRate < 1e9) {\r\n throw new Error('invalidTransferRate');\r\n }\r\n\r\n return this;\r\n};\r\n\r\n// Add flags to a transaction.\r\n// --> flags: undefined, _flag_, or [ _flags_ ]\r\nTransaction.prototype.set_flags = function (flags) {\r\n if (flags) {\r\n var transaction_flags = Transaction.flags[this.tx_json.TransactionType];\r\n\r\n // We plan to not define this field on new Transaction.\r\n if (this.tx_json.Flags === void(0)) {\r\n this.tx_json.Flags = 0;\r\n }\r\n\r\n var flag_set = Array.isArray(flags) ? flags : [ flags ];\r\n\r\n for (var i=0, l=flag_set.length; i<l; i++) {\r\n var flag = flag_set[i];\r\n if (transaction_flags.hasOwnProperty(flag)) {\r\n this.tx_json.Flags += transaction_flags[flag];\r\n } else {\r\n // XXX Immediately report an error or mark it.\r\n }\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\n//\r\n// Transactions\r\n//\r\n\r\nTransaction.prototype._account_secret = function (account) {\r\n // Fill in secret from remote, if available.\r\n return this.remote.secrets[account];\r\n};\r\n\r\n// Options:\r\n// .domain() NYI\r\n// .flags()\r\n// .message_key() NYI\r\n// .transfer_rate()\r\n// .wallet_locator() NYI\r\n// .wallet_size() NYI\r\nTransaction.prototype.account_set = function (src) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Source address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'AccountSet';\r\n this.tx_json.Account = UInt160.json_rewrite(src);\r\n return this;\r\n};\r\n\r\nTransaction.prototype.claim = function (src, generator, public_key, signature) {\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'Claim';\r\n this.tx_json.Generator = generator;\r\n this.tx_json.PublicKey = public_key;\r\n this.tx_json.Signature = signature;\r\n return this;\r\n};\r\n\r\nTransaction.prototype.offer_cancel = function (src, sequence) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Source address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'OfferCancel';\r\n this.tx_json.Account = UInt160.json_rewrite(src);\r\n this.tx_json.OfferSequence = Number(sequence);\r\n return this;\r\n};\r\n\r\n// Options:\r\n// .set_flags()\r\n// --> expiration : if not undefined, Date or Number\r\n// --> cancel_sequence : if not undefined, Sequence\r\nTransaction.prototype.offer_create = function (src, taker_pays, taker_gets, expiration, cancel_sequence) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Source address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'OfferCreate';\r\n this.tx_json.Account = UInt160.json_rewrite(src);\r\n this.tx_json.TakerPays = Amount.json_rewrite(taker_pays);\r\n this.tx_json.TakerGets = Amount.json_rewrite(taker_gets);\r\n\r\n if (this.remote.local_fee) {\r\n //this.tx_json.Fee = Transaction.fees.offer.to_json();\r\n }\r\n\r\n if (expiration) {\r\n this.tx_json.Expiration = expiration instanceof Date\r\n ? expiration.getTime()\r\n : Number(expiration);\r\n }\r\n\r\n if (cancel_sequence) {\r\n this.tx_json.OfferSequence = Number(cancel_sequence);\r\n }\r\n\r\n return this;\r\n};\r\n\r\nTransaction.prototype.password_fund = function (src, dst) {\r\n if (!UInt160.is_valid(dst)) {\r\n throw new Error('Destination address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'PasswordFund';\r\n this.tx_json.Destination = UInt160.json_rewrite(dst);\r\n return this;\r\n}\r\n\r\nTransaction.prototype.password_set = function (src, authorized_key, generator, public_key, signature) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Source address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'PasswordSet';\r\n this.tx_json.RegularKey = authorized_key;\r\n this.tx_json.Generator = generator;\r\n this.tx_json.PublicKey = public_key;\r\n this.tx_json.Signature = signature;\r\n return this;\r\n}\r\n\r\n// Construct a 'payment' transaction.\r\n//\r\n// When a transaction is submitted:\r\n// - If the connection is reliable and the server is not merely forwarding and is not malicious,\r\n// --> src : UInt160 or String\r\n// --> dst : UInt160 or String\r\n// --> deliver_amount : Amount or String.\r\n//\r\n// Options:\r\n// .paths()\r\n// .build_path()\r\n// .destination_tag()\r\n// .path_add()\r\n// .secret()\r\n// .send_max()\r\n// .set_flags()\r\n// .source_tag()\r\nTransaction.prototype.payment = function (src, dst, deliver_amount) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Payment source address invalid');\r\n }\r\n\r\n if (!UInt160.is_valid(dst)) {\r\n throw new Error('Payment destination address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'Payment';\r\n this.tx_json.Account = UInt160.json_rewrite(src);\r\n this.tx_json.Amount = Amount.json_rewrite(deliver_amount);\r\n this.tx_json.Destination = UInt160.json_rewrite(dst);\r\n\r\n return this;\r\n}\r\n\r\nTransaction.prototype.ripple_line_set = function (src, limit, quality_in, quality_out) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Source address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'TrustSet';\r\n this.tx_json.Account = UInt160.json_rewrite(src);\r\n\r\n // Allow limit of 0 through.\r\n if (limit !== void(0)) {\r\n this.tx_json.LimitAmount = Amount.json_rewrite(limit);\r\n }\r\n \r\n if (quality_in) {\r\n this.tx_json.QualityIn = quality_in;\r\n }\r\n\r\n if (quality_out) {\r\n this.tx_json.QualityOut = quality_out;\r\n }\r\n\r\n // XXX Throw an error if nothing is set.\r\n\r\n return this;\r\n};\r\n\r\nTransaction.prototype.wallet_add = function (src, amount, authorized_key, public_key, signature) {\r\n if (!UInt160.is_valid(src)) {\r\n throw new Error('Source address invalid');\r\n }\r\n\r\n this._secret = this._account_secret(src);\r\n this.tx_json.TransactionType = 'WalletAdd';\r\n this.tx_json.Amount = Amount.json_rewrite(amount);\r\n this.tx_json.RegularKey = authorized_key;\r\n this.tx_json.PublicKey = public_key;\r\n this.tx_json.Signature = signature;\r\n return this;\r\n};\r\n\r\n/**\r\n * Returns the number of fee units this transaction will cost.\r\n *\r\n * Each Ripple transaction based on its type and makeup costs a certain number\r\n * of fee units. The fee units are calculated on a per-server basis based on the\r\n * current load on both the network and the server.\r\n *\r\n * @see https://ripple.com/wiki/Transaction_Fee\r\n *\r\n * @return {Number} Number of fee units for this transaction.\r\n */\r\nTransaction.prototype.fee_units = function () {\r\n return Transaction.fee_units['default'];\r\n};\r\n\r\n// Submit a transaction to the network.\r\nTransaction.prototype.submit = function (callback) {\r\n var self = this;\r\n\r\n this.callback = typeof callback === 'function' ? callback : function(){};\r\n\r\n function submission_error(error, message) {\r\n if (!(error instanceof RippleError)) {\r\n error = new RippleError(error, message);\r\n }\r\n self.callback(error);\r\n }\r\n\r\n function submission_success(message) {\r\n self.callback(null, message);\r\n }\r\n\r\n this.on('error', function(){});\r\n this.once('error', submission_error);\r\n this.once('success', submission_success);\r\n\r\n var account = this.tx_json.Account;\r\n\r\n if (typeof account !== 'string') {\r\n this.emit('error', new RippleError('tejInvalidAccount', 'Account is unspecified'));\r\n } else {\r\n // YYY Might check paths for invalid accounts.\r\n this.remote.account(account).submit(this);\r\n }\r\n\r\n return this;\r\n};\r\n\r\nTransaction.prototype.abort = function(callback) {\r\n if (!this.finalized) {\r\n var callback = typeof callback === 'function' ? callback : function(){};\r\n this.once('final', callback);\r\n this.emit('abort');\r\n }\r\n};\r\n\r\nexports.Transaction = Transaction;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 5\n// module.readableIdentifier = ./src/js/ripple/transaction.js\n//@ sourceURL=webpack-module:///./src/js/ripple/transaction.js");
/***/ },
/***/ 6:
/***/ function(module, exports, require) {
eval("var extend = require(29);\r\nvar utils = require(9);\r\nvar UInt160 = require(15).UInt160;\r\nvar Amount = require(2).Amount;\r\n\r\n/**\r\n * Meta data processing facility.\r\n */\r\nvar Meta = function (raw_data)\r\n{\r\n this.nodes = [];\r\n\r\n for (var i = 0, l = raw_data.AffectedNodes.length; i < l; i++) {\r\n var an = raw_data.AffectedNodes[i],\r\n result = {};\r\n\r\n [\"CreatedNode\", \"ModifiedNode\", \"DeletedNode\"].forEach(function (x) {\r\n if (an[x]) result.diffType = x;\r\n });\r\n\r\n if (!result.diffType) return null;\r\n\r\n an = an[result.diffType];\r\n\r\n result.entryType = an.LedgerEntryType;\r\n result.ledgerIndex = an.LedgerIndex;\r\n\r\n result.fields = extend({}, an.PreviousFields, an.NewFields, an.FinalFields);\r\n result.fieldsPrev = an.PreviousFields || {};\r\n result.fieldsNew = an.NewFields || {};\r\n result.fieldsFinal = an.FinalFields || {};\r\n\r\n this.nodes.push(result);\r\n }\r\n};\r\n\r\n/**\r\n * Execute a function on each affected node.\r\n *\r\n * The callback is passed two parameters. The first is a node object which looks\r\n * like this:\r\n *\r\n * {\r\n * // Type of diff, e.g. CreatedNode, ModifiedNode\r\n * diffType: 'CreatedNode'\r\n *\r\n * // Type of node affected, e.g. RippleState, AccountRoot\r\n * entryType: 'RippleState',\r\n *\r\n * // Index of the ledger this change occurred in\r\n * ledgerIndex: '01AB01AB...',\r\n *\r\n * // Contains all fields with later versions taking precedence\r\n * //\r\n * // This is a shorthand for doing things like checking which account\r\n * // this affected without having to check the diffType.\r\n * fields: {...},\r\n *\r\n * // Old fields (before the change)\r\n * fieldsPrev: {...},\r\n *\r\n * // New fields (that have been added)\r\n * fieldsNew: {...},\r\n *\r\n * // Changed fields\r\n * fieldsFinal: {...}\r\n * }\r\n *\r\n * The second parameter to the callback is the index of the node in the metadata\r\n * (first entry is index 0).\r\n */\r\nMeta.prototype.each = function (fn)\r\n{\r\n for (var i = 0, l = this.nodes.length; i < l; i++) {\r\n fn(this.nodes[i], i);\r\n }\r\n};\r\n\r\nvar amountFieldsAffectingIssuer = [\r\n \"LowLimit\", \"HighLimit\", \"TakerPays\", \"TakerGets\"\r\n];\r\nMeta.prototype.getAffectedAccounts = function ()\r\n{\r\n var accounts = [];\r\n\r\n // This code should match the behavior of the C++ method:\r\n // TransactionMetaSet::getAffectedAccounts\r\n this.each(function (an) {\r\n var fields = (an.diffType === \"CreatedNode\") ? an.fieldsNew : an.fieldsFinal;\r\n\r\n for (var i in fields) {\r\n var field = fields[i];\r\n\r\n if (\"string\" === typeof field && UInt160.is_valid(field)) {\r\n accounts.push(field);\r\n } else if (amountFieldsAffectingIssuer.indexOf(i) !== -1) {\r\n var amount = Amount.from_json(field);\r\n var issuer = amount.issuer();\r\n if (issuer.is_valid() && !issuer.is_zero()) {\r\n accounts.push(issuer.to_json());\r\n }\r\n }\r\n }\r\n });\r\n\r\n accounts = utils.arrayUnique(accounts);\r\n\r\n return accounts;\r\n};\r\n\r\nMeta.prototype.getAffectedBooks = function ()\r\n{\r\n var books = [];\r\n\r\n this.each(function (an) {\r\n if (an.entryType !== 'Offer') return;\r\n\r\n var gets = Amount.from_json(an.fields.TakerGets);\r\n var pays = Amount.from_json(an.fields.TakerPays);\r\n\r\n var getsKey = gets.currency().to_json();\r\n if (getsKey !== 'XRP') getsKey += '/' + gets.issuer().to_json();\r\n\r\n var paysKey = pays.currency().to_json();\r\n if (paysKey !== 'XRP') paysKey += '/' + pays.issuer().to_json();\r\n\r\n var key = getsKey + \":\" + paysKey;\r\n\r\n books.push(key);\r\n });\r\n\r\n books = utils.arrayUnique(books);\r\n\r\n return books;\r\n};\r\n\r\nexports.Meta = Meta;\r\n\n\n// WEBPACK FOOTER\n// module.id = 6\n// module.readableIdentifier = ./src/js/ripple/meta.js\n//@ sourceURL=webpack-module:///./src/js/ripple/meta.js");
/***/ },
/***/ 7:
/***/ function(module, exports, require) {
eval("/* WEBPACK VAR INJECTION */(function(require, Buffer) {var binformat = require(8),\r\n sjcl = require(10),\r\n extend = require(29),\r\n stypes = require(22);\r\n\r\nvar UInt256 = require(23).UInt256;\r\n\r\nvar SerializedObject = function (buf) {\r\n if (Array.isArray(buf) || (Buffer && Buffer.isBuffer(buf)) ) {\r\n this.buffer = buf;\r\n } else if (\"string\" === typeof buf) {\r\n this.buffer = sjcl.codec.bytes.fromBits(sjcl.codec.hex.toBits(buf));\r\n } else if (!buf) {\r\n this.buffer = [];\r\n } else {\r\n throw new Error(\"Invalid buffer passed.\");\r\n }\r\n this.pointer = 0;\r\n};\r\n\r\nSerializedObject.from_json = function (obj) {\r\n var typedef;\r\n var so = new SerializedObject();\r\n\r\n // Create a copy of the object so we don't modify it\r\n obj = extend({}, obj);\r\n\r\n if (\"number\" === typeof obj.TransactionType) {\r\n obj.TransactionType = SerializedObject.lookup_type_tx(obj.TransactionType);\r\n\r\n if (!obj.TransactionType) {\r\n throw new Error(\"Transaction type ID is invalid.\");\r\n }\r\n }\r\n\r\n if (\"string\" === typeof obj.TransactionType) {\r\n typedef = binformat.tx[obj.TransactionType].slice();\r\n\r\n obj.TransactionType = typedef.shift();\r\n } else if (\"undefined\" !== typeof obj.LedgerEntryType) {\r\n // XXX: TODO\r\n throw new Error(\"Ledger entry binary format not yet implemented.\");\r\n } else throw new Error(\"Object to be serialized must contain either \" +\r\n \"TransactionType or LedgerEntryType.\");\r\n\r\n so.serialize(typedef, obj);\r\n\r\n return so;\r\n};\r\n\r\nSerializedObject.prototype.append = function (bytes) {\r\n this.buffer = this.buffer.concat(bytes);\r\n this.pointer += bytes.length;\r\n};\r\n\r\nSerializedObject.prototype.resetPointer = function () {\r\n this.pointer = 0;\r\n};\r\n\r\n\r\nvar readOrPeek = function (advance) {\r\n return function(numberOfBytes) {\r\n\t var start = this.pointer;\r\n\t var end = start+numberOfBytes;\r\n\t if (end > this.buffer.length) {\r\n\t\tthrow new Error(\"There aren't that many bytes left.\");\r\n\t } else {\r\n\t\tvar result = this.buffer.slice(start,end);\r\n\t\tif (advance) {this.pointer = end;}\r\n\t\treturn result;\r\n\t }\r\n }\r\n}\r\nSerializedObject.prototype.read = readOrPeek(true);\r\nSerializedObject.prototype.peek = readOrPeek(false);\r\n\r\n\r\nSerializedObject.prototype.to_bits = function ()\r\n{\r\n return sjcl.codec.bytes.toBits(this.buffer);\r\n};\r\n\r\nSerializedObject.prototype.to_hex = function () {\r\n return sjcl.codec.hex.fromBits(this.to_bits()).toUpperCase();\r\n};\r\n\r\n\r\n\r\n\r\nvar TRANSACTION_TYPES = {\r\n\t0:\"Payment\",\r\n\t3:\"AccountSet\",\r\n\t5:\"SetRegularKey\",\r\n\t7:\"OfferCreate\",\r\n\t8:\"OfferCancel\",\r\n\t9:\"Contract\",\r\n\t10:\"RemoveContract\",\r\n\t20:\"TrustSet\",\r\n\t100:\"EnableFeature\",\r\n\t101:\"SetFee\"\r\n};\r\n\r\nvar LEDGER_ENTRY_TYPES = {\r\n\t97:\"AccountRoot\",\r\n\t99:\"Contract\",\r\n\t100:\"DirectoryNode\",\r\n\t102:\"Features\",\r\n\t103:\"GeneratorMap\",\r\n\t104:\"LedgerHashes\",\r\n\t110:\"Nickname\",\r\n\t111:\"Offer\",\r\n\t114:\"RippleState\",\r\n\t115:\"FeeSettings\"\r\n};\r\n\r\nvar TRANSACTION_RESULTS = {\r\n 0 :\"tesSUCCESS\",\r\n\t100:\"tecCLAIM\",\r\n\t101:\"tecPATH_PARTIAL\",\r\n\t102:\"tecUNFUNDED_ADD\",\r\n\t103:\"tecUNFUNDED_OFFER\",\r\n\t104:\"tecUNFUNDED_PAYMENT\",\r\n\t105:\"tecFAILED_PROCESSING\",\r\n\t121:\"tecDIR_FULL\",\r\n\t122:\"tecINSUF_RESERVE_LINE\",\r\n\t123:\"tecINSUF_RESERVE_OFFER\",\r\n\t124:\"tecNO_DST\",\r\n\t125:\"tecNO_DST_INSUF_XRP\",\r\n\t126:\"tecNO_LINE_INSUF_RESERVE\",\r\n\t127:\"tecNO_LINE_REDUNDANT\",\r\n\t128:\"tecPATH_DRY\",\r\n\t129:\"tecUNFUNDED\", // Deprecated, old ambiguous unfunded.\r\n\t130:\"tecMASTER_DISABLED\",\r\n\t131:\"tecNO_REGULAR_KEY\",\r\n\t132:\"tecOWNERS\"\r\n};\r\n\r\n\r\n\r\n\r\n\r\nSerializedObject.prototype.to_json = function() {\r\n\tvar old_pointer = this.pointer;\r\n\tthis.resetPointer();\r\n\tvar output = {};\r\n\twhile (true) {\r\n\t\tvar key_and_value = stypes.parse_whatever(this);\r\n\t\tvar key = key_and_value[0];\r\n\t\tvar value = key_and_value[1];\r\n\t\toutput[key] = jsonify_structure(value,key);\r\n\t\tif (this.pointer == this.buffer.length) {\r\n\t\t\tbreak;\r\n\t\t} else if (this.pointer > this.buffer.length) {\r\n\t\t\tconsole.log(\"WARNING: Buffer length exceeded during SerializedObject.to_json\");\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tthis.pointer = old_pointer;\r\n\treturn output;\r\n}\r\n\r\nfunction jsonify_structure(thing,field_name) {\r\n\tvar output;\r\n\tvar typeof_thing = typeof thing;\r\n\tif (\"number\" === typeof thing) { //Special codes\r\n\t\tif (field_name) {\r\n\t\t\tif (field_name === \"LedgerEntryType\") {\r\n\t\t\t\toutput = LEDGER_ENTRY_TYPES[thing] || thing;\r\n\t\t\t} else if (field_name === \"TransactionResult\") {\r\n\t\t\t\toutput = TRANSACTION_RESULTS[thing] || thing;\r\n\t\t\t} else if (field_name === \"TransactionType\") {\r\n\t\t\t\toutput = TRANSACTION_TYPES[thing] || thing;\r\n\t\t\t} else {\r\n\t\t\t\toutput = thing;\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\toutput = thing;\r\n\t\t}\r\n\t} else if (\"object\" === typeof thing &&\r\n \"function\" === typeof thing.to_json) {\r\n\t\toutput = thing.to_json();\r\n\t} else if (Array.isArray(thing)) {\r\n\t\t//console.log(\"here2\");\r\n\t\t//iterate over array []\r\n\t\toutput = [];\r\n\t\tfor (var i=0; i< thing.length; i++) {\r\n\t\t\toutput.push(jsonify_structure(thing[i]));\r\n\t\t}\r\n\t} else if (\"object\" === typeof thing) {\r\n\t\t//console.log(\"here1\", thing);\r\n\t\t//iterate over object {}\r\n\t\toutput = {};\r\n\t\tvar keys = Object.keys(thing);\r\n\t\tfor (var i=0; i<keys.length; i++) {\r\n\t\t\tvar key = keys[i];\r\n\t\t\tvar value = thing[key];\r\n\t\t\toutput[key] = jsonify_structure(value,key);\r\n\t\t}\r\n\t} else {\r\n output = thing;\r\n }\r\n\r\n\treturn output;\r\n}\r\n\r\nSerializedObject.prototype.serialize = function (typedef, obj)\r\n{\r\n // Ensure canonical order\r\n typedef = SerializedObject._sort_typedef(typedef.slice());\r\n\r\n // Serialize fields\r\n for (var i = 0, l = typedef.length; i < l; i++) {\r\n var spec = typedef[i];\r\n this.serialize_field(spec, obj);\r\n }\r\n};\r\n\r\nSerializedObject.prototype.signing_hash = function (prefix)\r\n{\r\n var sign_buffer = new SerializedObject();\r\n stypes.Int32.serialize(sign_buffer, prefix);\r\n sign_buffer.append(this.buffer);\r\n return sign_buffer.hash_sha512_half();\r\n};\r\n\r\nSerializedObject.prototype.hash_sha512_half = function ()\r\n{\r\n var bits = sjcl.codec.bytes.toBits(this.buffer),\r\n hash = sjcl.bitArray.bitSlice(sjcl.hash.sha512.hash(bits), 0, 256);\r\n\r\n return UInt256.from_hex(sjcl.codec.hex.fromBits(hash));\r\n};\r\n\r\nSerializedObject.prototype.serialize_field = function (spec, obj)\r\n{\r\n spec = spec.slice();\r\n\r\n var name = spec.shift(),\r\n presence = spec.shift(),\r\n field_id = spec.shift(),\r\n Type = spec.shift();\r\n\r\n if (\"undefined\" !== typeof obj[name]) {\r\n //console.log(name, Type.id, field_id);\r\n this.append(SerializedObject.get_field_header(Type.id, field_id));\r\n\r\n try {\r\n Type.serialize(this, obj[name]);\r\n } catch (e) {\r\n // Add field name to message and rethrow\r\n e.message = \"Error serializing '\"+name+\"': \"+e.message;\r\n throw e;\r\n }\r\n } else if (presence === binformat.REQUIRED) {\r\n throw new Error('Missing required field '+name);\r\n }\r\n};\r\n\r\nSerializedObject.get_field_header = function (type_id, field_id)\r\n{\r\n var buffer = [0];\r\n if (type_id > 0xf) buffer.push(type_id & 0xff);\r\n else buffer[0] += (type_id & 0xf) << 4;\r\n\r\n if (field_id > 0xf) buffer.push(field_id & 0xff);\r\n else buffer[0] += field_id & 0xf;\r\n\r\n return buffer;\r\n};\r\n\r\nfunction sort_field_compare(a, b) {\r\n // Sort by type id first, then by field id\r\n return a[3].id !== b[3].id ?\r\n a[3].id - b[3].id :\r\n a[2] - b[2];\r\n};\r\nSerializedObject._sort_typedef = function (typedef) {\r\n return typedef.sort(sort_field_compare);\r\n};\r\n\r\nSerializedObject.lookup_type_tx = function (id) {\r\n for (var i in binformat.tx) {\r\n if (!binformat.tx.hasOwnProperty(i)) continue;\r\n\r\n if (binformat.tx[i][0] === id) {\r\n return i;\r\n }\r\n }\r\n\r\n return null;\r\n};\r\n\r\n\r\nexports.SerializedObject = SerializedObject;\r\n\n/* WEBPACK VAR INJECTION */}(require, require(24).Buffer))\n\n// WEBPACK FOOTER\n// module.id = 7\n// module.readableIdentifier = ./src/js/ripple/serializedobject.js\n//@ sourceURL=webpack-module:///./src/js/ripple/serializedobject.js");
/***/ },
/***/ 8:
/***/ function(module, exports, require) {
eval("var ST = require(22);\r\n\r\nvar REQUIRED = exports.REQUIRED = 0,\r\n OPTIONAL = exports.OPTIONAL = 1,\r\n DEFAULT = exports.DEFAULT = 2;\r\n\r\nST.Int16.id = 1;\r\nST.Int32.id = 2;\r\nST.Int64.id = 3;\r\nST.Hash128.id = 4;\r\nST.Hash256.id = 5;\r\nST.Amount.id = 6;\r\nST.VariableLength.id = 7;\r\nST.Account.id = 8;\r\nST.Object.id = 14;\r\nST.Array.id = 15;\r\nST.Int8.id = 16;\r\nST.Hash160.id = 17;\r\nST.PathSet.id = 18;\r\nST.Vector256.id = 19;\r\n\r\nvar base = [\r\n [ 'TransactionType' , REQUIRED, 2, ST.Int16 ],\r\n [ 'Flags' , OPTIONAL, 2, ST.Int32 ],\r\n [ 'SourceTag' , OPTIONAL, 3, ST.Int32 ],\r\n [ 'Account' , REQUIRED, 1, ST.Account ],\r\n [ 'Sequence' , REQUIRED, 4, ST.Int32 ],\r\n [ 'Fee' , REQUIRED, 8, ST.Amount ],\r\n [ 'OperationLimit' , OPTIONAL, 29, ST.Int32 ],\r\n [ 'SigningPubKey' , REQUIRED, 3, ST.VariableLength ],\r\n [ 'TxnSignature' , OPTIONAL, 4, ST.VariableLength ]\r\n];\r\n\r\nexports.tx = {\r\n AccountSet: [3].concat(base, [\r\n [ 'EmailHash' , OPTIONAL, 1, ST.Hash128 ],\r\n [ 'WalletLocator' , OPTIONAL, 7, ST.Hash256 ],\r\n [ 'WalletSize' , OPTIONAL, 12, ST.Int32 ],\r\n [ 'MessageKey' , OPTIONAL, 2, ST.VariableLength ],\r\n [ 'Domain' , OPTIONAL, 7, ST.VariableLength ],\r\n [ 'TransferRate' , OPTIONAL, 11, ST.Int32 ]\r\n ]),\r\n TrustSet: [20].concat(base, [\r\n [ 'LimitAmount' , OPTIONAL, 3, ST.Amount ],\r\n [ 'QualityIn' , OPTIONAL, 20, ST.Int32 ],\r\n [ 'QualityOut' , OPTIONAL, 21, ST.Int32 ]\r\n ]),\r\n OfferCreate: [7].concat(base, [\r\n [ 'TakerPays' , REQUIRED, 4, ST.Amount ],\r\n [ 'TakerGets' , REQUIRED, 5, ST.Amount ],\r\n [ 'Expiration' , OPTIONAL, 10, ST.Int32 ]\r\n ]),\r\n OfferCancel: [8].concat(base, [\r\n [ 'OfferSequence' , REQUIRED, 25, ST.Int32 ]\r\n ]),\r\n SetRegularKey: [5].concat(base, [\r\n [ 'RegularKey' , REQUIRED, 8, ST.Account ]\r\n ]),\r\n Payment: [0].concat(base, [\r\n [ 'Destination' , REQUIRED, 3, ST.Account ],\r\n [ 'Amount' , REQUIRED, 1, ST.Amount ],\r\n [ 'SendMax' , OPTIONAL, 9, ST.Amount ],\r\n [ 'Paths' , DEFAULT , 1, ST.PathSet ],\r\n [ 'InvoiceID' , OPTIONAL, 17, ST.Hash256 ],\r\n [ 'DestinationTag' , OPTIONAL, 14, ST.Int32 ]\r\n ]),\r\n Contract: [9].concat(base, [\r\n [ 'Expiration' , REQUIRED, 10, ST.Int32 ],\r\n [ 'BondAmount' , REQUIRED, 23, ST.Int32 ],\r\n [ 'StampEscrow' , REQUIRED, 22, ST.Int32 ],\r\n [ 'RippleEscrow' , REQUIRED, 17, ST.Amount ],\r\n [ 'CreateCode' , OPTIONAL, 11, ST.VariableLength ],\r\n [ 'FundCode' , OPTIONAL, 8, ST.VariableLength ],\r\n [ 'RemoveCode' , OPTIONAL, 9, ST.VariableLength ],\r\n [ 'ExpireCode' , OPTIONAL, 10, ST.VariableLength ]\r\n ]),\r\n RemoveContract: [10].concat(base, [\r\n [ 'Target' , REQUIRED, 7, ST.Account ]\r\n ]),\r\n EnableFeature: [100].concat(base, [\r\n [ 'Feature' , REQUIRED, 19, ST.Hash256 ]\r\n ]),\r\n SetFee: [101].concat(base, [\r\n [ 'Features' , REQUIRED, 9, ST.Array ],\r\n [ 'BaseFee' , REQUIRED, 5, ST.Int64 ],\r\n [ 'ReferenceFeeUnits' , REQUIRED, 30, ST.Int32 ],\r\n [ 'ReserveBase' , REQUIRED, 31, ST.Int32 ],\r\n [ 'ReserveIncrement' , REQUIRED, 32, ST.Int32 ]\r\n ])\r\n};\r\n\n\n// WEBPACK FOOTER\n// module.id = 8\n// module.readableIdentifier = ./src/js/ripple/binformat.js\n//@ sourceURL=webpack-module:///./src/js/ripple/binformat.js");
/***/ },
/***/ 9:
/***/ function(module, exports, require) {
eval("var exports = module.exports = require(13);\r\n\r\n// We override this function for browsers, because they print objects nicer\r\n// natively than JSON.stringify can.\r\nexports.logObject = function (msg, obj) {\r\n if (/MSIE/.test(navigator.userAgent)) {\r\n console.log(msg, JSON.stringify(obj));\r\n } else {\r\n console.log(msg, \"\", obj);\r\n }\r\n};\r\n\n\n// WEBPACK FOOTER\n// module.id = 9\n// module.readableIdentifier = ./src/js/ripple/utils.web.js\n//@ sourceURL=webpack-module:///./src/js/ripple/utils.web.js");
/***/ },
/***/ 10:
/***/ function(module, exports, require) {
eval("/* WEBPACK VAR INJECTION */(function(require, module) {/** @fileOverview Javascript cryptography implementation.\r\n *\r\n * Crush to remove comments, shorten variable names and\r\n * generally reduce transmission size.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n\"use strict\";\r\n/*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */\r\n/*global document, window, escape, unescape */\r\n\r\n/** @namespace The Stanford Javascript Crypto Library, top-level namespace. */\r\nvar sjcl = {\r\n /** @namespace Symmetric ciphers. */\r\n cipher: {},\r\n\r\n /** @namespace Hash functions. Right now only SHA256 is implemented. */\r\n hash: {},\r\n\r\n /** @namespace Key exchange functions. Right now only SRP is implemented. */\r\n keyexchange: {},\r\n \r\n /** @namespace Block cipher modes of operation. */\r\n mode: {},\r\n\r\n /** @namespace Miscellaneous. HMAC and PBKDF2. */\r\n misc: {},\r\n \r\n /**\r\n * @namespace Bit array encoders and decoders.\r\n *\r\n * @description\r\n * The members of this namespace are functions which translate between\r\n * SJCL's bitArrays and other objects (usually strings). Because it\r\n * isn't always clear which direction is encoding and which is decoding,\r\n * the method names are \"fromBits\" and \"toBits\".\r\n */\r\n codec: {},\r\n \r\n /** @namespace Exceptions. */\r\n exception: {\r\n /** @constructor Ciphertext is corrupt. */\r\n corrupt: function(message) {\r\n this.toString = function() { return \"CORRUPT: \"+this.message; };\r\n this.message = message;\r\n },\r\n \r\n /** @constructor Invalid parameter. */\r\n invalid: function(message) {\r\n this.toString = function() { return \"INVALID: \"+this.message; };\r\n this.message = message;\r\n },\r\n \r\n /** @constructor Bug or missing feature in SJCL. @constructor */\r\n bug: function(message) {\r\n this.toString = function() { return \"BUG: \"+this.message; };\r\n this.message = message;\r\n },\r\n\r\n /** @constructor Something isn't ready. */\r\n notReady: function(message) {\r\n this.toString = function() { return \"NOT READY: \"+this.message; };\r\n this.message = message;\r\n }\r\n }\r\n};\r\n\r\nif(typeof module != 'undefined' && module.exports){\r\n module.exports = sjcl;\r\n}\r\n\r\n/** @fileOverview Low-level AES implementation.\r\n *\r\n * This file contains a low-level implementation of AES, optimized for\r\n * size and for efficiency on several browsers. It is based on\r\n * OpenSSL's aes_core.c, a public-domain implementation by Vincent\r\n * Rijmen, Antoon Bosselaers and Paulo Barreto.\r\n *\r\n * An older version of this implementation is available in the public\r\n * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,\r\n * Stanford University 2008-2010 and BSD-licensed for liability\r\n * reasons.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/**\r\n * Schedule out an AES key for both encryption and decryption. This\r\n * is a low-level class. Use a cipher mode to do bulk encryption.\r\n *\r\n * @constructor\r\n * @param {Array} key The key as an array of 4, 6 or 8 words.\r\n *\r\n * @class Advanced Encryption Standard (low-level interface)\r\n */\r\nsjcl.cipher.aes = function (key) {\r\n if (!this._tables[0][0][0]) {\r\n this._precompute();\r\n }\r\n \r\n var i, j, tmp,\r\n encKey, decKey,\r\n sbox = this._tables[0][4], decTable = this._tables[1],\r\n keyLen = key.length, rcon = 1;\r\n \r\n if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {\r\n throw new sjcl.exception.invalid(\"invalid aes key size\");\r\n }\r\n \r\n this._key = [encKey = key.slice(0), decKey = []];\r\n \r\n // schedule encryption keys\r\n for (i = keyLen; i < 4 * keyLen + 28; i++) {\r\n tmp = encKey[i-1];\r\n \r\n // apply sbox\r\n if (i%keyLen === 0 || (keyLen === 8 && i%keyLen === 4)) {\r\n tmp = sbox[tmp>>>24]<<24 ^ sbox[tmp>>16&255]<<16 ^ sbox[tmp>>8&255]<<8 ^ sbox[tmp&255];\r\n \r\n // shift rows and add rcon\r\n if (i%keyLen === 0) {\r\n tmp = tmp<<8 ^ tmp>>>24 ^ rcon<<24;\r\n rcon = rcon<<1 ^ (rcon>>7)*283;\r\n }\r\n }\r\n \r\n encKey[i] = encKey[i-keyLen] ^ tmp;\r\n }\r\n \r\n // schedule decryption keys\r\n for (j = 0; i; j++, i--) {\r\n tmp = encKey[j&3 ? i : i - 4];\r\n if (i<=4 || j<4) {\r\n decKey[j] = tmp;\r\n } else {\r\n decKey[j] = decTable[0][sbox[tmp>>>24 ]] ^\r\n decTable[1][sbox[tmp>>16 & 255]] ^\r\n decTable[2][sbox[tmp>>8 & 255]] ^\r\n decTable[3][sbox[tmp & 255]];\r\n }\r\n }\r\n};\r\n\r\nsjcl.cipher.aes.prototype = {\r\n // public\r\n /* Something like this might appear here eventually\r\n name: \"AES\",\r\n blockSize: 4,\r\n keySizes: [4,6,8],\r\n */\r\n \r\n /**\r\n * Encrypt an array of 4 big-endian words.\r\n * @param {Array} data The plaintext.\r\n * @return {Array} The ciphertext.\r\n */\r\n encrypt:function (data) { return this._crypt(data,0); },\r\n \r\n /**\r\n * Decrypt an array of 4 big-endian words.\r\n * @param {Array} data The ciphertext.\r\n * @return {Array} The plaintext.\r\n */\r\n decrypt:function (data) { return this._crypt(data,1); },\r\n \r\n /**\r\n * The expanded S-box and inverse S-box tables. These will be computed\r\n * on the client so that we don't have to send them down the wire.\r\n *\r\n * There are two tables, _tables[0] is for encryption and\r\n * _tables[1] is for decryption.\r\n *\r\n * The first 4 sub-tables are the expanded S-box with MixColumns. The\r\n * last (_tables[01][4]) is the S-box itself.\r\n *\r\n * @private\r\n */\r\n _tables: [[[],[],[],[],[]],[[],[],[],[],[]]],\r\n\r\n /**\r\n * Expand the S-box tables.\r\n *\r\n * @private\r\n */\r\n _precompute: function () {\r\n var encTable = this._tables[0], decTable = this._tables[1],\r\n sbox = encTable[4], sboxInv = decTable[4],\r\n i, x, xInv, d=[], th=[], x2, x4, x8, s, tEnc, tDec;\r\n\r\n // Compute double and third tables\r\n for (i = 0; i < 256; i++) {\r\n th[( d[i] = i<<1 ^ (i>>7)*283 )^i]=i;\r\n }\r\n \r\n for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {\r\n // Compute sbox\r\n s = xInv ^ xInv<<1 ^ xInv<<2 ^ xInv<<3 ^ xInv<<4;\r\n s = s>>8 ^ s&255 ^ 99;\r\n sbox[x] = s;\r\n sboxInv[s] = x;\r\n \r\n // Compute MixColumns\r\n x8 = d[x4 = d[x2 = d[x]]];\r\n tDec = x8*0x1010101 ^ x4*0x10001 ^ x2*0x101 ^ x*0x1010100;\r\n tEnc = d[s]*0x101 ^ s*0x1010100;\r\n \r\n for (i = 0; i < 4; i++) {\r\n encTable[i][x] = tEnc = tEnc<<24 ^ tEnc>>>8;\r\n decTable[i][s] = tDec = tDec<<24 ^ tDec>>>8;\r\n }\r\n }\r\n \r\n // Compactify. Considerable speedup on Firefox.\r\n for (i = 0; i < 5; i++) {\r\n encTable[i] = encTable[i].slice(0);\r\n decTable[i] = decTable[i].slice(0);\r\n }\r\n },\r\n \r\n /**\r\n * Encryption and decryption core.\r\n * @param {Array} input Four words to be encrypted or decrypted.\r\n * @param dir The direction, 0 for encrypt and 1 for decrypt.\r\n * @return {Array} The four encrypted or decrypted words.\r\n * @private\r\n */\r\n _crypt:function (input, dir) {\r\n if (input.length !== 4) {\r\n throw new sjcl.exception.invalid(\"invalid aes block size\");\r\n }\r\n \r\n var key = this._key[dir],\r\n // state variables a,b,c,d are loaded with pre-whitened data\r\n a = input[0] ^ key[0],\r\n b = input[dir ? 3 : 1] ^ key[1],\r\n c = input[2] ^ key[2],\r\n d = input[dir ? 1 : 3] ^ key[3],\r\n a2, b2, c2,\r\n \r\n nInnerRounds = key.length/4 - 2,\r\n i,\r\n kIndex = 4,\r\n out = [0,0,0,0],\r\n table = this._tables[dir],\r\n \r\n // load up the tables\r\n t0 = table[0],\r\n t1 = table[1],\r\n t2 = table[2],\r\n t3 = table[3],\r\n sbox = table[4];\r\n \r\n // Inner rounds. Cribbed from OpenSSL.\r\n for (i = 0; i < nInnerRounds; i++) {\r\n a2 = t0[a>>>24] ^ t1[b>>16 & 255] ^ t2[c>>8 & 255] ^ t3[d & 255] ^ key[kIndex];\r\n b2 = t0[b>>>24] ^ t1[c>>16 & 255] ^ t2[d>>8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];\r\n c2 = t0[c>>>24] ^ t1[d>>16 & 255] ^ t2[a>>8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];\r\n d = t0[d>>>24] ^ t1[a>>16 & 255] ^ t2[b>>8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];\r\n kIndex += 4;\r\n a=a2; b=b2; c=c2;\r\n }\r\n \r\n // Last round.\r\n for (i = 0; i < 4; i++) {\r\n out[dir ? 3&-i : i] =\r\n sbox[a>>>24 ]<<24 ^ \r\n sbox[b>>16 & 255]<<16 ^\r\n sbox[c>>8 & 255]<<8 ^\r\n sbox[d & 255] ^\r\n key[kIndex++];\r\n a2=a; a=b; b=c; c=d; d=a2;\r\n }\r\n \r\n return out;\r\n }\r\n};\r\n\r\n\r\n/** @fileOverview Arrays of bits, encoded as arrays of Numbers.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** @namespace Arrays of bits, encoded as arrays of Numbers.\r\n *\r\n * @description\r\n * <p>\r\n * These objects are the currency accepted by SJCL's crypto functions.\r\n * </p>\r\n *\r\n * <p>\r\n * Most of our crypto primitives operate on arrays of 4-byte words internally,\r\n * but many of them can take arguments that are not a multiple of 4 bytes.\r\n * This library encodes arrays of bits (whose size need not be a multiple of 8\r\n * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an\r\n * array of words, 32 bits at a time. Since the words are double-precision\r\n * floating point numbers, they fit some extra data. We use this (in a private,\r\n * possibly-changing manner) to encode the number of bits actually present\r\n * in the last word of the array.\r\n * </p>\r\n *\r\n * <p>\r\n * Because bitwise ops clear this out-of-band data, these arrays can be passed\r\n * to ciphers like AES which want arrays of words.\r\n * </p>\r\n */\r\nsjcl.bitArray = {\r\n /**\r\n * Array slices in units of bits.\r\n * @param {bitArray} a The array to slice.\r\n * @param {Number} bstart The offset to the start of the slice, in bits.\r\n * @param {Number} bend The offset to the end of the slice, in bits. If this is undefined,\r\n * slice until the end of the array.\r\n * @return {bitArray} The requested slice.\r\n */\r\n bitSlice: function (a, bstart, bend) {\r\n a = sjcl.bitArray._shiftRight(a.slice(bstart/32), 32 - (bstart & 31)).slice(1);\r\n return (bend === undefined) ? a : sjcl.bitArray.clamp(a, bend-bstart);\r\n },\r\n\r\n /**\r\n * Extract a number packed into a bit array.\r\n * @param {bitArray} a The array to slice.\r\n * @param {Number} bstart The offset to the start of the slice, in bits.\r\n * @param {Number} length The length of the number to extract.\r\n * @return {Number} The requested slice.\r\n */\r\n extract: function(a, bstart, blength) {\r\n // FIXME: this Math.floor is not necessary at all, but for some reason\r\n // seems to suppress a bug in the Chromium JIT.\r\n var x, sh = Math.floor((-bstart-blength) & 31);\r\n if ((bstart + blength - 1 ^ bstart) & -32) {\r\n // it crosses a boundary\r\n x = (a[bstart/32|0] << (32 - sh)) ^ (a[bstart/32+1|0] >>> sh);\r\n } else {\r\n // within a single word\r\n x = a[bstart/32|0] >>> sh;\r\n }\r\n return x & ((1<<blength) - 1);\r\n },\r\n\r\n /**\r\n * Concatenate two bit arrays.\r\n * @param {bitArray} a1 The first array.\r\n * @param {bitArray} a2 The second array.\r\n * @return {bitArray} The concatenation of a1 and a2.\r\n */\r\n concat: function (a1, a2) {\r\n if (a1.length === 0 || a2.length === 0) {\r\n return a1.concat(a2);\r\n }\r\n \r\n var out, i, last = a1[a1.length-1], shift = sjcl.bitArray.getPartial(last);\r\n if (shift === 32) {\r\n return a1.concat(a2);\r\n } else {\r\n return sjcl.bitArray._shiftRight(a2, shift, last|0, a1.slice(0,a1.length-1));\r\n }\r\n },\r\n\r\n /**\r\n * Find the length of an array of bits.\r\n * @param {bitArray} a The array.\r\n * @return {Number} The length of a, in bits.\r\n */\r\n bitLength: function (a) {\r\n var l = a.length, x;\r\n if (l === 0) { return 0; }\r\n x = a[l - 1];\r\n return (l-1) * 32 + sjcl.bitArray.getPartial(x);\r\n },\r\n\r\n /**\r\n * Truncate an array.\r\n * @param {bitArray} a The array.\r\n * @param {Number} len The length to truncate to, in bits.\r\n * @return {bitArray} A new array, truncated to len bits.\r\n */\r\n clamp: function (a, len) {\r\n if (a.length * 32 < len) { return a; }\r\n a = a.slice(0, Math.ceil(len / 32));\r\n var l = a.length;\r\n len = len & 31;\r\n if (l > 0 && len) {\r\n a[l-1] = sjcl.bitArray.partial(len, a[l-1] & 0x80000000 >> (len-1), 1);\r\n }\r\n return a;\r\n },\r\n\r\n /**\r\n * Make a partial word for a bit array.\r\n * @param {Number} len The number of bits in the word.\r\n * @param {Number} x The bits.\r\n * @param {Number} [0] _end Pass 1 if x has already been shifted to the high side.\r\n * @return {Number} The partial word.\r\n */\r\n partial: function (len, x, _end) {\r\n if (len === 32) { return x; }\r\n return (_end ? x|0 : x << (32-len)) + len * 0x10000000000;\r\n },\r\n\r\n /**\r\n * Get the number of bits used by a partial word.\r\n * @param {Number} x The partial word.\r\n * @return {Number} The number of bits used by the partial word.\r\n */\r\n getPartial: function (x) {\r\n return Math.round(x/0x10000000000) || 32;\r\n },\r\n\r\n /**\r\n * Compare two arrays for equality in a predictable amount of time.\r\n * @param {bitArray} a The first array.\r\n * @param {bitArray} b The second array.\r\n * @return {boolean} true if a == b; false otherwise.\r\n */\r\n equal: function (a, b) {\r\n if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) {\r\n return false;\r\n }\r\n var x = 0, i;\r\n for (i=0; i<a.length; i++) {\r\n x |= a[i]^b[i];\r\n }\r\n return (x === 0);\r\n },\r\n\r\n /** Shift an array right.\r\n * @param {bitArray} a The array to shift.\r\n * @param {Number} shift The number of bits to shift.\r\n * @param {Number} [carry=0] A byte to carry in\r\n * @param {bitArray} [out=[]] An array to prepend to the output.\r\n * @private\r\n */\r\n _shiftRight: function (a, shift, carry, out) {\r\n var i, last2=0, shift2;\r\n if (out === undefined) { out = []; }\r\n \r\n for (; shift >= 32; shift -= 32) {\r\n out.push(carry);\r\n carry = 0;\r\n }\r\n if (shift === 0) {\r\n return out.concat(a);\r\n }\r\n \r\n for (i=0; i<a.length; i++) {\r\n out.push(carry | a[i]>>>shift);\r\n carry = a[i] << (32-shift);\r\n }\r\n last2 = a.length ? a[a.length-1] : 0;\r\n shift2 = sjcl.bitArray.getPartial(last2);\r\n out.push(sjcl.bitArray.partial(shift+shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(),1));\r\n return out;\r\n },\r\n \r\n /** xor a block of 4 words together.\r\n * @private\r\n */\r\n _xor4: function(x,y) {\r\n return [x[0]^y[0],x[1]^y[1],x[2]^y[2],x[3]^y[3]];\r\n }\r\n};\r\n\r\n/** @fileOverview Bit array codec implementations.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n \r\n/** @namespace UTF-8 strings */\r\nsjcl.codec.utf8String = {\r\n /** Convert from a bitArray to a UTF-8 string. */\r\n fromBits: function (arr) {\r\n var out = \"\", bl = sjcl.bitArray.bitLength(arr), i, tmp;\r\n for (i=0; i<bl/8; i++) {\r\n if ((i&3) === 0) {\r\n tmp = arr[i/4];\r\n }\r\n out += String.fromCharCode(tmp >>> 24);\r\n tmp <<= 8;\r\n }\r\n return decodeURIComponent(escape(out));\r\n },\r\n \r\n /** Convert from a UTF-8 string to a bitArray. */\r\n toBits: function (str) {\r\n str = unescape(encodeURIComponent(str));\r\n var out = [], i, tmp=0;\r\n for (i=0; i<str.length; i++) {\r\n tmp = tmp << 8 | str.charCodeAt(i);\r\n if ((i&3) === 3) {\r\n out.push(tmp);\r\n tmp = 0;\r\n }\r\n }\r\n if (i&3) {\r\n out.push(sjcl.bitArray.partial(8*(i&3), tmp));\r\n }\r\n return out;\r\n }\r\n};\r\n\r\n/** @fileOverview Bit array codec implementations.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** @namespace Hexadecimal */\r\nsjcl.codec.hex = {\r\n /** Convert from a bitArray to a hex string. */\r\n fromBits: function (arr) {\r\n var out = \"\", i, x;\r\n for (i=0; i<arr.length; i++) {\r\n out += ((arr[i]|0)+0xF00000000000).toString(16).substr(4);\r\n }\r\n return out.substr(0, sjcl.bitArray.bitLength(arr)/4);//.replace(/(.{8})/g, \"$1 \");\r\n },\r\n /** Convert from a hex string to a bitArray. */\r\n toBits: function (str) {\r\n var i, out=[], len;\r\n str = str.replace(/\\s|0x/g, \"\");\r\n len = str.length;\r\n str = str + \"00000000\";\r\n for (i=0; i<str.length; i+=8) {\r\n out.push(parseInt(str.substr(i,8),16)^0);\r\n }\r\n return sjcl.bitArray.clamp(out, len*4);\r\n }\r\n};\r\n\r\n\r\n/** @fileOverview Bit array codec implementations.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** @namespace Base64 encoding/decoding */\r\nsjcl.codec.base64 = {\r\n /** The base64 alphabet.\r\n * @private\r\n */\r\n _chars: \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",\r\n \r\n /** Convert from a bitArray to a base64 string. */\r\n fromBits: function (arr, _noEquals, _url) {\r\n var out = \"\", i, bits=0, c = sjcl.codec.base64._chars, ta=0, bl = sjcl.bitArray.bitLength(arr);\r\n if (_url) c = c.substr(0,62) + '-_';\r\n for (i=0; out.length * 6 < bl; ) {\r\n out += c.charAt((ta ^ arr[i]>>>bits) >>> 26);\r\n if (bits < 6) {\r\n ta = arr[i] << (6-bits);\r\n bits += 26;\r\n i++;\r\n } else {\r\n ta <<= 6;\r\n bits -= 6;\r\n }\r\n }\r\n while ((out.length & 3) && !_noEquals) { out += \"=\"; }\r\n return out;\r\n },\r\n \r\n /** Convert from a base64 string to a bitArray */\r\n toBits: function(str, _url) {\r\n str = str.replace(/\\s|=/g,'');\r\n var out = [], i, bits=0, c = sjcl.codec.base64._chars, ta=0, x;\r\n if (_url) c = c.substr(0,62) + '-_';\r\n for (i=0; i<str.length; i++) {\r\n x = c.indexOf(str.charAt(i));\r\n if (x < 0) {\r\n throw new sjcl.exception.invalid(\"this isn't base64!\");\r\n }\r\n if (bits > 26) {\r\n bits -= 26;\r\n out.push(ta ^ x>>>bits);\r\n ta = x << (32-bits);\r\n } else {\r\n bits += 6;\r\n ta ^= x << (32-bits);\r\n }\r\n }\r\n if (bits&56) {\r\n out.push(sjcl.bitArray.partial(bits&56, ta, 1));\r\n }\r\n return out;\r\n }\r\n};\r\n\r\nsjcl.codec.base64url = {\r\n fromBits: function (arr) { return sjcl.codec.base64.fromBits(arr,1,1); },\r\n toBits: function (str) { return sjcl.codec.base64.toBits(str,1); }\r\n};\r\n\r\n/** @fileOverview Bit array codec implementations.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** @namespace Arrays of bytes */\r\nsjcl.codec.bytes = {\r\n /** Convert from a bitArray to an array of bytes. */\r\n fromBits: function (arr) {\r\n var out = [], bl = sjcl.bitArray.bitLength(arr), i, tmp;\r\n for (i=0; i<bl/8; i++) {\r\n if ((i&3) === 0) {\r\n tmp = arr[i/4];\r\n }\r\n out.push(tmp >>> 24);\r\n tmp <<= 8;\r\n }\r\n return out;\r\n },\r\n /** Convert from an array of bytes to a bitArray. */\r\n toBits: function (bytes) {\r\n var out = [], i, tmp=0;\r\n for (i=0; i<bytes.length; i++) {\r\n tmp = tmp << 8 | bytes[i];\r\n if ((i&3) === 3) {\r\n out.push(tmp);\r\n tmp = 0;\r\n }\r\n }\r\n if (i&3) {\r\n out.push(sjcl.bitArray.partial(8*(i&3), tmp));\r\n }\r\n return out;\r\n }\r\n};\r\n\r\n/** @fileOverview Javascript SHA-256 implementation.\r\n *\r\n * An older version of this implementation is available in the public\r\n * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,\r\n * Stanford University 2008-2010 and BSD-licensed for liability\r\n * reasons.\r\n *\r\n * Special thanks to Aldo Cortesi for pointing out several bugs in\r\n * this code.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/**\r\n * Context for a SHA-256 operation in progress.\r\n * @constructor\r\n * @class Secure Hash Algorithm, 256 bits.\r\n */\r\nsjcl.hash.sha256 = function (hash) {\r\n if (!this._key[0]) { this._precompute(); }\r\n if (hash) {\r\n this._h = hash._h.slice(0);\r\n this._buffer = hash._buffer.slice(0);\r\n this._length = hash._length;\r\n } else {\r\n this.reset();\r\n }\r\n};\r\n\r\n/**\r\n * Hash a string or an array of words.\r\n * @static\r\n * @param {bitArray|String} data the data to hash.\r\n * @return {bitArray} The hash value, an array of 16 big-endian words.\r\n */\r\nsjcl.hash.sha256.hash = function (data) {\r\n return (new sjcl.hash.sha256()).update(data).finalize();\r\n};\r\n\r\nsjcl.hash.sha256.prototype = {\r\n /**\r\n * The hash's block size, in bits.\r\n * @constant\r\n */\r\n blockSize: 512,\r\n \r\n /**\r\n * Reset the hash state.\r\n * @return this\r\n */\r\n reset:function () {\r\n this._h = this._init.slice(0);\r\n this._buffer = [];\r\n this._length = 0;\r\n return this;\r\n },\r\n \r\n /**\r\n * Input several words to the hash.\r\n * @param {bitArray|String} data the data to hash.\r\n * @return this\r\n */\r\n update: function (data) {\r\n if (typeof data === \"string\") {\r\n data = sjcl.codec.utf8String.toBits(data);\r\n }\r\n var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),\r\n ol = this._length,\r\n nl = this._length = ol + sjcl.bitArray.bitLength(data);\r\n for (i = 512+ol & -512; i <= nl; i+= 512) {\r\n this._block(b.splice(0,16));\r\n }\r\n return this;\r\n },\r\n \r\n /**\r\n * Complete hashing and output the hash value.\r\n * @return {bitArray} The hash value, an array of 8 big-endian words.\r\n */\r\n finalize:function () {\r\n var i, b = this._buffer, h = this._h;\r\n\r\n // Round out and push the buffer\r\n b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1,1)]);\r\n \r\n // Round out the buffer to a multiple of 16 words, less the 2 length words.\r\n for (i = b.length + 2; i & 15; i++) {\r\n b.push(0);\r\n }\r\n \r\n // append the length\r\n b.push(Math.floor(this._length / 0x100000000));\r\n b.push(this._length | 0);\r\n\r\n while (b.length) {\r\n this._block(b.splice(0,16));\r\n }\r\n\r\n this.reset();\r\n return h;\r\n },\r\n\r\n /**\r\n * The SHA-256 initialization vector, to be precomputed.\r\n * @private\r\n */\r\n _init:[],\r\n /*\r\n _init:[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19],\r\n */\r\n \r\n /**\r\n * The SHA-256 hash key, to be precomputed.\r\n * @private\r\n */\r\n _key:[],\r\n /*\r\n _key:\r\n [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\r\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\r\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\r\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\r\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\r\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\r\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\r\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2],\r\n */\r\n\r\n\r\n /**\r\n * Function to precompute _init and _key.\r\n * @private\r\n */\r\n _precompute: function () {\r\n var i = 0, prime = 2, factor;\r\n\r\n function frac(x) { return (x-Math.floor(x)) * 0x100000000 | 0; }\r\n\r\n outer: for (; i<64; prime++) {\r\n for (factor=2; factor*factor <= prime; factor++) {\r\n if (prime % factor === 0) {\r\n // not a prime\r\n continue outer;\r\n }\r\n }\r\n \r\n if (i<8) {\r\n this._init[i] = frac(Math.pow(prime, 1/2));\r\n }\r\n this._key[i] = frac(Math.pow(prime, 1/3));\r\n i++;\r\n }\r\n },\r\n \r\n /**\r\n * Perform one cycle of SHA-256.\r\n * @param {bitArray} words one block of words.\r\n * @private\r\n */\r\n _block:function (words) { \r\n var i, tmp, a, b,\r\n w = words.slice(0),\r\n h = this._h,\r\n k = this._key,\r\n h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3],\r\n h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];\r\n\r\n /* Rationale for placement of |0 :\r\n * If a value can overflow is original 32 bits by a factor of more than a few\r\n * million (2^23 ish), there is a possibility that it might overflow the\r\n * 53-bit mantissa and lose precision.\r\n *\r\n * To avoid this, we clamp back to 32 bits by |'ing with 0 on any value that\r\n * propagates around the loop, and on the hash state h[]. I don't believe\r\n * that the clamps on h4 and on h0 are strictly necessary, but it's close\r\n * (for h4 anyway), and better safe than sorry.\r\n *\r\n * The clamps on h[] are necessary for the output to be correct even in the\r\n * common case and for short inputs.\r\n */\r\n for (i=0; i<64; i++) {\r\n // load up the input word for this round\r\n if (i<16) {\r\n tmp = w[i];\r\n } else {\r\n a = w[(i+1 ) & 15];\r\n b = w[(i+14) & 15];\r\n tmp = w[i&15] = ((a>>>7 ^ a>>>18 ^ a>>>3 ^ a<<25 ^ a<<14) + \r\n (b>>>17 ^ b>>>19 ^ b>>>10 ^ b<<15 ^ b<<13) +\r\n w[i&15] + w[(i+9) & 15]) | 0;\r\n }\r\n \r\n tmp = (tmp + h7 + (h4>>>6 ^ h4>>>11 ^ h4>>>25 ^ h4<<26 ^ h4<<21 ^ h4<<7) + (h6 ^ h4&(h5^h6)) + k[i]); // | 0;\r\n \r\n // shift register\r\n h7 = h6; h6 = h5; h5 = h4;\r\n h4 = h3 + tmp | 0;\r\n h3 = h2; h2 = h1; h1 = h0;\r\n\r\n h0 = (tmp + ((h1&h2) ^ (h3&(h1^h2))) + (h1>>>2 ^ h1>>>13 ^ h1>>>22 ^ h1<<30 ^ h1<<19 ^ h1<<10)) | 0;\r\n }\r\n\r\n h[0] = h[0]+h0 | 0;\r\n h[1] = h[1]+h1 | 0;\r\n h[2] = h[2]+h2 | 0;\r\n h[3] = h[3]+h3 | 0;\r\n h[4] = h[4]+h4 | 0;\r\n h[5] = h[5]+h5 | 0;\r\n h[6] = h[6]+h6 | 0;\r\n h[7] = h[7]+h7 | 0;\r\n }\r\n};\r\n\r\n\r\n\r\n/** @fileOverview Javascript SHA-512 implementation.\r\n *\r\n * This implementation was written for CryptoJS by Jeff Mott and adapted for\r\n * SJCL by Stefan Thomas.\r\n *\r\n * CryptoJS (c) 2009–2012 by Jeff Mott. All rights reserved.\r\n * Released with New BSD License\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n * @author Jeff Mott\r\n * @author Stefan Thomas\r\n */\r\n\r\n/**\r\n * Context for a SHA-512 operation in progress.\r\n * @constructor\r\n * @class Secure Hash Algorithm, 512 bits.\r\n */\r\nsjcl.hash.sha512 = function (hash) {\r\n if (!this._key[0]) { this._precompute(); }\r\n if (hash) {\r\n this._h = hash._h.slice(0);\r\n this._buffer = hash._buffer.slice(0);\r\n this._length = hash._length;\r\n } else {\r\n this.reset();\r\n }\r\n};\r\n\r\n/**\r\n * Hash a string or an array of words.\r\n * @static\r\n * @param {bitArray|String} data the data to hash.\r\n * @return {bitArray} The hash value, an array of 16 big-endian words.\r\n */\r\nsjcl.hash.sha512.hash = function (data) {\r\n return (new sjcl.hash.sha512()).update(data).finalize();\r\n};\r\n\r\nsjcl.hash.sha512.prototype = {\r\n /**\r\n * The hash's block size, in bits.\r\n * @constant\r\n */\r\n blockSize: 1024,\r\n \r\n /**\r\n * Reset the hash state.\r\n * @return this\r\n */\r\n reset:function () {\r\n this._h = this._init.slice(0);\r\n this._buffer = [];\r\n this._length = 0;\r\n return this;\r\n },\r\n \r\n /**\r\n * Input several words to the hash.\r\n * @param {bitArray|String} data the data to hash.\r\n * @return this\r\n */\r\n update: function (data) {\r\n if (typeof data === \"string\") {\r\n data = sjcl.codec.utf8String.toBits(data);\r\n }\r\n var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),\r\n ol = this._length,\r\n nl = this._length = ol + sjcl.bitArray.bitLength(data);\r\n for (i = 1024+ol & -1024; i <= nl; i+= 1024) {\r\n this._block(b.splice(0,32));\r\n }\r\n return this;\r\n },\r\n \r\n /**\r\n * Complete hashing and output the hash value.\r\n * @return {bitArray} The hash value, an array of 16 big-endian words.\r\n */\r\n finalize:function () {\r\n var i, b = this._buffer, h = this._h;\r\n\r\n // Round out and push the buffer\r\n b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1,1)]);\r\n\r\n // Round out the buffer to a multiple of 32 words, less the 4 length words.\r\n for (i = b.length + 4; i & 31; i++) {\r\n b.push(0);\r\n }\r\n\r\n // append the length\r\n b.push(0);\r\n b.push(0);\r\n b.push(Math.floor(this._length / 0x100000000));\r\n b.push(this._length | 0);\r\n\r\n while (b.length) {\r\n this._block(b.splice(0,32));\r\n }\r\n\r\n this.reset();\r\n return h;\r\n },\r\n\r\n /**\r\n * The SHA-512 initialization vector, to be precomputed.\r\n * @private\r\n */\r\n _init:[],\r\n\r\n /**\r\n * Least significant 24 bits of SHA512 initialization values.\r\n *\r\n * Javascript only has 53 bits of precision, so we compute the 40 most\r\n * significant bits and add the remaining 24 bits as constants.\r\n *\r\n * @private\r\n */\r\n _initr: [ 0xbcc908, 0xcaa73b, 0x94f82b, 0x1d36f1, 0xe682d1, 0x3e6c1f, 0x41bd6b, 0x7e2179 ],\r\n\r\n /*\r\n _init:\r\n [0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\r\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179],\r\n */\r\n\r\n /**\r\n * The SHA-512 hash key, to be precomputed.\r\n * @private\r\n */\r\n _key:[],\r\n\r\n /**\r\n * Least significant 24 bits of SHA512 key values.\r\n * @private\r\n */\r\n _keyr:\r\n [0x28ae22, 0xef65cd, 0x4d3b2f, 0x89dbbc, 0x48b538, 0x05d019, 0x194f9b, 0x6d8118,\r\n 0x030242, 0x706fbe, 0xe4b28c, 0xffb4e2, 0x7b896f, 0x1696b1, 0xc71235, 0x692694,\r\n 0xf14ad2, 0x4f25e3, 0x8cd5b5, 0xac9c65, 0x2b0275, 0xa6e483, 0x41fbd4, 0x1153b5,\r\n 0x66dfab, 0xb43210, 0xfb213f, 0xef0ee4, 0xa88fc2, 0x0aa725, 0x03826f, 0x0e6e70,\r\n 0xd22ffc, 0x26c926, 0xc42aed, 0x95b3df, 0xaf63de, 0x77b2a8, 0xedaee6, 0x82353b,\r\n 0xf10364, 0x423001, 0xf89791, 0x54be30, 0xef5218, 0x65a910, 0x71202a, 0xbbd1b8,\r\n 0xd2d0c8, 0x41ab53, 0x8eeb99, 0x9b48a8, 0xc95a63, 0x418acb, 0x63e373, 0xb2b8a3,\r\n 0xefb2fc, 0x172f60, 0xf0ab72, 0x6439ec, 0x631e28, 0x82bde9, 0xc67915, 0x72532b,\r\n 0x26619c, 0xc0c207, 0xe0eb1e, 0x6ed178, 0x176fba, 0xc898a6, 0xf90dae, 0x1c471b,\r\n 0x047d84, 0xc72493, 0xc9bebc, 0x100d4c, 0x3e42b6, 0x657e2a, 0xd6faec, 0x475817],\r\n\r\n /*\r\n _key:\r\n [0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\r\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\r\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\r\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\r\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\r\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\r\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\r\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\r\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\r\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\r\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\r\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\r\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\r\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\r\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\r\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\r\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\r\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\r\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\r\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817],\r\n */\r\n\r\n /**\r\n * Function to precompute _init and _key.\r\n * @private\r\n */\r\n _precompute: function () {\r\n // XXX: This code is for precomputing the SHA256 constants, change for\r\n // SHA512 and re-enable.\r\n var i = 0, prime = 2, factor;\r\n\r\n function frac(x) { return (x-Math.floor(x)) * 0x100000000 | 0; }\r\n function frac2(x) { return (x-Math.floor(x)) * 0x10000000000 & 0xff; }\r\n\r\n outer: for (; i<80; prime++) {\r\n for (factor=2; factor*factor <= prime; factor++) {\r\n if (prime % factor === 0) {\r\n // not a prime\r\n continue outer;\r\n }\r\n }\r\n\r\n if (i<8) {\r\n this._init[i*2] = frac(Math.pow(prime, 1/2));\r\n this._init[i*2+1] = (frac2(Math.pow(prime, 1/2)) << 24) | this._initr[i];\r\n }\r\n this._key[i*2] = frac(Math.pow(prime, 1/3));\r\n this._key[i*2+1] = (frac2(Math.pow(prime, 1/3)) << 24) | this._keyr[i];\r\n i++;\r\n }\r\n },\r\n\r\n /**\r\n * Perform one cycle of SHA-512.\r\n * @param {bitArray} words one block of words.\r\n * @private\r\n */\r\n _block:function (words) {\r\n var i, wrh, wrl,\r\n w = words.slice(0),\r\n h = this._h,\r\n k = this._key,\r\n h0h = h[ 0], h0l = h[ 1], h1h = h[ 2], h1l = h[ 3],\r\n h2h = h[ 4], h2l = h[ 5], h3h = h[ 6], h3l = h[ 7],\r\n h4h = h[ 8], h4l = h[ 9], h5h = h[10], h5l = h[11],\r\n h6h = h[12], h6l = h[13], h7h = h[14], h7l = h[15];\r\n\r\n // Working variables\r\n var ah = h0h, al = h0l, bh = h1h, bl = h1l,\r\n ch = h2h, cl = h2l, dh = h3h, dl = h3l,\r\n eh = h4h, el = h4l, fh = h5h, fl = h5l,\r\n gh = h6h, gl = h6l, hh = h7h, hl = h7l;\r\n\r\n for (i=0; i<80; i++) {\r\n // load up the input word for this round\r\n if (i<16) {\r\n wrh = w[i * 2];\r\n wrl = w[i * 2 + 1];\r\n } else {\r\n // Gamma0\r\n var gamma0xh = w[(i-15) * 2];\r\n var gamma0xl = w[(i-15) * 2 + 1];\r\n var gamma0h =\r\n ((gamma0xl << 31) | (gamma0xh >>> 1)) ^\r\n ((gamma0xl << 24) | (gamma0xh >>> 8)) ^\r\n (gamma0xh >>> 7);\r\n var gamma0l =\r\n ((gamma0xh << 31) | (gamma0xl >>> 1)) ^\r\n ((gamma0xh << 24) | (gamma0xl >>> 8)) ^\r\n ((gamma0xh << 25) | (gamma0xl >>> 7));\r\n\r\n // Gamma1\r\n var gamma1xh = w[(i-2) * 2];\r\n var gamma1xl = w[(i-2) * 2 + 1];\r\n var gamma1h =\r\n ((gamma1xl << 13) | (gamma1xh >>> 19)) ^\r\n ((gamma1xh << 3) | (gamma1xl >>> 29)) ^\r\n (gamma1xh >>> 6);\r\n var gamma1l =\r\n ((gamma1xh << 13) | (gamma1xl >>> 19)) ^\r\n ((gamma1xl << 3) | (gamma1xh >>> 29)) ^\r\n ((gamma1xh << 26) | (gamma1xl >>> 6));\r\n\r\n // Shortcuts\r\n var wr7h = w[(i-7) * 2];\r\n var wr7l = w[(i-7) * 2 + 1];\r\n\r\n var wr16h = w[(i-16) * 2];\r\n var wr16l = w[(i-16) * 2 + 1];\r\n\r\n // W(round) = gamma0 + W(round - 7) + gamma1 + W(round - 16)\r\n wrl = gamma0l + wr7l;\r\n wrh = gamma0h + wr7h + ((wrl >>> 0) < (gamma0l >>> 0) ? 1 : 0);\r\n wrl += gamma1l;\r\n wrh += gamma1h + ((wrl >>> 0) < (gamma1l >>> 0) ? 1 : 0);\r\n wrl += wr16l;\r\n wrh += wr16h + ((wrl >>> 0) < (wr16l >>> 0) ? 1 : 0);\r\n }\r\n\r\n w[i*2] = wrh |= 0;\r\n w[i*2 + 1] = wrl |= 0;\r\n\r\n // Ch\r\n var chh = (eh & fh) ^ (~eh & gh);\r\n var chl = (el & fl) ^ (~el & gl);\r\n\r\n // Maj\r\n var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);\r\n var majl = (al & bl) ^ (al & cl) ^ (bl & cl);\r\n\r\n // Sigma0\r\n var sigma0h = ((al << 4) | (ah >>> 28)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));\r\n var sigma0l = ((ah << 4) | (al >>> 28)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));\r\n\r\n // Sigma1\r\n var sigma1h = ((el << 18) | (eh >>> 14)) ^ ((el << 14) | (eh >>> 18)) ^ ((eh << 23) | (el >>> 9));\r\n var sigma1l = ((eh << 18) | (el >>> 14)) ^ ((eh << 14) | (el >>> 18)) ^ ((el << 23) | (eh >>> 9));\r\n\r\n // K(round)\r\n var krh = k[i*2];\r\n var krl = k[i*2+1];\r\n\r\n // t1 = h + sigma1 + ch + K(round) + W(round)\r\n var t1l = hl + sigma1l;\r\n var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);\r\n t1l += chl;\r\n t1h += chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);\r\n t1l += krl;\r\n t1h += krh + ((t1l >>> 0) < (krl >>> 0) ? 1 : 0);\r\n t1l += wrl;\r\n t1h += wrh + ((t1l >>> 0) < (wrl >>> 0) ? 1 : 0);\r\n\r\n // t2 = sigma0 + maj\r\n var t2l = sigma0l + majl;\r\n var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);\r\n\r\n // Update working variables\r\n hh = gh;\r\n hl = gl;\r\n gh = fh;\r\n gl = fl;\r\n fh = eh;\r\n fl = el;\r\n el = (dl + t1l) | 0;\r\n eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;\r\n dh = ch;\r\n dl = cl;\r\n ch = bh;\r\n cl = bl;\r\n bh = ah;\r\n bl = al;\r\n al = (t1l + t2l) | 0;\r\n ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;\r\n }\r\n\r\n // Intermediate hash\r\n h0l = h[1] = (h0l + al) | 0;\r\n h[0] = (h0h + ah + ((h0l >>> 0) < (al >>> 0) ? 1 : 0)) | 0;\r\n h1l = h[3] = (h1l + bl) | 0;\r\n h[2] = (h1h + bh + ((h1l >>> 0) < (bl >>> 0) ? 1 : 0)) | 0;\r\n h2l = h[5] = (h2l + cl) | 0;\r\n h[4] = (h2h + ch + ((h2l >>> 0) < (cl >>> 0) ? 1 : 0)) | 0;\r\n h3l = h[7] = (h3l + dl) | 0;\r\n h[6] = (h3h + dh + ((h3l >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;\r\n h4l = h[9] = (h4l + el) | 0;\r\n h[8] = (h4h + eh + ((h4l >>> 0) < (el >>> 0) ? 1 : 0)) | 0;\r\n h5l = h[11] = (h5l + fl) | 0;\r\n h[10] = (h5h + fh + ((h5l >>> 0) < (fl >>> 0) ? 1 : 0)) | 0;\r\n h6l = h[13] = (h6l + gl) | 0;\r\n h[12] = (h6h + gh + ((h6l >>> 0) < (gl >>> 0) ? 1 : 0)) | 0;\r\n h7l = h[15] = (h7l + hl) | 0;\r\n h[14] = (h7h + hh + ((h7l >>> 0) < (hl >>> 0) ? 1 : 0)) | 0;\r\n }\r\n};\r\n\r\n\r\n\r\n/** @fileOverview Javascript SHA-1 implementation.\r\n *\r\n * Based on the implementation in RFC 3174, method 1, and on the SJCL\r\n * SHA-256 implementation.\r\n *\r\n * @author Quinn Slack\r\n */\r\n\r\n/**\r\n * Context for a SHA-1 operation in progress.\r\n * @constructor\r\n * @class Secure Hash Algorithm, 160 bits.\r\n */\r\nsjcl.hash.sha1 = function (hash) {\r\n if (hash) {\r\n this._h = hash._h.slice(0);\r\n this._buffer = hash._buffer.slice(0);\r\n this._length = hash._length;\r\n } else {\r\n this.reset();\r\n }\r\n};\r\n\r\n/**\r\n * Hash a string or an array of words.\r\n * @static\r\n * @param {bitArray|String} data the data to hash.\r\n * @return {bitArray} The hash value, an array of 5 big-endian words.\r\n */\r\nsjcl.hash.sha1.hash = function (data) {\r\n return (new sjcl.hash.sha1()).update(data).finalize();\r\n};\r\n\r\nsjcl.hash.sha1.prototype = {\r\n /**\r\n * The hash's block size, in bits.\r\n * @constant\r\n */\r\n blockSize: 512,\r\n \r\n /**\r\n * Reset the hash state.\r\n * @return this\r\n */\r\n reset:function () {\r\n this._h = this._init.slice(0);\r\n this._buffer = [];\r\n this._length = 0;\r\n return this;\r\n },\r\n \r\n /**\r\n * Input several words to the hash.\r\n * @param {bitArray|String} data the data to hash.\r\n * @return this\r\n */\r\n update: function (data) {\r\n if (typeof data === \"string\") {\r\n data = sjcl.codec.utf8String.toBits(data);\r\n }\r\n var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),\r\n ol = this._length,\r\n nl = this._length = ol + sjcl.bitArray.bitLength(data);\r\n for (i = this.blockSize+ol & -this.blockSize; i <= nl;\r\n i+= this.blockSize) {\r\n this._block(b.splice(0,16));\r\n }\r\n return this;\r\n },\r\n \r\n /**\r\n * Complete hashing and output the hash value.\r\n * @return {bitArray} The hash value, an array of 5 big-endian words. TODO\r\n */\r\n finalize:function () {\r\n var i, b = this._buffer, h = this._h;\r\n\r\n // Round out and push the buffer\r\n b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1,1)]);\r\n // Round out the buffer to a multiple of 16 words, less the 2 length words.\r\n for (i = b.length + 2; i & 15; i++) {\r\n b.push(0);\r\n }\r\n\r\n // append the length\r\n b.push(Math.floor(this._length / 0x100000000));\r\n b.push(this._length | 0);\r\n\r\n while (b.length) {\r\n this._block(b.splice(0,16));\r\n }\r\n\r\n this.reset();\r\n return h;\r\n },\r\n\r\n /**\r\n * The SHA-1 initialization vector.\r\n * @private\r\n */\r\n _init:[0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0],\r\n\r\n /**\r\n * The SHA-1 hash key.\r\n * @private\r\n */\r\n _key:[0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6],\r\n\r\n /**\r\n * The SHA-1 logical functions f(0), f(1), ..., f(79).\r\n * @private\r\n */\r\n _f:function(t, b, c, d) {\r\n if (t <= 19) {\r\n return (b & c) | (~b & d);\r\n } else if (t <= 39) {\r\n return b ^ c ^ d;\r\n } else if (t <= 59) {\r\n return (b & c) | (b & d) | (c & d);\r\n } else if (t <= 79) {\r\n return b ^ c ^ d;\r\n }\r\n },\r\n\r\n /**\r\n * Circular left-shift operator.\r\n * @private\r\n */\r\n _S:function(n, x) {\r\n return (x << n) | (x >>> 32-n);\r\n },\r\n \r\n /**\r\n * Perform one cycle of SHA-1.\r\n * @param {bitArray} words one block of words.\r\n * @private\r\n */\r\n _block:function (words) { \r\n var t, tmp, a, b, c, d, e,\r\n w = words.slice(0),\r\n h = this._h,\r\n k = this._key;\r\n \r\n a = h[0]; b = h[1]; c = h[2]; d = h[3]; e = h[4]; \r\n\r\n for (t=0; t<=79; t++) {\r\n if (t >= 16) {\r\n w[t] = this._S(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]);\r\n }\r\n tmp = (this._S(5, a) + this._f(t, b, c, d) + e + w[t] +\r\n this._key[Math.floor(t/20)]) | 0;\r\n e = d;\r\n d = c;\r\n c = this._S(30, b);\r\n b = a;\r\n a = tmp;\r\n }\r\n\r\n h[0] = (h[0]+a) |0;\r\n h[1] = (h[1]+b) |0;\r\n h[2] = (h[2]+c) |0;\r\n h[3] = (h[3]+d) |0;\r\n h[4] = (h[4]+e) |0;\r\n }\r\n};\r\n\r\n/** @fileOverview CCM mode implementation.\r\n *\r\n * Special thanks to Roy Nicholson for pointing out a bug in our\r\n * implementation.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** @namespace CTR mode with CBC MAC. */\r\nsjcl.mode.ccm = {\r\n /** The name of the mode.\r\n * @constant\r\n */\r\n name: \"ccm\",\r\n \r\n /** Encrypt in CCM mode.\r\n * @static\r\n * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.\r\n * @param {bitArray} plaintext The plaintext data.\r\n * @param {bitArray} iv The initialization value.\r\n * @param {bitArray} [adata=[]] The authenticated data.\r\n * @param {Number} [tlen=64] the desired tag length, in bits.\r\n * @return {bitArray} The encrypted data, an array of bytes.\r\n */\r\n encrypt: function(prf, plaintext, iv, adata, tlen) {\r\n var L, i, out = plaintext.slice(0), tag, w=sjcl.bitArray, ivl = w.bitLength(iv) / 8, ol = w.bitLength(out) / 8;\r\n tlen = tlen || 64;\r\n adata = adata || [];\r\n \r\n if (ivl < 7) {\r\n throw new sjcl.exception.invalid(\"ccm: iv must be at least 7 bytes\");\r\n }\r\n \r\n // compute the length of the length\r\n for (L=2; L<4 && ol >>> 8*L; L++) {}\r\n if (L < 15 - ivl) { L = 15-ivl; }\r\n iv = w.clamp(iv,8*(15-L));\r\n \r\n // compute the tag\r\n tag = sjcl.mode.ccm._computeTag(prf, plaintext, iv, adata, tlen, L);\r\n \r\n // encrypt\r\n out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);\r\n \r\n return w.concat(out.data, out.tag);\r\n },\r\n \r\n /** Decrypt in CCM mode.\r\n * @static\r\n * @param {Object} prf The pseudorandom function. It must have a block size of 16 bytes.\r\n * @param {bitArray} ciphertext The ciphertext data.\r\n * @param {bitArray} iv The initialization value.\r\n * @param {bitArray} [[]] adata The authenticated data.\r\n * @param {Number} [64] tlen the desired tag length, in bits.\r\n * @return {bitArray} The decrypted data.\r\n */\r\n decrypt: function(prf, ciphertext, iv, adata, tlen) {\r\n tlen = tlen || 64;\r\n adata = adata || [];\r\n var L, i, \r\n w=sjcl.bitArray,\r\n ivl = w.bitLength(iv) / 8,\r\n ol = w.bitLength(ciphertext), \r\n out = w.clamp(ciphertext, ol - tlen),\r\n tag = w.bitSlice(ciphertext, ol - tlen), tag2;\r\n \r\n\r\n ol = (ol - tlen) / 8;\r\n \r\n if (ivl < 7) {\r\n throw new sjcl.exception.invalid(\"ccm: iv must be at least 7 bytes\");\r\n }\r\n \r\n // compute the length of the length\r\n for (L=2; L<4 && ol >>> 8*L; L++) {}\r\n if (L < 15 - ivl) { L = 15-ivl; }\r\n iv = w.clamp(iv,8*(15-L));\r\n \r\n // decrypt\r\n out = sjcl.mode.ccm._ctrMode(prf, out, iv, tag, tlen, L);\r\n \r\n // check the tag\r\n tag2 = sjcl.mode.ccm._computeTag(prf, out.data, iv, adata, tlen, L);\r\n if (!w.equal(out.tag, tag2)) {\r\n throw new sjcl.exception.corrupt(\"ccm: tag doesn't match\");\r\n }\r\n \r\n return out.data;\r\n },\r\n\r\n /* Compute the (unencrypted) authentication tag, according to the CCM specification\r\n * @param {Object} prf The pseudorandom function.\r\n * @param {bitArray} plaintext The plaintext data.\r\n * @param {bitArray} iv The initialization value.\r\n * @param {bitArray} adata The authenticated data.\r\n * @param {Number} tlen the desired tag length, in bits.\r\n * @return {bitArray} The tag, but not yet encrypted.\r\n * @private\r\n */\r\n _computeTag: function(prf, plaintext, iv, adata, tlen, L) {\r\n // compute B[0]\r\n var q, mac, field = 0, offset = 24, tmp, i, macData = [], w=sjcl.bitArray, xor = w._xor4;\r\n\r\n tlen /= 8;\r\n \r\n // check tag length and message length\r\n if (tlen % 2 || tlen < 4 || tlen > 16) {\r\n throw new sjcl.exception.invalid(\"ccm: invalid tag length\");\r\n }\r\n \r\n if (adata.length > 0xFFFFFFFF || plaintext.length > 0xFFFFFFFF) {\r\n // I don't want to deal with extracting high words from doubles.\r\n throw new sjcl.exception.bug(\"ccm: can't deal with 4GiB or more data\");\r\n }\r\n\r\n // mac the flags\r\n mac = [w.partial(8, (adata.length ? 1<<6 : 0) | (tlen-2) << 2 | L-1)];\r\n\r\n // mac the iv and length\r\n mac = w.concat(mac, iv);\r\n mac[3] |= w.bitLength(plaintext)/8;\r\n mac = prf.encrypt(mac);\r\n \r\n \r\n if (adata.length) {\r\n // mac the associated data. start with its length...\r\n tmp = w.bitLength(adata)/8;\r\n if (tmp <= 0xFEFF) {\r\n macData = [w.partial(16, tmp)];\r\n } else if (tmp <= 0xFFFFFFFF) {\r\n macData = w.concat([w.partial(16,0xFFFE)], [tmp]);\r\n } // else ...\r\n \r\n // mac the data itself\r\n macData = w.concat(macData, adata);\r\n for (i=0; i<macData.length; i += 4) {\r\n mac = prf.encrypt(xor(mac, macData.slice(i,i+4).concat([0,0,0])));\r\n }\r\n }\r\n \r\n // mac the plaintext\r\n for (i=0; i<plaintext.length; i+=4) {\r\n mac = prf.encrypt(xor(mac, plaintext.slice(i,i+4).concat([0,0,0])));\r\n }\r\n\r\n return w.clamp(mac, tlen * 8);\r\n },\r\n\r\n /** CCM CTR mode.\r\n * Encrypt or decrypt data and tag with the prf in CCM-style CTR mode.\r\n * May mutate its arguments.\r\n * @param {Object} prf The PRF.\r\n * @param {bitArray} data The data to be encrypted or decrypted.\r\n * @param {bitArray} iv The initialization vector.\r\n * @param {bitArray} tag The authentication tag.\r\n * @param {Number} tlen The length of th etag, in bits.\r\n * @param {Number} L The CCM L value.\r\n * @return {Object} An object with data and tag, the en/decryption of data and tag values.\r\n * @private\r\n */\r\n _ctrMode: function(prf, data, iv, tag, tlen, L) {\r\n var enc, i, w=sjcl.bitArray, xor = w._xor4, ctr, b, l = data.length, bl=w.bitLength(data);\r\n\r\n // start the ctr\r\n ctr = w.concat([w.partial(8,L-1)],iv).concat([0,0,0]).slice(0,4);\r\n \r\n // en/decrypt the tag\r\n tag = w.bitSlice(xor(tag,prf.encrypt(ctr)), 0, tlen);\r\n \r\n // en/decrypt the data\r\n if (!l) { return {tag:tag, data:[]}; }\r\n \r\n for (i=0; i<l; i+=4) {\r\n ctr[3]++;\r\n enc = prf.encrypt(ctr);\r\n data[i] ^= enc[0];\r\n data[i+1] ^= enc[1];\r\n data[i+2] ^= enc[2];\r\n data[i+3] ^= enc[3];\r\n }\r\n return { tag:tag, data:w.clamp(data,bl) };\r\n }\r\n};\r\n\r\n/** @fileOverview HMAC implementation.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** HMAC with the specified hash function.\r\n * @constructor\r\n * @param {bitArray} key the key for HMAC.\r\n * @param {Object} [hash=sjcl.hash.sha256] The hash function to use.\r\n */\r\nsjcl.misc.hmac = function (key, Hash) {\r\n this._hash = Hash = Hash || sjcl.hash.sha256;\r\n var exKey = [[],[]], i,\r\n bs = Hash.prototype.blockSize / 32;\r\n this._baseHash = [new Hash(), new Hash()];\r\n\r\n if (key.length > bs) {\r\n key = Hash.hash(key);\r\n }\r\n \r\n for (i=0; i<bs; i++) {\r\n exKey[0][i] = key[i]^0x36363636;\r\n exKey[1][i] = key[i]^0x5C5C5C5C;\r\n }\r\n \r\n this._baseHash[0].update(exKey[0]);\r\n this._baseHash[1].update(exKey[1]);\r\n};\r\n\r\n/** HMAC with the specified hash function. Also called encrypt since it's a prf.\r\n * @param {bitArray|String} data The data to mac.\r\n */\r\nsjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function (data) {\r\n var w = new (this._hash)(this._baseHash[0]).update(data).finalize();\r\n return new (this._hash)(this._baseHash[1]).update(w).finalize();\r\n};\r\n\r\n\r\n/** @fileOverview Password-based key-derivation function, version 2.0.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** Password-Based Key-Derivation Function, version 2.0.\r\n *\r\n * Generate keys from passwords using PBKDF2-HMAC-SHA256.\r\n *\r\n * This is the method specified by RSA's PKCS #5 standard.\r\n *\r\n * @param {bitArray|String} password The password.\r\n * @param {bitArray} salt The salt. Should have lots of entropy.\r\n * @param {Number} [count=1000] The number of iterations. Higher numbers make the function slower but more secure.\r\n * @param {Number} [length] The length of the derived key. Defaults to the\r\n output size of the hash function.\r\n * @param {Object} [Prff=sjcl.misc.hmac] The pseudorandom function family.\r\n * @return {bitArray} the derived key.\r\n */\r\nsjcl.misc.pbkdf2 = function (password, salt, count, length, Prff) {\r\n count = count || 1000;\r\n \r\n if (length < 0 || count < 0) {\r\n throw sjcl.exception.invalid(\"invalid params to pbkdf2\");\r\n }\r\n \r\n if (typeof password === \"string\") {\r\n password = sjcl.codec.utf8String.toBits(password);\r\n }\r\n \r\n Prff = Prff || sjcl.misc.hmac;\r\n \r\n var prf = new Prff(password),\r\n u, ui, i, j, k, out = [], b = sjcl.bitArray;\r\n\r\n for (k = 1; 32 * out.length < (length || 1); k++) {\r\n u = ui = prf.encrypt(b.concat(salt,[k]));\r\n \r\n for (i=1; i<count; i++) {\r\n ui = prf.encrypt(ui);\r\n for (j=0; j<ui.length; j++) {\r\n u[j] ^= ui[j];\r\n }\r\n }\r\n \r\n out = out.concat(u);\r\n }\r\n\r\n if (length) { out = b.clamp(out, length); }\r\n\r\n return out;\r\n};\r\n\r\n/** @fileOverview Random number generator.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n\r\n/** @constructor\r\n * @class Random number generator\r\n *\r\n * @description\r\n * <p>\r\n * This random number generator is a derivative of Ferguson and Schneier's\r\n * generator Fortuna. It collects entropy from various events into several\r\n * pools, implemented by streaming SHA-256 instances. It differs from\r\n * ordinary Fortuna in a few ways, though.\r\n * </p>\r\n *\r\n * <p>\r\n * Most importantly, it has an entropy estimator. This is present because\r\n * there is a strong conflict here between making the generator available\r\n * as soon as possible, and making sure that it doesn't \"run on empty\".\r\n * In Fortuna, there is a saved state file, and the system is likely to have\r\n * time to warm up.\r\n * </p>\r\n *\r\n * <p>\r\n * Second, because users are unlikely to stay on the page for very long,\r\n * and to speed startup time, the number of pools increases logarithmically:\r\n * a new pool is created when the previous one is actually used for a reseed.\r\n * This gives the same asymptotic guarantees as Fortuna, but gives more\r\n * entropy to early reseeds.\r\n * </p>\r\n *\r\n * <p>\r\n * The entire mechanism here feels pretty klunky. Furthermore, there are\r\n * several improvements that should be made, including support for\r\n * dedicated cryptographic functions that may be present in some browsers;\r\n * state files in local storage; cookies containing randomness; etc. So\r\n * look for improvements in future versions.\r\n * </p>\r\n */\r\nsjcl.prng = function(defaultParanoia) {\r\n \r\n /* private */\r\n this._pools = [new sjcl.hash.sha256()];\r\n this._poolEntropy = [0];\r\n this._reseedCount = 0;\r\n this._robins = {};\r\n this._eventId = 0;\r\n \r\n this._collectorIds = {};\r\n this._collectorIdNext = 0;\r\n \r\n this._strength = 0;\r\n this._poolStrength = 0;\r\n this._nextReseed = 0;\r\n this._key = [0,0,0,0,0,0,0,0];\r\n this._counter = [0,0,0,0];\r\n this._cipher = undefined;\r\n this._defaultParanoia = defaultParanoia;\r\n \r\n /* event listener stuff */\r\n this._collectorsStarted = false;\r\n this._callbacks = {progress: {}, seeded: {}};\r\n this._callbackI = 0;\r\n \r\n /* constants */\r\n this._NOT_READY = 0;\r\n this._READY = 1;\r\n this._REQUIRES_RESEED = 2;\r\n\r\n this._MAX_WORDS_PER_BURST = 65536;\r\n this._PARANOIA_LEVELS = [0,48,64,96,128,192,256,384,512,768,1024];\r\n this._MILLISECONDS_PER_RESEED = 30000;\r\n this._BITS_PER_RESEED = 80;\r\n}\r\n \r\nsjcl.prng.prototype = {\r\n /** Generate several random words, and return them in an array\r\n * @param {Number} nwords The number of words to generate.\r\n */\r\n randomWords: function (nwords, paranoia) {\r\n var out = [], i, readiness = this.isReady(paranoia), g;\r\n \r\n if (readiness === this._NOT_READY) {\r\n throw new sjcl.exception.notReady(\"generator isn't seeded\");\r\n } else if (readiness & this._REQUIRES_RESEED) {\r\n this._reseedFromPools(!(readiness & this._READY));\r\n }\r\n \r\n for (i=0; i<nwords; i+= 4) {\r\n if ((i+1) % this._MAX_WORDS_PER_BURST === 0) {\r\n this._gate();\r\n }\r\n \r\n g = this._gen4words();\r\n out.push(g[0],g[1],g[2],g[3]);\r\n }\r\n this._gate();\r\n \r\n return out.slice(0,nwords);\r\n },\r\n \r\n setDefaultParanoia: function (paranoia) {\r\n this._defaultParanoia = paranoia;\r\n },\r\n \r\n /**\r\n * Add entropy to the pools.\r\n * @param data The entropic value. Should be a 32-bit integer, array of 32-bit integers, or string\r\n * @param {Number} estimatedEntropy The estimated entropy of data, in bits\r\n * @param {String} source The source of the entropy, eg \"mouse\"\r\n */\r\n addEntropy: function (data, estimatedEntropy, source) {\r\n source = source || \"user\";\r\n \r\n var id,\r\n i, tmp,\r\n t = (new Date()).valueOf(),\r\n robin = this._robins[source],\r\n oldReady = this.isReady(), err = 0;\r\n \r\n id = this._collectorIds[source];\r\n if (id === undefined) { id = this._collectorIds[source] = this._collectorIdNext ++; }\r\n \r\n if (robin === undefined) { robin = this._robins[source] = 0; }\r\n this._robins[source] = ( this._robins[source] + 1 ) % this._pools.length;\r\n \r\n switch(typeof(data)) {\r\n \r\n case \"number\":\r\n if (estimatedEntropy === undefined) {\r\n estimatedEntropy = 1;\r\n }\r\n this._pools[robin].update([id,this._eventId++,1,estimatedEntropy,t,1,data|0]);\r\n break;\r\n \r\n case \"object\":\r\n var objName = Object.prototype.toString.call(data);\r\n if (objName === \"[object Uint32Array]\") {\r\n tmp = [];\r\n for (i = 0; i < data.length; i++) {\r\n tmp.push(data[i]);\r\n }\r\n data = tmp;\r\n } else {\r\n if (objName !== \"[object Array]\") {\r\n err = 1;\r\n }\r\n for (i=0; i<data.length && !err; i++) {\r\n if (typeof(data[i]) != \"number\") {\r\n err = 1;\r\n }\r\n }\r\n }\r\n if (!err) {\r\n if (estimatedEntropy === undefined) {\r\n /* horrible entropy estimator */\r\n estimatedEntropy = 0;\r\n for (i=0; i<data.length; i++) {\r\n tmp= data[i];\r\n while (tmp>0) {\r\n estimatedEntropy++;\r\n tmp = tmp >>> 1;\r\n }\r\n }\r\n }\r\n this._pools[robin].update([id,this._eventId++,2,estimatedEntropy,t,data.length].concat(data));\r\n }\r\n break;\r\n \r\n case \"string\":\r\n if (estimatedEntropy === undefined) {\r\n /* English text has just over 1 bit per character of entropy.\r\n * But this might be HTML or something, and have far less\r\n * entropy than English... Oh well, let's just say one bit.\r\n */\r\n estimatedEntropy = data.length;\r\n }\r\n this._pools[robin].update([id,this._eventId++,3,estimatedEntropy,t,data.length]);\r\n this._pools[robin].update(data);\r\n break;\r\n \r\n default:\r\n err=1;\r\n }\r\n if (err) {\r\n throw new sjcl.exception.bug(\"random: addEntropy only supports number, array of numbers or string\");\r\n }\r\n \r\n /* record the new strength */\r\n this._poolEntropy[robin] += estimatedEntropy;\r\n this._poolStrength += estimatedEntropy;\r\n \r\n /* fire off events */\r\n if (oldReady === this._NOT_READY) {\r\n if (this.isReady() !== this._NOT_READY) {\r\n this._fireEvent(\"seeded\", Math.max(this._strength, this._poolStrength));\r\n }\r\n this._fireEvent(\"progress\", this.getProgress());\r\n }\r\n },\r\n \r\n /** Is the generator ready? */\r\n isReady: function (paranoia) {\r\n var entropyRequired = this._PARANOIA_LEVELS[ (paranoia !== undefined) ? paranoia : this._defaultParanoia ];\r\n \r\n if (this._strength && this._strength >= entropyRequired) {\r\n return (this._poolEntropy[0] > this._BITS_PER_RESEED && (new Date()).valueOf() > this._nextReseed) ?\r\n this._REQUIRES_RESEED | this._READY :\r\n this._READY;\r\n } else {\r\n return (this._poolStrength >= entropyRequired) ?\r\n this._REQUIRES_RESEED | this._NOT_READY :\r\n this._NOT_READY;\r\n }\r\n },\r\n \r\n /** Get the generator's progress toward readiness, as a fraction */\r\n getProgress: function (paranoia) {\r\n var entropyRequired = this._PARANOIA_LEVELS[ paranoia ? paranoia : this._defaultParanoia ];\r\n \r\n if (this._strength >= entropyRequired) {\r\n return 1.0;\r\n } else {\r\n return (this._poolStrength > entropyRequired) ?\r\n 1.0 :\r\n this._poolStrength / entropyRequired;\r\n }\r\n },\r\n \r\n /** start the built-in entropy collectors */\r\n startCollectors: function () {\r\n if (this._collectorsStarted) { return; }\r\n \r\n if (window.addEventListener) {\r\n window.addEventListener(\"load\", this._loadTimeCollector, false);\r\n window.addEventListener(\"mousemove\", this._mouseCollector, false);\r\n } else if (document.attachEvent) {\r\n document.attachEvent(\"onload\", this._loadTimeCollector);\r\n document.attachEvent(\"onmousemove\", this._mouseCollector);\r\n }\r\n else {\r\n throw new sjcl.exception.bug(\"can't attach event\");\r\n }\r\n \r\n this._collectorsStarted = true;\r\n },\r\n \r\n /** stop the built-in entropy collectors */\r\n stopCollectors: function () {\r\n if (!this._collectorsStarted) { return; }\r\n \r\n if (window.removeEventListener) {\r\n window.removeEventListener(\"load\", this._loadTimeCollector, false);\r\n window.removeEventListener(\"mousemove\", this._mouseCollector, false);\r\n } else if (window.detachEvent) {\r\n window.detachEvent(\"onload\", this._loadTimeCollector);\r\n window.detachEvent(\"onmousemove\", this._mouseCollector);\r\n }\r\n this._collectorsStarted = false;\r\n },\r\n \r\n /* use a cookie to store entropy.\r\n useCookie: function (all_cookies) {\r\n throw new sjcl.exception.bug(\"random: useCookie is unimplemented\");\r\n },*/\r\n \r\n /** add an event listener for progress or seeded-ness. */\r\n addEventListener: function (name, callback) {\r\n this._callbacks[name][this._callbackI++] = callback;\r\n },\r\n \r\n /** remove an event listener for progress or seeded-ness */\r\n removeEventListener: function (name, cb) {\r\n var i, j, cbs=this._callbacks[name], jsTemp=[];\r\n \r\n /* I'm not sure if this is necessary; in C++, iterating over a\r\n * collection and modifying it at the same time is a no-no.\r\n */\r\n \r\n for (j in cbs) {\r\n\tif (cbs.hasOwnProperty(j) && cbs[j] === cb) {\r\n jsTemp.push(j);\r\n }\r\n }\r\n \r\n for (i=0; i<jsTemp.length; i++) {\r\n j = jsTemp[i];\r\n delete cbs[j];\r\n }\r\n },\r\n \r\n /** Generate 4 random words, no reseed, no gate.\r\n * @private\r\n */\r\n _gen4words: function () {\r\n for (var i=0; i<4; i++) {\r\n this._counter[i] = this._counter[i]+1 | 0;\r\n if (this._counter[i]) { break; }\r\n }\r\n return this._cipher.encrypt(this._counter);\r\n },\r\n \r\n /* Rekey the AES instance with itself after a request, or every _MAX_WORDS_PER_BURST words.\r\n * @private\r\n */\r\n _gate: function () {\r\n this._key = this._gen4words().concat(this._gen4words());\r\n this._cipher = new sjcl.cipher.aes(this._key);\r\n },\r\n \r\n /** Reseed the generator with the given words\r\n * @private\r\n */\r\n _reseed: function (seedWords) {\r\n this._key = sjcl.hash.sha256.hash(this._key.concat(seedWords));\r\n this._cipher = new sjcl.cipher.aes(this._key);\r\n for (var i=0; i<4; i++) {\r\n this._counter[i] = this._counter[i]+1 | 0;\r\n if (this._counter[i]) { break; }\r\n }\r\n },\r\n \r\n /** reseed the data from the entropy pools\r\n * @param full If set, use all the entropy pools in the reseed.\r\n */\r\n _reseedFromPools: function (full) {\r\n var reseedData = [], strength = 0, i;\r\n \r\n this._nextReseed = reseedData[0] =\r\n (new Date()).valueOf() + this._MILLISECONDS_PER_RESEED;\r\n \r\n for (i=0; i<16; i++) {\r\n /* On some browsers, this is cryptographically random. So we might\r\n * as well toss it in the pot and stir...\r\n */\r\n reseedData.push(Math.random()*0x100000000|0);\r\n }\r\n \r\n for (i=0; i<this._pools.length; i++) {\r\n reseedData = reseedData.concat(this._pools[i].finalize());\r\n strength += this._poolEntropy[i];\r\n this._poolEntropy[i] = 0;\r\n \r\n if (!full && (this._reseedCount & (1<<i))) { break; }\r\n }\r\n \r\n /* if we used the last pool, push a new one onto the stack */\r\n if (this._reseedCount >= 1 << this._pools.length) {\r\n this._pools.push(new sjcl.hash.sha256());\r\n this._poolEntropy.push(0);\r\n }\r\n \r\n /* how strong was this reseed? */\r\n this._poolStrength -= strength;\r\n if (strength > this._strength) {\r\n this._strength = strength;\r\n }\r\n \r\n this._reseedCount ++;\r\n this._reseed(reseedData);\r\n },\r\n \r\n _mouseCollector: function (ev) {\r\n var x = ev.x || ev.clientX || ev.offsetX || 0, y = ev.y || ev.clientY || ev.offsetY || 0;\r\n sjcl.random.addEntropy([x,y], 2, \"mouse\");\r\n },\r\n \r\n _loadTimeCollector: function (ev) {\r\n sjcl.random.addEntropy((new Date()).valueOf(), 2, \"loadtime\");\r\n },\r\n \r\n _fireEvent: function (name, arg) {\r\n var j, cbs=sjcl.random._callbacks[name], cbsTemp=[];\r\n /* TODO: there is a race condition between removing collectors and firing them */ \r\n\r\n /* I'm not sure if this is necessary; in C++, iterating over a\r\n * collection and modifying it at the same time is a no-no.\r\n */\r\n \r\n for (j in cbs) {\r\n if (cbs.hasOwnProperty(j)) {\r\n cbsTemp.push(cbs[j]);\r\n }\r\n }\r\n \r\n for (j=0; j<cbsTemp.length; j++) {\r\n cbsTemp[j](arg);\r\n }\r\n }\r\n};\r\n\r\nsjcl.random = new sjcl.prng(6);\r\n\r\n(function(){\r\n try {\r\n // get cryptographically strong entropy in Webkit\r\n var ab = new Uint32Array(32);\r\n crypto.getRandomValues(ab);\r\n sjcl.random.addEntropy(ab, 1024, \"crypto.getRandomValues\");\r\n } catch (e) {\r\n // no getRandomValues :-(\r\n }\r\n})();\r\n\r\n/** @fileOverview Convenince functions centered around JSON encapsulation.\r\n *\r\n * @author Emily Stark\r\n * @author Mike Hamburg\r\n * @author Dan Boneh\r\n */\r\n \r\n /** @namespace JSON encapsulation */\r\n sjcl.json = {\r\n /** Default values for encryption */\r\n defaults: { v:1, iter:1000, ks:128, ts:64, mode:\"ccm\", adata:\"\", cipher:\"aes\" },\r\n\r\n /** Simple encryption function.\r\n * @param {String|bitArray} password The password or key.\r\n * @param {String} plaintext The data to encrypt.\r\n * @param {Object} [params] The parameters including tag, iv and salt.\r\n * @param {Object} [rp] A returned version with filled-in parameters.\r\n * @return {String} The ciphertext.\r\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\r\n */\r\n encrypt: function (password, plaintext, params, rp) {\r\n params = params || {};\r\n rp = rp || {};\r\n \r\n var j = sjcl.json, p = j._add({ iv: sjcl.random.randomWords(4,0) },\r\n j.defaults), tmp, prp, adata;\r\n j._add(p, params);\r\n adata = p.adata;\r\n if (typeof p.salt === \"string\") {\r\n p.salt = sjcl.codec.base64.toBits(p.salt);\r\n }\r\n if (typeof p.iv === \"string\") {\r\n p.iv = sjcl.codec.base64.toBits(p.iv);\r\n }\r\n \r\n if (!sjcl.mode[p.mode] ||\r\n !sjcl.cipher[p.cipher] ||\r\n (typeof password === \"string\" && p.iter <= 100) ||\r\n (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||\r\n (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||\r\n (p.iv.length < 2 || p.iv.length > 4)) {\r\n throw new sjcl.exception.invalid(\"json encrypt: invalid parameters\");\r\n }\r\n \r\n if (typeof password === \"string\") {\r\n tmp = sjcl.misc.cachedPbkdf2(password, p);\r\n password = tmp.key.slice(0,p.ks/32);\r\n p.salt = tmp.salt;\r\n } else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.publicKey) {\r\n tmp = password.kem();\r\n p.kemtag = tmp.tag;\r\n password = tmp.key.slice(0,p.ks/32);\r\n }\r\n if (typeof plaintext === \"string\") {\r\n plaintext = sjcl.codec.utf8String.toBits(plaintext);\r\n }\r\n if (typeof adata === \"string\") {\r\n adata = sjcl.codec.utf8String.toBits(adata);\r\n }\r\n prp = new sjcl.cipher[p.cipher](password);\r\n \r\n /* return the json data */\r\n j._add(rp, p);\r\n rp.key = password;\r\n \r\n /* do the encryption */\r\n p.ct = sjcl.mode[p.mode].encrypt(prp, plaintext, p.iv, adata, p.ts);\r\n \r\n //return j.encode(j._subtract(p, j.defaults));\r\n return j.encode(p);\r\n },\r\n \r\n /** Simple decryption function.\r\n * @param {String|bitArray} password The password or key.\r\n * @param {String} ciphertext The ciphertext to decrypt.\r\n * @param {Object} [params] Additional non-default parameters.\r\n * @param {Object} [rp] A returned object with filled parameters.\r\n * @return {String} The plaintext.\r\n * @throws {sjcl.exception.invalid} if a parameter is invalid.\r\n * @throws {sjcl.exception.corrupt} if the ciphertext is corrupt.\r\n */\r\n decrypt: function (password, ciphertext, params, rp) {\r\n params = params || {};\r\n rp = rp || {};\r\n \r\n var j = sjcl.json, p = j._add(j._add(j._add({},j.defaults),j.decode(ciphertext)), params, true), ct, tmp, prp, adata=p.adata;\r\n if (typeof p.salt === \"string\") {\r\n p.salt = sjcl.codec.base64.toBits(p.salt);\r\n }\r\n if (typeof p.iv === \"string\") {\r\n p.iv = sjcl.codec.base64.toBits(p.iv);\r\n }\r\n \r\n if (!sjcl.mode[p.mode] ||\r\n !sjcl.cipher[p.cipher] ||\r\n (typeof password === \"string\" && p.iter <= 100) ||\r\n (p.ts !== 64 && p.ts !== 96 && p.ts !== 128) ||\r\n (p.ks !== 128 && p.ks !== 192 && p.ks !== 256) ||\r\n (!p.iv) ||\r\n (p.iv.length < 2 || p.iv.length > 4)) {\r\n throw new sjcl.exception.invalid(\"json decrypt: invalid parameters\");\r\n }\r\n \r\n if (typeof password === \"string\") {\r\n tmp = sjcl.misc.cachedPbkdf2(password, p);\r\n password = tmp.key.slice(0,p.ks/32);\r\n p.salt = tmp.salt;\r\n } else if (sjcl.ecc && password instanceof sjcl.ecc.elGamal.secretKey) {\r\n password = password.unkem(sjcl.codec.base64.toBits(p.kemtag)).slice(0,p.ks/32);\r\n }\r\n if (typeof adata === \"string\") {\r\n adata = sjcl.codec.utf8String.toBits(adata);\r\n }\r\n prp = new sjcl.cipher[p.cipher](password);\r\n \r\n /* do the decryption */\r\n ct = sjcl.mode[p.mode].decrypt(prp, p.ct, p.iv, adata, p.ts);\r\n \r\n /* return the json data */\r\n j._add(rp, p);\r\n rp.key = password;\r\n \r\n return sjcl.codec.utf8String.fromBits(ct);\r\n },\r\n \r\n /** Encode a flat structure into a JSON string.\r\n * @param {Object} obj The structure to encode.\r\n * @return {String} A JSON string.\r\n * @throws {sjcl.exception.invalid} if obj has a non-alphanumeric property.\r\n * @throws {sjcl.exception.bug} if a parameter has an unsupported type.\r\n */\r\n encode: function (obj) {\r\n var i, out='{', comma='';\r\n for (i in obj) {\r\n if (obj.hasOwnProperty(i)) {\r\n if (!i.match(/^[a-z0-9]+$/i)) {\r\n throw new sjcl.exception.invalid(\"json encode: invalid property name\");\r\n }\r\n out += comma + '\"' + i + '\":';\r\n comma = ',';\r\n \r\n switch (typeof obj[i]) {\r\n case 'number':\r\n case 'boolean':\r\n out += obj[i];\r\n break;\r\n \r\n case 'string':\r\n out += '\"' + escape(obj[i]) + '\"';\r\n break;\r\n \r\n case 'object':\r\n out += '\"' + sjcl.codec.base64.fromBits(obj[i],0) + '\"';\r\n break;\r\n \r\n default:\r\n throw new sjcl.exception.bug(\"json encode: unsupported type\");\r\n }\r\n }\r\n }\r\n return out+'}';\r\n },\r\n \r\n /** Decode a simple (flat) JSON string into a structure. The ciphertext,\r\n * adata, salt and iv will be base64-decoded.\r\n * @param {String} str The string.\r\n * @return {Object} The decoded structure.\r\n * @throws {sjcl.exception.invalid} if str isn't (simple) JSON.\r\n */\r\n decode: function (str) {\r\n str = str.replace(/\\s/g,'');\r\n if (!str.match(/^\\{.*\\}$/)) { \r\n throw new sjcl.exception.invalid(\"json decode: this isn't json!\");\r\n }\r\n var a = str.replace(/^\\{|\\}$/g, '').split(/,/), out={}, i, m;\r\n for (i=0; i<a.length; i++) {\r\n if (!(m=a[i].match(/^(?:([\"']?)([a-z][a-z0-9]*)\\1):(?:(\\d+)|\"([a-z0-9+\\/%*_.@=\\-]*)\")$/i))) {\r\n throw new sjcl.exception.invalid(\"json decode: this isn't json!\");\r\n }\r\n if (m[3]) {\r\n out[m[2]] = parseInt(m[3],10);\r\n } else {\r\n out[m[2]] = m[2].match(/^(ct|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);\r\n }\r\n }\r\n return out;\r\n },\r\n \r\n /** Insert all elements of src into target, modifying and returning target.\r\n * @param {Object} target The object to be modified.\r\n * @param {Object} src The object to pull data from.\r\n * @param {boolean} [requireSame=false] If true, throw an exception if any field of target differs from corresponding field of src.\r\n * @return {Object} target.\r\n * @private\r\n */\r\n _add: function (target, src, requireSame) {\r\n if (target === undefined) { target = {}; }\r\n if (src === undefined) { return target; }\r\n var i;\r\n for (i in src) {\r\n if (src.hasOwnProperty(i)) {\r\n if (requireSame && target[i] !== undefined && target[i] !== src[i]) {\r\n throw new sjcl.exception.invalid(\"required parameter overridden\");\r\n }\r\n target[i] = src[i];\r\n }\r\n }\r\n return target;\r\n },\r\n \r\n /** Remove all elements of minus from plus. Does not modify plus.\r\n * @private\r\n */\r\n _subtract: function (plus, minus) {\r\n var out = {}, i;\r\n \r\n for (i in plus) {\r\n if (plus.hasOwnProperty(i) && plus[i] !== minus[i]) {\r\n out[i] = plus[i];\r\n }\r\n }\r\n \r\n return out;\r\n },\r\n \r\n /** Return only the specified elements of src.\r\n * @private\r\n */\r\n _filter: function (src, filter) {\r\n var out = {}, i;\r\n for (i=0; i<filter.length; i++) {\r\n if (src[filter[i]] !== undefined) {\r\n out[filter[i]] = src[filter[i]];\r\n }\r\n }\r\n return out;\r\n }\r\n};\r\n\r\n/** Simple encryption function; convenient shorthand for sjcl.json.encrypt.\r\n * @param {String|bitArray} password The password or key.\r\n * @param {String} plaintext The data to encrypt.\r\n * @param {Object} [params] The parameters including tag, iv and salt.\r\n * @param {Object} [rp] A returned version with filled-in parameters.\r\n * @return {String} The ciphertext.\r\n */\r\nsjcl.encrypt = sjcl.json.encrypt;\r\n\r\n/** Simple decryption function; convenient shorthand for sjcl.json.decrypt.\r\n * @param {String|bitArray} password The password or key.\r\n * @param {String} ciphertext The ciphertext to decrypt.\r\n * @param {Object} [params] Additional non-default parameters.\r\n * @param {Object} [rp] A returned object with filled parameters.\r\n * @return {String} The plaintext.\r\n */\r\nsjcl.decrypt = sjcl.json.decrypt;\r\n\r\n/** The cache for cachedPbkdf2.\r\n * @private\r\n */\r\nsjcl.misc._pbkdf2Cache = {};\r\n\r\n/** Cached PBKDF2 key derivation.\r\n * @param {String} password The password.\r\n * @param {Object} [params] The derivation params (iteration count and optional salt).\r\n * @return {Object} The derived data in key, the salt in salt.\r\n */\r\nsjcl.misc.cachedPbkdf2 = function (password, obj) {\r\n var cache = sjcl.misc._pbkdf2Cache, c, cp, str, salt, iter;\r\n \r\n obj = obj || {};\r\n iter = obj.iter || 1000;\r\n \r\n /* open the cache for this password and iteration count */\r\n cp = cache[password] = cache[password] || {};\r\n c = cp[iter] = cp[iter] || { firstSalt: (obj.salt && obj.salt.length) ?\r\n obj.salt.slice(0) : sjcl.random.randomWords(2,0) };\r\n \r\n salt = (obj.salt === undefined) ? c.firstSalt : obj.salt;\r\n \r\n c[salt] = c[salt] || sjcl.misc.pbkdf2(password, salt, obj.iter);\r\n return { key: c[salt].slice(0), salt:salt.slice(0) };\r\n};\r\n\r\n\r\n\r\n/**\r\n * @constructor\r\n * Constructs a new bignum from another bignum, a number or a hex string.\r\n */\r\nsjcl.bn = function(it) {\r\n this.initWith(it);\r\n};\r\n\r\nsjcl.bn.prototype = {\r\n radix: 24,\r\n maxMul: 8,\r\n _class: sjcl.bn,\r\n \r\n copy: function() {\r\n return new this._class(this);\r\n },\r\n\r\n /**\r\n * Initializes this with it, either as a bn, a number, or a hex string.\r\n */\r\n initWith: function(it) {\r\n var i=0, k, n, l;\r\n switch(typeof it) {\r\n case \"object\":\r\n this.limbs = it.limbs.slice(0);\r\n break;\r\n \r\n case \"number\":\r\n this.limbs = [it];\r\n this.normalize();\r\n break;\r\n \r\n case \"string\":\r\n it = it.replace(/^0x/, '');\r\n this.limbs = [];\r\n // hack\r\n k = this.radix / 4;\r\n for (i=0; i < it.length; i+=k) {\r\n this.limbs.push(parseInt(it.substring(Math.max(it.length - i - k, 0), it.length - i),16));\r\n }\r\n break;\r\n\r\n default:\r\n this.limbs = [0];\r\n }\r\n return this;\r\n },\r\n\r\n /**\r\n * Returns true if \"this\" and \"that\" are equal. Calls fullReduce().\r\n * Equality test is in constant time.\r\n */\r\n equals: function(that) {\r\n if (typeof that === \"number\") { that = new this._class(that); }\r\n var difference = 0, i;\r\n this.fullReduce();\r\n that.fullReduce();\r\n for (i = 0; i < this.limbs.length || i < that.limbs.length; i++) {\r\n difference |= this.getLimb(i) ^ that.getLimb(i);\r\n }\r\n return (difference === 0);\r\n },\r\n \r\n /**\r\n * Get the i'th limb of this, zero if i is too large.\r\n */\r\n getLimb: function(i) {\r\n return (i >= this.limbs.length) ? 0 : this.limbs[i];\r\n },\r\n \r\n /**\r\n * Constant time comparison function.\r\n * Returns 1 if this >= that, or zero otherwise.\r\n */\r\n greaterEquals: function(that) {\r\n if (typeof that === \"number\") { that = new this._class(that); }\r\n var less = 0, greater = 0, i, a, b;\r\n i = Math.max(this.limbs.length, that.limbs.length) - 1;\r\n for (; i>= 0; i--) {\r\n a = this.getLimb(i);\r\n b = that.getLimb(i);\r\n greater |= (b - a) & ~less;\r\n less |= (a - b) & ~greater;\r\n }\r\n return (greater | ~less) >>> 31;\r\n },\r\n \r\n /**\r\n * Convert to a hex string.\r\n */\r\n toString: function() {\r\n this.fullReduce();\r\n var out=\"\", i, s, l = this.limbs;\r\n for (i=0; i < this.limbs.length; i++) {\r\n s = l[i].toString(16);\r\n while (i < this.limbs.length - 1 && s.length < 6) {\r\n s = \"0\" + s;\r\n }\r\n out = s + out;\r\n }\r\n return \"0x\"+out;\r\n },\r\n \r\n /** this += that. Does not normalize. */\r\n addM: function(that) {\r\n if (typeof(that) !== \"object\") { that = new this._class(that); }\r\n var i, l=this.limbs, ll=that.limbs;\r\n for (i=l.length; i<ll.length; i++) {\r\n l[i] = 0;\r\n }\r\n for (i=0; i<ll.length; i++) {\r\n l[i] += ll[i];\r\n }\r\n return this;\r\n },\r\n \r\n /** this *= 2. Requires normalized; ends up normalized. */\r\n doubleM: function() {\r\n var i, carry=0, tmp, r=this.radix, m=this.radixMask, l=this.limbs;\r\n for (i=0; i<l.length; i++) {\r\n tmp = l[i];\r\n tmp = tmp+tmp+carry;\r\n l[i] = tmp & m;\r\n carry = tmp >> r;\r\n }\r\n if (carry) {\r\n l.push(carry);\r\n }\r\n return this;\r\n },\r\n \r\n /** this /= 2, rounded down. Requires normalized; ends up normalized. */\r\n halveM: function() {\r\n var i, carry=0, tmp, r=this.radix, l=this.limbs;\r\n for (i=l.length-1; i>=0; i--) {\r\n tmp = l[i];\r\n l[i] = (tmp+carry)>>1;\r\n carry = (tmp&1) << r;\r\n }\r\n if (!l[l.length-1]) {\r\n l.pop();\r\n }\r\n return this;\r\n },\r\n\r\n /** this -= that. Does not normalize. */\r\n subM: function(that) {\r\n if (typeof(that) !== \"object\") { that = new this._class(that); }\r\n var i, l=this.limbs, ll=that.limbs;\r\n for (i=l.length; i<ll.length; i++) {\r\n l[i] = 0;\r\n }\r\n for (i=0; i<ll.length; i++) {\r\n l[i] -= ll[i];\r\n }\r\n return this;\r\n },\r\n \r\n mod: function(that) {\r\n var neg = !this.greaterEquals(new sjcl.bn(0));\r\n \r\n that = new sjcl.bn(that).normalize(); // copy before we begin\r\n var out = new sjcl.bn(this).normalize(), ci=0;\r\n \r\n if (neg) out = (new sjcl.bn(0)).subM(out).normalize();\r\n \r\n for (; out.greaterEquals(that); ci++) {\r\n that.doubleM();\r\n }\r\n \r\n if (neg) out = that.sub(out).normalize();\r\n \r\n for (; ci > 0; ci--) {\r\n that.halveM();\r\n if (out.greaterEquals(that)) {\r\n out.subM(that).normalize();\r\n }\r\n }\r\n return out.trim();\r\n },\r\n \r\n /** return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p. */\r\n inverseMod: function(p) {\r\n var a = new sjcl.bn(1), b = new sjcl.bn(0), x = new sjcl.bn(this), y = new sjcl.bn(p), tmp, i, nz=1;\r\n \r\n if (!(p.limbs[0] & 1)) {\r\n throw (new sjcl.exception.invalid(\"inverseMod: p must be odd\"));\r\n }\r\n \r\n // invariant: y is odd\r\n do {\r\n if (x.limbs[0] & 1) {\r\n if (!x.greaterEquals(y)) {\r\n // x < y; swap everything\r\n tmp = x; x = y; y = tmp;\r\n tmp = a; a = b; b = tmp;\r\n }\r\n x.subM(y);\r\n x.normalize();\r\n \r\n if (!a.greaterEquals(b)) {\r\n a.addM(p);\r\n }\r\n a.subM(b);\r\n }\r\n \r\n // cut everything in half\r\n x.halveM();\r\n if (a.limbs[0] & 1) {\r\n a.addM(p);\r\n }\r\n a.normalize();\r\n a.halveM();\r\n \r\n // check for termination: x ?= 0\r\n for (i=nz=0; i<x.limbs.length; i++) {\r\n nz |= x.limbs[i];\r\n }\r\n } while(nz);\r\n \r\n if (!y.equals(1)) {\r\n throw (new sjcl.exception.invalid(\"inverseMod: p and x must be relatively prime\"));\r\n }\r\n \r\n return b;\r\n },\r\n \r\n /** this + that. Does not normalize. */\r\n add: function(that) {\r\n return this.copy().addM(that);\r\n },\r\n\r\n /** this - that. Does not normalize. */\r\n sub: function(that) {\r\n return this.copy().subM(that);\r\n },\r\n \r\n /** this * that. Normalizes and reduces. */\r\n mul: function(that) {\r\n if (typeof(that) === \"number\") { that = new this._class(that); }\r\n var i, j, a = this.limbs, b = that.limbs, al = a.length, bl = b.length, out = new this._class(), c = out.limbs, ai, ii=this.maxMul;\r\n\r\n for (i=0; i < this.limbs.length + that.limbs.length + 1; i++) {\r\n c[i] = 0;\r\n }\r\n for (i=0; i<al; i++) {\r\n ai = a[i];\r\n for (j=0; j<bl; j++) {\r\n c[i+j] += ai * b[j];\r\n }\r\n \r\n if (!--ii) {\r\n ii = this.maxMul;\r\n out.cnormalize();\r\n }\r\n }\r\n return out.cnormalize().reduce();\r\n },\r\n\r\n /** this ^ 2. Normalizes and reduces. */\r\n square: function() {\r\n return this.mul(this);\r\n },\r\n\r\n /** this ^ n. Uses square-and-multiply. Normalizes and reduces. */\r\n power: function(l) {\r\n if (typeof(l) === \"number\") {\r\n l = [l];\r\n } else if (l.limbs !== undefined) {\r\n l = l.normalize().limbs;\r\n }\r\n var i, j, out = new this._class(1), pow = this;\r\n\r\n for (i=0; i<l.length; i++) {\r\n for (j=0; j<this.radix; j++) {\r\n if (l[i] & (1<<j)) {\r\n out = out.mul(pow);\r\n }\r\n pow = pow.square();\r\n }\r\n }\r\n \r\n return out;\r\n },\r\n\r\n /** this * that mod N */\r\n mulmod: function(that, N) {\r\n return this.mod(N).mul(that.mod(N)).mod(N);\r\n },\r\n\r\n /** this ^ x mod N */\r\n powermod: function(x, N) {\r\n var result = new sjcl.bn(1), a = new sjcl.bn(this), k = new sjcl.bn(x);\r\n while (true) {\r\n if (k.limbs[0] & 1) { result = result.mulmod(a, N); }\r\n k.halveM();\r\n if (k.equals(0)) { break; }\r\n a = a.mulmod(a, N);\r\n }\r\n return result.normalize().reduce();\r\n },\r\n\r\n trim: function() {\r\n var l = this.limbs, p;\r\n do {\r\n p = l.pop();\r\n } while (l.length && p === 0);\r\n l.push(p);\r\n return this;\r\n },\r\n \r\n /** Reduce mod a modulus. Stubbed for subclassing. */\r\n reduce: function() {\r\n return this;\r\n },\r\n\r\n /** Reduce and normalize. */\r\n fullReduce: function() {\r\n return this.normalize();\r\n },\r\n \r\n /** Propagate carries. */\r\n normalize: function() {\r\n var carry=0, i, pv = this.placeVal, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;\r\n for (i=0; i < ll || (carry !== 0 && carry !== -1); i++) {\r\n l = (limbs[i]||0) + carry;\r\n m = limbs[i] = l & mask;\r\n carry = (l-m)*ipv;\r\n }\r\n if (carry === -1) {\r\n limbs[i-1] -= this.placeVal;\r\n }\r\n return this;\r\n },\r\n\r\n /** Constant-time normalize. Does not allocate additional space. */\r\n cnormalize: function() {\r\n var carry=0, i, ipv = this.ipv, l, m, limbs = this.limbs, ll = limbs.length, mask = this.radixMask;\r\n for (i=0; i < ll-1; i++) {\r\n l = limbs[i] + carry;\r\n m = limbs[i] = l & mask;\r\n carry = (l-m)*ipv;\r\n }\r\n limbs[i] += carry;\r\n return this;\r\n },\r\n \r\n /** Serialize to a bit array */\r\n toBits: function(len) {\r\n this.fullReduce();\r\n len = len || this.exponent || this.bitLength();\r\n var i = Math.floor((len-1)/24), w=sjcl.bitArray, e = (len + 7 & -8) % this.radix || this.radix,\r\n out = [w.partial(e, this.getLimb(i))];\r\n for (i--; i >= 0; i--) {\r\n out = w.concat(out, [w.partial(Math.min(this.radix,len), this.getLimb(i))]);\r\n len -= this.radix;\r\n }\r\n return out;\r\n },\r\n \r\n /** Return the length in bits, rounded up to the nearest byte. */\r\n bitLength: function() {\r\n this.fullReduce();\r\n var out = this.radix * (this.limbs.length - 1),\r\n b = this.limbs[this.limbs.length - 1];\r\n for (; b; b >>>= 1) {\r\n out ++;\r\n }\r\n return out+7 & -8;\r\n }\r\n};\r\n\r\n/** @this { sjcl.bn } */\r\nsjcl.bn.fromBits = function(bits) {\r\n var Class = this, out = new Class(), words=[], w=sjcl.bitArray, t = this.prototype,\r\n l = Math.min(this.bitLength || 0x100000000, w.bitLength(bits)), e = l % t.radix || t.radix;\r\n \r\n words[0] = w.extract(bits, 0, e);\r\n for (; e < l; e += t.radix) {\r\n words.unshift(w.extract(bits, e, t.radix));\r\n }\r\n\r\n out.limbs = words;\r\n return out;\r\n};\r\n\r\n\r\n\r\nsjcl.bn.prototype.ipv = 1 / (sjcl.bn.prototype.placeVal = Math.pow(2,sjcl.bn.prototype.radix));\r\nsjcl.bn.prototype.radixMask = (1 << sjcl.bn.prototype.radix) - 1;\r\n\r\n/**\r\n * Creates a new subclass of bn, based on reduction modulo a pseudo-Mersenne prime,\r\n * i.e. a prime of the form 2^e + sum(a * 2^b),where the sum is negative and sparse.\r\n */\r\nsjcl.bn.pseudoMersennePrime = function(exponent, coeff) {\r\n /** @constructor */\r\n function p(it) {\r\n this.initWith(it);\r\n /*if (this.limbs[this.modOffset]) {\r\n this.reduce();\r\n }*/\r\n }\r\n\r\n var ppr = p.prototype = new sjcl.bn(), i, tmp, mo;\r\n mo = ppr.modOffset = Math.ceil(tmp = exponent / ppr.radix);\r\n ppr.exponent = exponent;\r\n ppr.offset = [];\r\n ppr.factor = [];\r\n ppr.minOffset = mo;\r\n ppr.fullMask = 0;\r\n ppr.fullOffset = [];\r\n ppr.fullFactor = [];\r\n ppr.modulus = p.modulus = new sjcl.bn(Math.pow(2,exponent));\r\n \r\n ppr.fullMask = 0|-Math.pow(2, exponent % ppr.radix);\r\n\r\n for (i=0; i<coeff.length; i++) {\r\n ppr.offset[i] = Math.floor(coeff[i][0] / ppr.radix - tmp);\r\n ppr.fullOffset[i] = Math.ceil(coeff[i][0] / ppr.radix - tmp);\r\n ppr.factor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.offset[i] * ppr.radix);\r\n ppr.fullFactor[i] = coeff[i][1] * Math.pow(1/2, exponent - coeff[i][0] + ppr.fullOffset[i] * ppr.radix);\r\n ppr.modulus.addM(new sjcl.bn(Math.pow(2,coeff[i][0])*coeff[i][1]));\r\n ppr.minOffset = Math.min(ppr.minOffset, -ppr.offset[i]); // conservative\r\n }\r\n ppr._class = p;\r\n ppr.modulus.cnormalize();\r\n\r\n /** Approximate reduction mod p. May leave a number which is negative or slightly larger than p.\r\n * @this {sjcl.bn}\r\n */\r\n ppr.reduce = function() {\r\n var i, k, l, mo = this.modOffset, limbs = this.limbs, aff, off = this.offset, ol = this.offset.length, fac = this.factor, ll;\r\n\r\n i = this.minOffset;\r\n while (limbs.length > mo) {\r\n l = limbs.pop();\r\n ll = limbs.length;\r\n for (k=0; k<ol; k++) {\r\n limbs[ll+off[k]] -= fac[k] * l;\r\n }\r\n \r\n i--;\r\n if (!i) {\r\n limbs.push(0);\r\n this.cnormalize();\r\n i = this.minOffset;\r\n }\r\n }\r\n this.cnormalize();\r\n\r\n return this;\r\n };\r\n \r\n /** @this {sjcl.bn} */\r\n ppr._strongReduce = (ppr.fullMask === -1) ? ppr.reduce : function() {\r\n var limbs = this.limbs, i = limbs.length - 1, k, l;\r\n this.reduce();\r\n if (i === this.modOffset - 1) {\r\n l = limbs[i] & this.fullMask;\r\n limbs[i] -= l;\r\n for (k=0; k<this.fullOffset.length; k++) {\r\n limbs[i+this.fullOffset[k]] -= this.fullFactor[k] * l;\r\n }\r\n this.normalize();\r\n }\r\n };\r\n\r\n /** mostly constant-time, very expensive full reduction.\r\n * @this {sjcl.bn}\r\n */\r\n ppr.fullReduce = function() {\r\n var greater, i;\r\n // massively above the modulus, may be negative\r\n \r\n this._strongReduce();\r\n // less than twice the modulus, may be negative\r\n\r\n this.addM(this.modulus);\r\n this.addM(this.modulus);\r\n this.normalize();\r\n // probably 2-3x the modulus\r\n \r\n this._strongReduce();\r\n // less than the power of 2. still may be more than\r\n // the modulus\r\n\r\n // HACK: pad out to this length\r\n for (i=this.limbs.length; i<this.modOffset; i++) {\r\n this.limbs[i] = 0;\r\n }\r\n \r\n // constant-time subtract modulus\r\n greater = this.greaterEquals(this.modulus);\r\n for (i=0; i<this.limbs.length; i++) {\r\n this.limbs[i] -= this.modulus.limbs[i] * greater;\r\n }\r\n this.cnormalize();\r\n\r\n return this;\r\n };\r\n\r\n\r\n /** @this {sjcl.bn} */\r\n ppr.inverse = function() {\r\n return (this.power(this.modulus.sub(2)));\r\n };\r\n\r\n p.fromBits = sjcl.bn.fromBits;\r\n\r\n return p;\r\n};\r\n\r\n// a small Mersenne prime\r\nsjcl.bn.prime = {\r\n p127: sjcl.bn.pseudoMersennePrime(127, [[0,-1]]),\r\n\r\n // Bernstein's prime for Curve25519\r\n p25519: sjcl.bn.pseudoMersennePrime(255, [[0,-19]]),\r\n\r\n // NIST primes\r\n p192: sjcl.bn.pseudoMersennePrime(192, [[0,-1],[64,-1]]),\r\n p224: sjcl.bn.pseudoMersennePrime(224, [[0,1],[96,-1]]),\r\n p256: sjcl.bn.pseudoMersennePrime(256, [[0,-1],[96,1],[192,1],[224,-1]]),\r\n p384: sjcl.bn.pseudoMersennePrime(384, [[0,-1],[32,1],[96,-1],[128,-1]]),\r\n p521: sjcl.bn.pseudoMersennePrime(521, [[0,-1]])\r\n};\r\n\r\nsjcl.bn.random = function(modulus, paranoia) {\r\n if (typeof modulus !== \"object\") { modulus = new sjcl.bn(modulus); }\r\n var words, i, l = modulus.limbs.length, m = modulus.limbs[l-1]+1, out = new sjcl.bn();\r\n while (true) {\r\n // get a sequence whose first digits make sense\r\n do {\r\n words = sjcl.random.randomWords(l, paranoia);\r\n if (words[l-1] < 0) { words[l-1] += 0x100000000; }\r\n } while (Math.floor(words[l-1] / m) === Math.floor(0x100000000 / m));\r\n words[l-1] %= m;\r\n\r\n // mask off all the limbs\r\n for (i=0; i<l-1; i++) {\r\n words[i] &= modulus.radixMask;\r\n }\r\n\r\n // check the rest of the digitssj\r\n out.limbs = words;\r\n if (!out.greaterEquals(modulus)) {\r\n return out;\r\n }\r\n }\r\n};\r\n\r\n\r\nsjcl.ecc = {};\r\n\r\n/**\r\n * Represents a point on a curve in affine coordinates.\r\n * @constructor\r\n * @param {sjcl.ecc.curve} curve The curve that this point lies on.\r\n * @param {bigInt} x The x coordinate.\r\n * @param {bigInt} y The y coordinate.\r\n */\r\nsjcl.ecc.point = function(curve,x,y) {\r\n if (x === undefined) {\r\n this.isIdentity = true;\r\n } else {\r\n this.x = x;\r\n this.y = y;\r\n this.isIdentity = false;\r\n }\r\n this.curve = curve;\r\n};\r\n\r\n\r\n\r\nsjcl.ecc.point.prototype = {\r\n toJac: function() {\r\n return new sjcl.ecc.pointJac(this.curve, this.x, this.y, new this.curve.field(1));\r\n },\r\n\r\n mult: function(k) {\r\n return this.toJac().mult(k, this).toAffine();\r\n },\r\n \r\n /**\r\n * Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates.\r\n * @param {bigInt} k The coefficient to multiply this by.\r\n * @param {bigInt} k2 The coefficient to multiply affine2 this by.\r\n * @param {sjcl.ecc.point} affine The other point in affine coordinates.\r\n * @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates.\r\n */\r\n mult2: function(k, k2, affine2) {\r\n return this.toJac().mult2(k, this, k2, affine2).toAffine();\r\n },\r\n \r\n multiples: function() {\r\n var m, i, j;\r\n if (this._multiples === undefined) {\r\n j = this.toJac().doubl();\r\n m = this._multiples = [new sjcl.ecc.point(this.curve), this, j.toAffine()];\r\n for (i=3; i<16; i++) {\r\n j = j.add(this);\r\n m.push(j.toAffine());\r\n }\r\n }\r\n return this._multiples;\r\n },\r\n\r\n isValid: function() {\r\n return this.y.square().equals(this.curve.b.add(this.x.mul(this.curve.a.add(this.x.square()))));\r\n },\r\n\r\n toBits: function() {\r\n return sjcl.bitArray.concat(this.x.toBits(), this.y.toBits());\r\n }\r\n};\r\n\r\n/**\r\n * Represents a point on a curve in Jacobian coordinates. Coordinates can be specified as bigInts or strings (which\r\n * will be converted to bigInts).\r\n *\r\n * @constructor\r\n * @param {bigInt/string} x The x coordinate.\r\n * @param {bigInt/string} y The y coordinate.\r\n * @param {bigInt/string} z The z coordinate.\r\n * @param {sjcl.ecc.curve} curve The curve that this point lies on.\r\n */\r\nsjcl.ecc.pointJac = function(curve, x, y, z) {\r\n if (x === undefined) {\r\n this.isIdentity = true;\r\n } else {\r\n this.x = x;\r\n this.y = y;\r\n this.z = z;\r\n this.isIdentity = false;\r\n }\r\n this.curve = curve;\r\n};\r\n\r\nsjcl.ecc.pointJac.prototype = {\r\n /**\r\n * Adds S and T and returns the result in Jacobian coordinates. Note that S must be in Jacobian coordinates and T must be in affine coordinates.\r\n * @param {sjcl.ecc.pointJac} S One of the points to add, in Jacobian coordinates.\r\n * @param {sjcl.ecc.point} T The other point to add, in affine coordinates.\r\n * @return {sjcl.ecc.pointJac} The sum of the two points, in Jacobian coordinates. \r\n */\r\n add: function(T) {\r\n var S = this, sz2, c, d, c2, x1, x2, x, y1, y2, y, z;\r\n if (S.curve !== T.curve) {\r\n throw(\"sjcl.ecc.add(): Points must be on the same curve to add them!\");\r\n }\r\n\r\n if (S.isIdentity) {\r\n return T.toJac();\r\n } else if (T.isIdentity) {\r\n return S;\r\n }\r\n\r\n sz2 = S.z.square();\r\n c = T.x.mul(sz2).subM(S.x);\r\n\r\n if (c.equals(0)) {\r\n if (S.y.equals(T.y.mul(sz2.mul(S.z)))) {\r\n // same point\r\n return S.doubl();\r\n } else {\r\n // inverses\r\n return new sjcl.ecc.pointJac(S.curve);\r\n }\r\n }\r\n \r\n d = T.y.mul(sz2.mul(S.z)).subM(S.y);\r\n c2 = c.square();\r\n\r\n x1 = d.square();\r\n x2 = c.square().mul(c).addM( S.x.add(S.x).mul(c2) );\r\n x = x1.subM(x2);\r\n\r\n y1 = S.x.mul(c2).subM(x).mul(d);\r\n y2 = S.y.mul(c.square().mul(c));\r\n y = y1.subM(y2);\r\n\r\n z = S.z.mul(c);\r\n\r\n return new sjcl.ecc.pointJac(this.curve,x,y,z);\r\n },\r\n \r\n /**\r\n * doubles this point.\r\n * @return {sjcl.ecc.pointJac} The doubled point.\r\n */\r\n doubl: function() {\r\n if (this.isIdentity) { return this; }\r\n\r\n var\r\n y2 = this.y.square(),\r\n a = y2.mul(this.x.mul(4)),\r\n b = y2.square().mul(8),\r\n z2 = this.z.square(),\r\n c = this.x.sub(z2).mul(3).mul(this.x.add(z2)),\r\n x = c.square().subM(a).subM(a),\r\n y = a.sub(x).mul(c).subM(b),\r\n z = this.y.add(this.y).mul(this.z);\r\n return new sjcl.ecc.pointJac(this.curve, x, y, z);\r\n },\r\n\r\n /**\r\n * Returns a copy of this point converted to affine coordinates.\r\n * @return {sjcl.ecc.point} The converted point.\r\n */ \r\n toAffine: function() {\r\n if (this.isIdentity || this.z.equals(0)) {\r\n return new sjcl.ecc.point(this.curve);\r\n }\r\n var zi = this.z.inverse(), zi2 = zi.square();\r\n return new sjcl.ecc.point(this.curve, this.x.mul(zi2).fullReduce(), this.y.mul(zi2.mul(zi)).fullReduce());\r\n },\r\n \r\n /**\r\n * Multiply this point by k and return the answer in Jacobian coordinates.\r\n * @param {bigInt} k The coefficient to multiply by.\r\n * @param {sjcl.ecc.point} affine This point in affine coordinates.\r\n * @return {sjcl.ecc.pointJac} The result of the multiplication, in Jacobian coordinates.\r\n */\r\n mult: function(k, affine) {\r\n if (typeof(k) === \"number\") {\r\n k = [k];\r\n } else if (k.limbs !== undefined) {\r\n k = k.normalize().limbs;\r\n }\r\n \r\n var i, j, out = new sjcl.ecc.point(this.curve).toJac(), multiples = affine.multiples();\r\n\r\n for (i=k.length-1; i>=0; i--) {\r\n for (j=sjcl.bn.prototype.radix-4; j>=0; j-=4) {\r\n out = out.doubl().doubl().doubl().doubl().add(multiples[k[i]>>j & 0xF]);\r\n }\r\n }\r\n \r\n return out;\r\n },\r\n \r\n /**\r\n * Multiply this point by k, added to affine2*k2, and return the answer in Jacobian coordinates.\r\n * @param {bigInt} k The coefficient to multiply this by.\r\n * @param {sjcl.ecc.point} affine This point in affine coordinates.\r\n * @param {bigInt} k2 The coefficient to multiply affine2 this by.\r\n * @param {sjcl.ecc.point} affine The other point in affine coordinates.\r\n * @return {sjcl.ecc.pointJac} The result of the multiplication and addition, in Jacobian coordinates.\r\n */\r\n mult2: function(k1, affine, k2, affine2) {\r\n if (typeof(k1) === \"number\") {\r\n k1 = [k1];\r\n } else if (k1.limbs !== undefined) {\r\n k1 = k1.normalize().limbs;\r\n }\r\n \r\n if (typeof(k2) === \"number\") {\r\n k2 = [k2];\r\n } else if (k2.limbs !== undefined) {\r\n k2 = k2.normalize().limbs;\r\n }\r\n \r\n var i, j, out = new sjcl.ecc.point(this.curve).toJac(), m1 = affine.multiples(),\r\n m2 = affine2.multiples(), l1, l2;\r\n\r\n for (i=Math.max(k1.length,k2.length)-1; i>=0; i--) {\r\n l1 = k1[i] | 0;\r\n l2 = k2[i] | 0;\r\n for (j=sjcl.bn.prototype.radix-4; j>=0; j-=4) {\r\n out = out.doubl().doubl().doubl().doubl().add(m1[l1>>j & 0xF]).add(m2[l2>>j & 0xF]);\r\n }\r\n }\r\n \r\n return out;\r\n },\r\n\r\n isValid: function() {\r\n var z2 = this.z.square(), z4 = z2.square(), z6 = z4.mul(z2);\r\n return this.y.square().equals(\r\n this.curve.b.mul(z6).add(this.x.mul(\r\n this.curve.a.mul(z4).add(this.x.square()))));\r\n }\r\n};\r\n\r\n/**\r\n * Construct an elliptic curve. Most users will not use this and instead start with one of the NIST curves defined below.\r\n *\r\n * @constructor\r\n * @param {bigInt} p The prime modulus.\r\n * @param {bigInt} r The prime order of the curve.\r\n * @param {bigInt} a The constant a in the equation of the curve y^2 = x^3 + ax + b (for NIST curves, a is always -3).\r\n * @param {bigInt} x The x coordinate of a base point of the curve.\r\n * @param {bigInt} y The y coordinate of a base point of the curve.\r\n */\r\nsjcl.ecc.curve = function(Field, r, a, b, x, y) {\r\n this.field = Field;\r\n this.r = Field.prototype.modulus.sub(r);\r\n this.a = new Field(a);\r\n this.b = new Field(b);\r\n this.G = new sjcl.ecc.point(this, new Field(x), new Field(y));\r\n};\r\n\r\nsjcl.ecc.curve.prototype.fromBits = function (bits) {\r\n var w = sjcl.bitArray, l = this.field.prototype.exponent + 7 & -8,\r\n p = new sjcl.ecc.point(this, this.field.fromBits(w.bitSlice(bits, 0, l)),\r\n this.field.fromBits(w.bitSlice(bits, l, 2*l)));\r\n if (!p.isValid()) {\r\n throw new sjcl.exception.corrupt(\"not on the curve!\");\r\n }\r\n return p;\r\n};\r\n\r\nsjcl.ecc.curves = {\r\n c192: new sjcl.ecc.curve(\r\n sjcl.bn.prime.p192,\r\n \"0x662107c8eb94364e4b2dd7ce\",\r\n -3,\r\n \"0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1\",\r\n \"0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012\",\r\n \"0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811\"),\r\n\r\n c224: new sjcl.ecc.curve(\r\n sjcl.bn.prime.p224,\r\n \"0xe95c1f470fc1ec22d6baa3a3d5c4\",\r\n -3,\r\n \"0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4\",\r\n \"0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21\",\r\n \"0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34\"),\r\n\r\n c256: new sjcl.ecc.curve(\r\n sjcl.bn.prime.p256,\r\n \"0x4319055358e8617b0c46353d039cdaae\",\r\n -3,\r\n \"0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b\",\r\n \"0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296\",\r\n \"0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5\"),\r\n\r\n c384: new sjcl.ecc.curve(\r\n sjcl.bn.prime.p384,\r\n \"0x389cb27e0bc8d21fa7e5f24cb74f58851313e696333ad68c\",\r\n -3,\r\n \"0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef\",\r\n \"0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7\",\r\n \"0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f\")\r\n};\r\n\r\n\r\n/* Diffie-Hellman-like public-key system */\r\nsjcl.ecc._dh = function(cn) {\r\n sjcl.ecc[cn] = {\r\n /** @constructor */\r\n publicKey: function(curve, point) {\r\n this._curve = curve;\r\n this._curveBitLength = curve.r.bitLength();\r\n if (point instanceof Array) {\r\n this._point = curve.fromBits(point);\r\n } else {\r\n this._point = point;\r\n }\r\n\r\n this.get = function() {\r\n var pointbits = this._point.toBits();\r\n var len = sjcl.bitArray.bitLength(pointbits);\r\n var x = sjcl.bitArray.bitSlice(pointbits, 0, len/2);\r\n var y = sjcl.bitArray.bitSlice(pointbits, len/2);\r\n return { x: x, y: y };\r\n }\r\n },\r\n\r\n /** @constructor */\r\n secretKey: function(curve, exponent) {\r\n this._curve = curve;\r\n this._curveBitLength = curve.r.bitLength();\r\n this._exponent = exponent;\r\n\r\n this.get = function() {\r\n return this._exponent.toBits();\r\n }\r\n },\r\n\r\n /** @constructor */\r\n generateKeys: function(curve, paranoia, sec) {\r\n if (curve === undefined) {\r\n curve = 256;\r\n }\r\n if (typeof curve === \"number\") {\r\n curve = sjcl.ecc.curves['c'+curve];\r\n if (curve === undefined) {\r\n throw new sjcl.exception.invalid(\"no such curve\");\r\n }\r\n }\r\n if (sec === undefined) {\r\n var sec = sjcl.bn.random(curve.r, paranoia);\r\n }\r\n var pub = curve.G.mult(sec);\r\n return { pub: new sjcl.ecc[cn].publicKey(curve, pub),\r\n sec: new sjcl.ecc[cn].secretKey(curve, sec) };\r\n }\r\n }; \r\n};\r\n\r\nsjcl.ecc._dh(\"elGamal\");\r\n\r\nsjcl.ecc.elGamal.publicKey.prototype = {\r\n kem: function(paranoia) {\r\n var sec = sjcl.bn.random(this._curve.r, paranoia),\r\n tag = this._curve.G.mult(sec).toBits(),\r\n key = sjcl.hash.sha256.hash(this._point.mult(sec).toBits());\r\n return { key: key, tag: tag };\r\n }\r\n};\r\n\r\nsjcl.ecc.elGamal.secretKey.prototype = {\r\n unkem: function(tag) {\r\n return sjcl.hash.sha256.hash(this._curve.fromBits(tag).mult(this._exponent).toBits());\r\n },\r\n\r\n dh: function(pk) {\r\n return sjcl.hash.sha256.hash(pk._point.mult(this._exponent).toBits());\r\n }\r\n};\r\n\r\nsjcl.ecc._dh(\"ecdsa\");\r\n\r\nsjcl.ecc.ecdsa.secretKey.prototype = {\r\n sign: function(hash, paranoia, fakeLegacyVersion, fixedKForTesting) {\r\n if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {\r\n hash = sjcl.bitArray.clamp(hash, this._curveBitLength);\r\n }\r\n var R = this._curve.r,\r\n l = R.bitLength(),\r\n k = fixedKForTesting || sjcl.bn.random(R.sub(1), paranoia).add(1),\r\n r = this._curve.G.mult(k).x.mod(R),\r\n ss = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)),\r\n s = fakeLegacyVersion ? ss.inverseMod(R).mul(k).mod(R)\r\n : ss.mul(k.inverseMod(R)).mod(R);\r\n return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));\r\n }\r\n};\r\n\r\nsjcl.ecc.ecdsa.publicKey.prototype = {\r\n verify: function(hash, rs, fakeLegacyVersion) {\r\n if (sjcl.bitArray.bitLength(hash) > this._curveBitLength) {\r\n hash = sjcl.bitArray.clamp(hash, this._curveBitLength);\r\n }\r\n var w = sjcl.bitArray,\r\n R = this._curve.r,\r\n l = this._curveBitLength,\r\n r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),\r\n ss = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),\r\n s = fakeLegacyVersion ? ss : ss.inverseMod(R),\r\n hG = sjcl.bn.fromBits(hash).mul(s).mod(R),\r\n hA = r.mul(s).mod(R),\r\n r2 = this._curve.G.mult2(hG, hA, this._point).x;\r\n if (r.equals(0) || ss.equals(0) || r.greaterEquals(R) || ss.greaterEquals(R) || !r2.equals(r)) {\r\n if (fakeLegacyVersion === undefined) {\r\n return this.verify(hash, rs, true);\r\n } else {\r\n throw (new sjcl.exception.corrupt(\"signature didn't check out\"));\r\n }\r\n }\r\n return true;\r\n }\r\n};\r\n\r\n/** @fileOverview Javascript SRP implementation.\r\n *\r\n * This file contains a partial implementation of the SRP (Secure Remote\r\n * Password) password-authenticated key exchange protocol. Given a user\r\n * identity, salt, and SRP group, it generates the SRP verifier that may\r\n * be sent to a remote server to establish and SRP account.\r\n *\r\n * For more information, see http://srp.stanford.edu/.\r\n *\r\n * @author Quinn Slack\r\n */\r\n\r\n/**\r\n * Compute the SRP verifier from the username, password, salt, and group.\r\n * @class SRP\r\n */\r\nsjcl.keyexchange.srp = {\r\n /**\r\n * Calculates SRP v, the verifier. \r\n * v = g^x mod N [RFC 5054]\r\n * @param {String} I The username.\r\n * @param {String} P The password.\r\n * @param {Object} s A bitArray of the salt.\r\n * @param {Object} group The SRP group. Use sjcl.keyexchange.srp.knownGroup\r\n to obtain this object.\r\n * @return {Object} A bitArray of SRP v.\r\n */\r\n makeVerifier: function(I, P, s, group) {\r\n var x;\r\n x = sjcl.keyexchange.srp.makeX(I, P, s);\r\n x = sjcl.bn.fromBits(x);\r\n return group.g.powermod(x, group.N);\r\n },\r\n\r\n /**\r\n * Calculates SRP x.\r\n * x = SHA1(<salt> | SHA(<username> | \":\" | <raw password>)) [RFC 2945]\r\n * @param {String} I The username.\r\n * @param {String} P The password.\r\n * @param {Object} s A bitArray of the salt.\r\n * @return {Object} A bitArray of SRP x.\r\n */\r\n makeX: function(I, P, s) {\r\n var inner = sjcl.hash.sha1.hash(I + ':' + P);\r\n return sjcl.hash.sha1.hash(sjcl.bitArray.concat(s, inner));\r\n },\r\n\r\n /**\r\n * Returns the known SRP group with the given size (in bits).\r\n * @param {String} i The size of the known SRP group.\r\n * @return {Object} An object with \"N\" and \"g\" properties.\r\n */\r\n knownGroup:function(i) {\r\n if (typeof i !== \"string\") { i = i.toString(); }\r\n if (!sjcl.keyexchange.srp._didInitKnownGroups) { sjcl.keyexchange.srp._initKnownGroups(); }\r\n return sjcl.keyexchange.srp._knownGroups[i];\r\n },\r\n\r\n /**\r\n * Initializes bignum objects for known group parameters.\r\n * @private\r\n */\r\n _didInitKnownGroups: false,\r\n _initKnownGroups:function() {\r\n var i, size, group;\r\n for (i=0; i < sjcl.keyexchange.srp._knownGroupSizes.length; i++) {\r\n size = sjcl.keyexchange.srp._knownGroupSizes[i].toString();\r\n group = sjcl.keyexchange.srp._knownGroups[size];\r\n group.N = new sjcl.bn(group.N);\r\n group.g = new sjcl.bn(group.g);\r\n }\r\n sjcl.keyexchange.srp._didInitKnownGroups = true;\r\n },\r\n\r\n _knownGroupSizes: [1024, 1536, 2048],\r\n _knownGroups: {\r\n 1024: {\r\n N: \"EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C\" +\r\n \"9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE4\" +\r\n \"8E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B29\" +\r\n \"7BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9A\" +\r\n \"FD5138FE8376435B9FC61D2FC0EB06E3\",\r\n g:2\r\n },\r\n\r\n 1536: {\r\n N: \"9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA961\" +\r\n \"4B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F843\" +\r\n \"80B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0B\" +\r\n \"E3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF5\" +\r\n \"6EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734A\" +\r\n \"F7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E\" +\r\n \"8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB\",\r\n g: 2\r\n },\r\n\r\n 2048: {\r\n N: \"AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294\" +\r\n \"3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D\" +\r\n \"CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB\" +\r\n \"D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74\" +\r\n \"7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A\" +\r\n \"436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D\" +\r\n \"5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73\" +\r\n \"03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6\" +\r\n \"94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F\" +\r\n \"9E4AFF73\",\r\n g: 2\r\n }\r\n }\r\n\r\n};\r\n\r\n\r\n// ----- for secp256k1 ------\r\n\r\n// Overwrite NIST-P256 with secp256k1 so we're on even footing\r\nsjcl.ecc.curves.c256 = new sjcl.ecc.curve(\r\n sjcl.bn.pseudoMersennePrime(256, [[0,-1],[4,-1],[6,-1],[7,-1],[8,-1],[9,-1],[32,-1]]),\r\n \"0x14551231950b75fc4402da1722fc9baee\",\r\n 0,\r\n 7,\r\n \"0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\",\r\n \"0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\"\r\n);\r\n\r\n// Replace point addition and doubling algorithms\r\n// NIST-P256 is a=-3, we need algorithms for a=0\r\nsjcl.ecc.pointJac.prototype.add = function(T) {\r\n var S = this;\r\n if (S.curve !== T.curve) {\r\n throw(\"sjcl.ecc.add(): Points must be on the same curve to add them!\");\r\n }\r\n\r\n if (S.isIdentity) {\r\n return T.toJac();\r\n } else if (T.isIdentity) {\r\n return S;\r\n }\r\n\r\n var z1z1 = S.z.square();\r\n var h = T.x.mul(z1z1).subM(S.x);\r\n var s2 = T.y.mul(S.z).mul(z1z1);\r\n\r\n if (h.equals(0)) {\r\n if (S.y.equals(T.y.mul(z1z1.mul(S.z)))) {\r\n // same point\r\n return S.doubl();\r\n } else {\r\n // inverses\r\n return new sjcl.ecc.pointJac(S.curve);\r\n }\r\n }\r\n\r\n var hh = h.square();\r\n var i = hh.copy().doubleM().doubleM();\r\n var j = h.mul(i);\r\n var r = s2.sub(S.y).doubleM();\r\n var v = S.x.mul(i);\r\n \r\n var x = r.square().subM(j).subM(v.copy().doubleM());\r\n var y = r.mul(v.sub(x)).subM(S.y.mul(j).doubleM());\r\n var z = S.z.add(h).square().subM(z1z1).subM(hh);\r\n\r\n return new sjcl.ecc.pointJac(this.curve,x,y,z);\r\n};\r\n\r\nsjcl.ecc.pointJac.prototype.doubl = function () {\r\n if (this.isIdentity) { return this; }\r\n\r\n var a = this.x.square();\r\n var b = this.y.square();\r\n var c = b.square();\r\n var d = this.x.add(b).square().subM(a).subM(c).doubleM();\r\n var e = a.mul(3);\r\n var f = e.square();\r\n var x = f.sub(d.copy().doubleM());\r\n var y = e.mul(d.sub(x)).subM(c.doubleM().doubleM().doubleM());\r\n var z = this.y.mul(this.z).doubleM();\r\n return new sjcl.ecc.pointJac(this.curve, x, y, z);\r\n};\r\n\r\nsjcl.ecc.point.prototype.toBytesCompressed = function () {\r\n var header = this.y.mod(2).toString() == \"0x0\" ? 0x02 : 0x03;\r\n return [header].concat(sjcl.codec.bytes.fromBits(this.x.toBits()))\r\n};\r\n\r\n/** @fileOverview Javascript RIPEMD-160 implementation.\r\n *\r\n * @author Artem S Vybornov <vybornov@gmail.com>\r\n */\r\n(function() {\r\n\r\n/**\r\n * Context for a RIPEMD-160 operation in progress.\r\n * @constructor\r\n * @class RIPEMD, 160 bits.\r\n */\r\nsjcl.hash.ripemd160 = function (hash) {\r\n if (hash) {\r\n this._h = hash._h.slice(0);\r\n this._buffer = hash._buffer.slice(0);\r\n this._length = hash._length;\r\n } else {\r\n this.reset();\r\n }\r\n};\r\n\r\n/**\r\n * Hash a string or an array of words.\r\n * @static\r\n * @param {bitArray|String} data the data to hash.\r\n * @return {bitArray} The hash value, an array of 5 big-endian words.\r\n */\r\nsjcl.hash.ripemd160.hash = function (data) {\r\n return (new sjcl.hash.ripemd160()).update(data).finalize();\r\n};\r\n\r\nsjcl.hash.ripemd160.prototype = {\r\n /**\r\n * Reset the hash state.\r\n * @return this\r\n */\r\n reset: function () {\r\n this._h = _h0.slice(0);\r\n this._buffer = [];\r\n this._length = 0;\r\n return this;\r\n },\r\n\r\n /**\r\n * Reset the hash state.\r\n * @param {bitArray|String} data the data to hash.\r\n * @return this\r\n */\r\n update: function (data) {\r\n if ( typeof data === \"string\" )\r\n data = sjcl.codec.utf8String.toBits(data);\r\n\r\n var i, b = this._buffer = sjcl.bitArray.concat(this._buffer, data),\r\n ol = this._length,\r\n nl = this._length = ol + sjcl.bitArray.bitLength(data);\r\n for (i = 512+ol & -512; i <= nl; i+= 512) {\r\n var words = b.splice(0,16);\r\n for ( var w = 0; w < 16; ++w )\r\n words[w] = _cvt(words[w]);\r\n\r\n _block.call( this, words );\r\n }\r\n\r\n return this;\r\n },\r\n\r\n /**\r\n * Complete hashing and output the hash value.\r\n * @return {bitArray} The hash value, an array of 5 big-endian words.\r\n */\r\n finalize: function () {\r\n var b = sjcl.bitArray.concat( this._buffer, [ sjcl.bitArray.partial(1,1) ] ),\r\n l = ( this._length + 1 ) % 512,\r\n z = ( l > 448 ? 512 : 448 ) - l % 448,\r\n zp = z % 32;\r\n\r\n if ( zp > 0 )\r\n b = sjcl.bitArray.concat( b, [ sjcl.bitArray.partial(zp,0) ] )\r\n for ( ; z >= 32; z -= 32 )\r\n b.push(0);\r\n\r\n b.push( _cvt( this._length | 0 ) );\r\n b.push( _cvt( Math.floor(this._length / 0x100000000) ) );\r\n\r\n while ( b.length ) {\r\n var words = b.splice(0,16);\r\n for ( var w = 0; w < 16; ++w )\r\n words[w] = _cvt(words[w]);\r\n\r\n _block.call( this, words );\r\n }\r\n\r\n var h = this._h;\r\n this.reset();\r\n\r\n for ( var w = 0; w < 5; ++w )\r\n h[w] = _cvt(h[w]);\r\n\r\n return h;\r\n }\r\n};\r\n\r\nvar _h0 = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];\r\n\r\nvar _k1 = [ 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e ];\r\nvar _k2 = [ 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000 ];\r\nfor ( var i = 4; i >= 0; --i ) {\r\n for ( var j = 1; j < 16; ++j ) {\r\n _k1.splice(i,0,_k1[i]);\r\n _k2.splice(i,0,_k2[i]);\r\n }\r\n}\r\n\r\nvar _r1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\r\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\r\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\r\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\r\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ];\r\nvar _r2 = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\r\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\r\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\r\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\r\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ];\r\n\r\nvar _s1 = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\r\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\r\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\r\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\r\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];\r\nvar _s2 = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\r\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\r\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\r\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\r\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];\r\n\r\nfunction _f0(x,y,z) {\r\n return x ^ y ^ z;\r\n};\r\n\r\nfunction _f1(x,y,z) {\r\n return (x & y) | (~x & z);\r\n};\r\n\r\nfunction _f2(x,y,z) {\r\n return (x | ~y) ^ z;\r\n};\r\n\r\nfunction _f3(x,y,z) {\r\n return (x & z) | (y & ~z);\r\n};\r\n\r\nfunction _f4(x,y,z) {\r\n return x ^ (y | ~z);\r\n};\r\n\r\nfunction _rol(n,l) {\r\n return (n << l) | (n >>> (32-l));\r\n}\r\n\r\nfunction _cvt(n) {\r\n return ( (n & 0xff << 0) << 24 )\r\n | ( (n & 0xff << 8) << 8 )\r\n | ( (n & 0xff << 16) >>> 8 )\r\n | ( (n & 0xff << 24) >>> 24 );\r\n}\r\n\r\nfunction _block(X) {\r\n var A1 = this._h[0], B1 = this._h[1], C1 = this._h[2], D1 = this._h[3], E1 = this._h[4],\r\n A2 = this._h[0], B2 = this._h[1], C2 = this._h[2], D2 = this._h[3], E2 = this._h[4];\r\n\r\n var j = 0, T;\r\n\r\n for ( ; j < 16; ++j ) {\r\n T = _rol( A1 + _f0(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;\r\n A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;\r\n T = _rol( A2 + _f4(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;\r\n A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }\r\n for ( ; j < 32; ++j ) {\r\n T = _rol( A1 + _f1(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;\r\n A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;\r\n T = _rol( A2 + _f3(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;\r\n A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }\r\n for ( ; j < 48; ++j ) {\r\n T = _rol( A1 + _f2(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;\r\n A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;\r\n T = _rol( A2 + _f2(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;\r\n A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }\r\n for ( ; j < 64; ++j ) {\r\n T = _rol( A1 + _f3(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;\r\n A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;\r\n T = _rol( A2 + _f1(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;\r\n A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }\r\n for ( ; j < 80; ++j ) {\r\n T = _rol( A1 + _f4(B1,C1,D1) + X[_r1[j]] + _k1[j], _s1[j] ) + E1;\r\n A1 = E1; E1 = D1; D1 = _rol(C1,10); C1 = B1; B1 = T;\r\n T = _rol( A2 + _f0(B2,C2,D2) + X[_r2[j]] + _k2[j], _s2[j] ) + E2;\r\n A2 = E2; E2 = D2; D2 = _rol(C2,10); C2 = B2; B2 = T; }\r\n\r\n T = this._h[1] + C1 + D2;\r\n this._h[1] = this._h[2] + D1 + E2;\r\n this._h[2] = this._h[3] + E1 + A2;\r\n this._h[3] = this._h[4] + A1 + B2;\r\n this._h[4] = this._h[0] + B1 + C2;\r\n this._h[0] = T;\r\n}\r\n\r\n})();\r\n\r\nsjcl.bn.ZERO = new sjcl.bn(0);\r\n\r\n/** [ this / that , this % that ] */\r\nsjcl.bn.prototype.divRem = function (that) {\r\n if (typeof(that) !== \"object\") { that = new this._class(that); }\r\n var thisa = this.abs(), thata = that.abs(), quot = new this._class(0),\r\n ci = 0;\r\n if (!thisa.greaterEquals(thata)) {\r\n this.initWith(0);\r\n return this;\r\n } else if (thisa.equals(thata)) {\r\n this.initWith(1);\r\n return this;\r\n }\r\n\r\n for (; thisa.greaterEquals(thata); ci++) {\r\n thata.doubleM();\r\n }\r\n for (; ci > 0; ci--) {\r\n quot.doubleM();\r\n thata.halveM();\r\n if (thisa.greaterEquals(thata)) {\r\n quot.addM(1);\r\n thisa.subM(that).normalize();\r\n }\r\n }\r\n return [quot, thisa];\r\n};\r\n\r\n/** this /= that (rounded to nearest int) */\r\nsjcl.bn.prototype.divRound = function (that) {\r\n var dr = this.divRem(that), quot = dr[0], rem = dr[1];\r\n\r\n if (rem.doubleM().greaterEquals(that)) {\r\n quot.addM(1);\r\n }\r\n\r\n return quot;\r\n};\r\n\r\n/** this /= that (rounded down) */\r\nsjcl.bn.prototype.div = function (that) {\r\n var dr = this.divRem(that);\r\n return dr[0];\r\n};\r\n\r\nsjcl.bn.prototype.sign = function () {\r\n return this.greaterEquals(sjcl.bn.ZERO) ? 1 : -1;\r\n };\r\n\r\n/** -this */\r\nsjcl.bn.prototype.neg = function () {\r\n return sjcl.bn.ZERO.sub(this);\r\n};\r\n\r\n/** |this| */\r\nsjcl.bn.prototype.abs = function () {\r\n if (this.sign() === -1) {\r\n return this.neg();\r\n } else return this;\r\n};\r\n\r\nsjcl.ecc.ecdsa.secretKey.prototype = {\r\n sign: function(hash, paranoia) {\r\n var R = this._curve.r,\r\n l = R.bitLength(),\r\n k = sjcl.bn.random(R.sub(1), paranoia).add(1),\r\n r = this._curve.G.mult(k).x.mod(R),\r\n s = sjcl.bn.fromBits(hash).add(r.mul(this._exponent)).mul(k.inverseMod(R)).mod(R);\r\n\r\n return sjcl.bitArray.concat(r.toBits(l), s.toBits(l));\r\n }\r\n};\r\n\r\nsjcl.ecc.ecdsa.publicKey.prototype = {\r\n verify: function(hash, rs) {\r\n var w = sjcl.bitArray,\r\n R = this._curve.r,\r\n l = R.bitLength(),\r\n r = sjcl.bn.fromBits(w.bitSlice(rs,0,l)),\r\n s = sjcl.bn.fromBits(w.bitSlice(rs,l,2*l)),\r\n sInv = s.modInverse(R),\r\n hG = sjcl.bn.fromBits(hash).mul(sInv).mod(R),\r\n hA = r.mul(sInv).mod(R),\r\n r2 = this._curve.G.mult2(hG, hA, this._point).x;\r\n\r\n if (r.equals(0) || s.equals(0) || r.greaterEquals(R) || s.greaterEquals(R) || !r2.equals(r)) {\r\n throw (new sjcl.exception.corrupt(\"signature didn't check out\"));\r\n }\r\n return true;\r\n }\r\n};\r\n\r\nsjcl.ecc.ecdsa.secretKey.prototype.signDER = function(hash, paranoia) {\r\n return this.encodeDER(this.sign(hash, paranoia));\r\n};\r\n\r\nsjcl.ecc.ecdsa.secretKey.prototype.encodeDER = function(rs) {\r\n var w = sjcl.bitArray,\r\n R = this._curve.r,\r\n l = R.bitLength();\r\n\r\n var rb = sjcl.codec.bytes.fromBits(w.bitSlice(rs,0,l)),\r\n sb = sjcl.codec.bytes.fromBits(w.bitSlice(rs,l,2*l));\r\n\r\n // Drop empty leading bytes\r\n while (!rb[0] && rb.length) rb.shift();\r\n while (!sb[0] && sb.length) sb.shift();\r\n\r\n // If high bit is set, prepend an extra zero byte (DER signed integer)\r\n if (rb[0] & 0x80) rb.unshift(0);\r\n if (sb[0] & 0x80) sb.unshift(0);\r\n\r\n var buffer = [].concat(\r\n 0x30,\r\n 4 + rb.length + sb.length,\r\n 0x02,\r\n rb.length,\r\n rb,\r\n 0x02,\r\n sb.length,\r\n sb\r\n );\r\n\r\n return sjcl.codec.bytes.toBits(buffer);\r\n};\r\n\r\n\n/* WEBPACK VAR INJECTION */}(require, require(25)(module)))\n\n// WEBPACK FOOTER\n// module.id = 10\n// module.readableIdentifier = ./build/sjcl.js\n//@ sourceURL=webpack-module:///./build/sjcl.js");
/***/ },
/***/ 11:
/***/ function(module, exports, require) {
eval("var EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\nvar utils = require(9);\r\n\r\n/**\r\n * @constructor Server\r\n * @param remote The Remote object\r\n * @param opts Configuration parameters.\r\n *\r\n * Keys for cfg:\r\n * url\r\n */ \r\n\r\nfunction Server(remote, opts) {\r\n EventEmitter.call(this);\r\n\r\n if (typeof opts !== 'object') {\r\n throw new Error('Invalid server configuration.');\r\n }\r\n\r\n var self = this;\r\n\r\n this._remote = remote;\r\n this._opts = opts;\r\n this._host = opts.host;\r\n this._port = opts.port;\r\n this._secure = typeof opts.secure === 'boolean' ? opts.secure : true;\r\n this._ws = void(0);\r\n this._connected = false;\r\n this._should_connect = false;\r\n this._state = void(0);\r\n this._id = 0;\r\n this._retry = 0;\r\n this._requests = { };\r\n\r\n this._opts.url = (opts.secure ? 'wss://' : 'ws://') + opts.host + ':' + opts.port;\r\n\r\n this.on('message', function(message) {\r\n self._handle_message(message);\r\n });\r\n\r\n this.on('response_subscribe', function(message) {\r\n self._handle_response_subscribe(message);\r\n });\r\n}\r\n\r\nutil.inherits(Server, EventEmitter);\r\n\r\n/**\r\n * Server states that we will treat as the server being online.\r\n *\r\n * Our requirements are that the server can process transactions and notify\r\n * us of changes.\r\n */\r\nServer.online_states = [\r\n 'syncing'\r\n , 'tracking'\r\n , 'proposing'\r\n , 'validating'\r\n , 'full'\r\n];\r\n\r\nServer.prototype._is_online = function (status) {\r\n return Server.online_states.indexOf(status) !== -1;\r\n};\r\n\r\nServer.prototype._set_state = function (state) {\r\n if (state !== this._state) {\r\n this._state = state;\r\n\r\n this.emit('state', state);\r\n\r\n switch (state) {\r\n case 'online':\r\n this._connected = true;\r\n this.emit('connect');\r\n break;\r\n case 'offline':\r\n this._connected = false;\r\n this.emit('disconnect');\r\n break;\r\n }\r\n }\r\n};\r\n\r\nServer.prototype._trace = function() {\r\n if (this._remote.trace) {\r\n utils.logObject.apply(utils, arguments);\r\n }\r\n};\r\n\r\nServer.prototype._remote_address = function() {\r\n try { var address = this._ws._socket.remoteAddress; } catch (e) { }\r\n return address;\r\n};\r\n\r\n// This is the final interface between client code and a socket connection to a\r\n// `rippled` server. As such, this is a decent hook point to allow a WebSocket\r\n// interface conforming object to be used as a basis to mock rippled. This\r\n// avoids the need to bind a websocket server to a port and allows a more\r\n// synchronous style of code to represent a client <-> server message sequence.\r\n// We can also use this to log a message sequence to a buffer.\r\nServer.prototype.websocket_constructor = function () {\r\n return require(26);\r\n};\r\n\r\nServer.prototype.connect = function () {\r\n var self = this;\r\n\r\n // We don't connect if we believe we're already connected. This means we have\r\n // recently received a message from the server and the WebSocket has not\r\n // reported any issues either. If we do fail to ping or the connection drops,\r\n // we will automatically reconnect.\r\n if (this._connected) {\r\n return;\r\n }\r\n\r\n this._trace('server: connect: %s', this._opts.url);\r\n\r\n // Ensure any existing socket is given the command to close first.\r\n if (this._ws) {\r\n this._ws.close();\r\n }\r\n\r\n // We require this late, because websocket shims may be loaded after\r\n // ripple-lib.\r\n var WebSocket = this.websocket_constructor();\r\n var ws = this._ws = new WebSocket(this._opts.url);\r\n\r\n this._should_connect = true;\r\n\r\n self.emit('connecting');\r\n\r\n ws.onopen = function () {\r\n // If we are no longer the active socket, simply ignore any event\r\n if (ws === self._ws) {\r\n self.emit('socket_open');\r\n // Subscribe to events\r\n var request = self._remote._server_prepare_subscribe();\r\n self.request(request);\r\n }\r\n };\r\n\r\n ws.onerror = function (e) {\r\n // If we are no longer the active socket, simply ignore any event\r\n if (ws === self._ws) {\r\n self._trace('server: onerror: %s', e.data || e);\r\n\r\n // Most connection errors for WebSockets are conveyed as 'close' events with\r\n // code 1006. This is done for security purposes and therefore unlikely to\r\n // ever change.\r\n\r\n // This means that this handler is hardly ever called in practice. If it is,\r\n // it probably means the server's WebSocket implementation is corrupt, or\r\n // the connection is somehow producing corrupt data.\r\n\r\n // Most WebSocket applications simply log and ignore this error. Once we\r\n // support for multiple servers, we may consider doing something like\r\n // lowering this server's quality score.\r\n\r\n // However, in Node.js this event may be triggered instead of the close\r\n // event, so we need to handle it.\r\n handleConnectionClose();\r\n }\r\n };\r\n\r\n // Failure to open.\r\n ws.onclose = function () {\r\n // If we are no longer the active socket, simply ignore any event\r\n if (ws === self._ws) {\r\n self._trace('server: onclose: %s', ws.readyState);\r\n handleConnectionClose();\r\n }\r\n };\r\n\r\n function handleConnectionClose() {\r\n self.emit('socket_close');\r\n self._set_state('offline');\r\n\r\n // Prevent additional events from this socket\r\n ws.onopen = ws.onerror = ws.onclose = ws.onmessage = function () {};\r\n\r\n // Should we be connected?\r\n if (!self._should_connect) {\r\n return;\r\n }\r\n\r\n // Delay and retry.\r\n self._retry += 1;\r\n self._retry_timer = setTimeout(function () {\r\n self._trace('server: retry');\r\n if (!self._should_connect) {\r\n return;\r\n }\r\n self.connect();\r\n }, self._retry < 40\r\n ? 1000/20 // First, for 2 seconds: 20 times per second\r\n : self._retry < 40+60\r\n ? 1000 // Then, for 1 minute: once per second\r\n : self._retry < 40+60+60\r\n ? 10*1000 // Then, for 10 minutes: once every 10 seconds\r\n : 30*1000); // Then: once every 30 seconds\r\n }\r\n\r\n ws.onmessage = function (msg) {\r\n self.emit('message', msg.data);\r\n };\r\n};\r\n\r\nServer.prototype.disconnect = function () {\r\n this._should_connect = false;\r\n this._set_state('offline');\r\n if (this._ws) {\r\n this._ws.close();\r\n }\r\n};\r\n\r\nServer.prototype.send_message = function (message) {\r\n if (this._ws) {\r\n this._ws.send(JSON.stringify(message));\r\n }\r\n};\r\n\r\n/**\r\n * Submit a Request object to this server.\r\n */\r\nServer.prototype.request = function (request) {\r\n var self = this;\r\n\r\n // Only bother if we are still connected.\r\n if (this._ws) {\r\n request.server = this;\r\n request.message.id = this._id;\r\n\r\n this._requests[request.message.id] = request;\r\n\r\n // Advance message ID\r\n this._id++;\r\n\r\n var is_connected = this._connected || (request.message.command === 'subscribe' && this._ws.readyState === 1);\r\n \r\n if (is_connected) {\r\n this._trace('server: request: %s', request.message);\r\n this.send_message(request.message);\r\n } else {\r\n // XXX There are many ways to make this smarter.\r\n function server_reconnected() {\r\n self._trace('server: request: %s', request.message);\r\n self.send_message(request.message);\r\n }\r\n this.once('connect', server_reconnected);\r\n }\r\n } else {\r\n this._trace('server: request: DROPPING: %s', request.message);\r\n }\r\n};\r\n\r\nServer.prototype._handle_message = function (message) {\r\n var self = this;\r\n\r\n try { message = JSON.parse(message); } catch(e) { }\r\n\r\n var unexpected = typeof message !== 'object' || typeof message.type !== 'string';\r\n\r\n if (unexpected) {\r\n return; \r\n }\r\n\r\n switch (message.type) {\r\n case 'response':\r\n // A response to a request.\r\n var request = self._requests[message.id];\r\n delete self._requests[message.id];\r\n\r\n if (!request) {\r\n this._trace('server: UNEXPECTED: %s', message);\r\n } else if ('success' === message.status) {\r\n this._trace('server: response: %s', message);\r\n\r\n request.emit('success', message.result);\r\n\r\n [ self, self._remote ].forEach(function(emitter) {\r\n emitter.emit('response_' + request.message.command, message.result, request, message);\r\n });\r\n } else if (message.error) {\r\n this._trace('server: error: %s', message);\r\n\r\n request.emit('error', {\r\n error : 'remoteError',\r\n error_message : 'Remote reported an error.',\r\n remote : message\r\n });\r\n }\r\n break;\r\n\r\n case 'path_find':\r\n if (self._remote.trace) utils.logObject('server: path_find: %s', message);\r\n break;\r\n\r\n case 'serverStatus':\r\n // This message is only received when online. As we are connected, it is the definative final state.\r\n this._set_state(this._is_online(message.server_status) ? 'online' : 'offline');\r\n break;\r\n }\r\n}\r\n\r\nServer.prototype._handle_response_subscribe = function (message) {\r\n this._server_status = message.server_status;\r\n if (this._is_online(message.server_status)) {\r\n this._set_state('online');\r\n }\r\n}\r\n\r\nexports.Server = Server;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 11\n// module.readableIdentifier = ./src/js/ripple/server.js\n//@ sourceURL=webpack-module:///./src/js/ripple/server.js");
/***/ },
/***/ 12:
/***/ function(module, exports, require) {
eval("// This object serves as a singleton to store config options\r\n\r\nvar extend = require(29);\r\n\r\nvar config = module.exports = {\r\n load: function (newOpts) {\r\n extend(config, newOpts);\r\n return config;\r\n }\r\n};\r\n\n\n// WEBPACK FOOTER\n// module.id = 12\n// module.readableIdentifier = ./src/js/ripple/config.js\n//@ sourceURL=webpack-module:///./src/js/ripple/config.js");
/***/ },
/***/ 13:
/***/ function(module, exports, require) {
eval("Function.prototype.method = function(name,func) {\r\n this.prototype[name] = func;\r\n\r\n return this;\r\n};\r\n\r\nvar filterErr = function(code, done) {\r\n return function(e) {\r\n done(e.code !== code ? e : undefined);\r\n };\r\n};\r\n\r\nvar throwErr = function(done) {\r\n return function(e) {\r\n if (e)\r\n\tthrow e;\r\n \r\n done();\r\n };\r\n};\r\n \r\nvar trace = function(comment, func) {\r\n return function() {\r\n console.log(\"%s: %s\", trace, arguments.toString);\r\n func(arguments);\r\n };\r\n};\r\n\r\nvar arraySet = function (count, value) {\r\n var i, a = new Array(count);\r\n\r\n for (i = 0; i < count; i++) {\r\n a[i] = value;\r\n }\r\n\r\n return a;\r\n};\r\n\r\nvar hexToString = function (h) {\r\n var\ta = [];\r\n var\ti = 0;\r\n\r\n if (h.length % 2) {\r\n a.push(String.fromCharCode(parseInt(h.substring(0, 1), 16)));\r\n i = 1;\r\n }\r\n\r\n for (; i != h.length; i += 2) {\r\n a.push(String.fromCharCode(parseInt(h.substring(i, i+2), 16)));\r\n }\r\n \r\n return a.join(\"\");\r\n};\r\n\r\nvar stringToHex = function (s) {\r\n return Array.prototype.map.call(s, function (c) {\r\n var b = c.charCodeAt(0);\r\n\r\n return b < 16 ? \"0\" + b.toString(16) : b.toString(16);\r\n }).join(\"\");\r\n};\r\n\r\nvar stringToArray = function (s) {\r\n var a = new Array(s.length);\r\n var i;\r\n\r\n for (i = 0; i != a.length; i += 1)\r\n a[i] = s.charCodeAt(i);\r\n\r\n return a;\r\n};\r\n\r\nvar hexToArray = function (h) {\r\n return stringToArray(hexToString(h));\r\n}\r\n\r\nvar chunkString = function (str, n, leftAlign) {\r\n var ret = [];\r\n var i=0, len=str.length;\r\n if (leftAlign) {\r\n i = str.length % n;\r\n if (i) ret.push(str.slice(0, i));\r\n }\r\n for(; i < len; i += n) {\r\n ret.push(str.slice(i, n+i));\r\n }\r\n return ret;\r\n};\r\n\r\nvar logObject = function (msg, obj) {\r\n console.log(msg, JSON.stringify(obj, undefined, 2));\r\n};\r\n\r\nvar assert = function (assertion, msg) {\r\n if (!assertion) {\r\n throw new Error(\"Assertion failed\" + (msg ? \": \"+msg : \".\"));\r\n }\r\n};\r\n\r\n/**\r\n * Return unique values in array.\r\n */\r\nvar arrayUnique = function (arr) {\r\n var u = {}, a = [];\r\n for (var i = 0, l = arr.length; i < l; ++i){\r\n if (u.hasOwnProperty(arr[i])) {\r\n continue;\r\n }\r\n a.push(arr[i]);\r\n u[arr[i]] = 1;\r\n }\r\n return a;\r\n};\r\n\r\n/**\r\n * Convert a ripple epoch to a JavaScript timestamp.\r\n *\r\n * JavaScript timestamps are unix epoch in milliseconds.\r\n */\r\nvar toTimestamp = function (rpepoch) {\r\n return (rpepoch + 0x386D4380) * 1000;\r\n};\r\n\r\nexports.trace = trace;\r\nexports.arraySet = arraySet;\r\nexports.hexToString = hexToString;\r\nexports.hexToArray = hexToArray;\r\nexports.stringToArray = stringToArray;\r\nexports.stringToHex = stringToHex;\r\nexports.chunkString = chunkString;\r\nexports.logObject = logObject;\r\nexports.assert = assert;\r\nexports.arrayUnique = arrayUnique;\r\nexports.toTimestamp = toTimestamp;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 13\n// module.readableIdentifier = ./src/js/ripple/utils.js\n//@ sourceURL=webpack-module:///./src/js/ripple/utils.js");
/***/ },
/***/ 14:
/***/ function(module, exports, require) {
eval("var EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\nvar UInt160 = require(15).UInt160;\r\nvar Currency = require(3).Currency;\r\nvar Transaction = require(5).Transaction;\r\nvar Account = require(16).Account;\r\nvar Meta = require(6).Meta;\r\nvar OrderBook = require(17).OrderBook;\r\nvar RippleError = require(19).RippleError;\r\n\r\n// Request events emitted:\r\n// 'success' : Request successful.\r\n// 'error' : Request failed.\r\n// 'remoteError'\r\n// 'remoteUnexpected'\r\n// 'remoteDisconnected'\r\nfunction Request(remote, command) {\r\n EventEmitter.call(this);\r\n\r\n this.remote = remote;\r\n this.requested = false;\r\n this.message = {\r\n command : command,\r\n id : void(0)\r\n };\r\n};\r\n\r\nutil.inherits(Request, EventEmitter);\r\n\r\n// Send the request to a remote.\r\nRequest.prototype.request = function (remote) {\r\n if (!this.requested) {\r\n this.requested = true;\r\n this.on('error', new Function);\r\n this.remote.request(this);\r\n this.emit('request', remote);\r\n }\r\n};\r\n\r\nRequest.prototype.callback = function(callback, successEvent, errorEvent) {\r\n if (callback && typeof callback === 'function') {\r\n var self = this;\r\n\r\n function request_success(message) {\r\n callback.call(self, null, message);\r\n }\r\n\r\n function request_error(error) {\r\n if (!(error instanceof RippleError)) {\r\n error = new RippleError(error);\r\n }\r\n callback.call(self, error);\r\n }\r\n\r\n this.once(successEvent || 'success', request_success);\r\n this.once(errorEvent || 'error' , request_error);\r\n this.request();\r\n }\r\n\r\n return this;\r\n};\r\n\r\nRequest.prototype.timeout = function(duration, callback) {\r\n var self = this;\r\n\r\n if (!this.requested) {\r\n function requested() {\r\n self.timeout(duration, callback);\r\n }\r\n this.once('request', requested);\r\n return;\r\n }\r\n\r\n var emit = this.emit;\r\n var timed_out = false;\r\n\r\n var timeout = setTimeout(function() {\r\n timed_out = true;\r\n if (typeof callback === 'function') callback();\r\n emit.call(self, 'timeout');\r\n }, duration);\r\n\r\n this.emit = function() {\r\n if (!timed_out) {\r\n clearTimeout(timeout);\r\n emit.apply(self, arguments);\r\n }\r\n };\r\n\r\n return this;\r\n};\r\n\r\nRequest.prototype.set_server = function(server) {\r\n var selected = null;\r\n\r\n switch (typeof server) {\r\n case 'object':\r\n selected = server;\r\n break;\r\n case 'string':\r\n for (var i=0, s; s=this.remote._servers[i]; i++) {\r\n if (s._host === server) {\r\n selected = s;\r\n break;\r\n }\r\n }\r\n break;\r\n };\r\n\r\n this.server = selected;\r\n};\r\n\r\nRequest.prototype.build_path = function (build) {\r\n if (build) {\r\n this.message.build_path = true;\r\n }\r\n return this;\r\n};\r\n\r\nRequest.prototype.ledger_choose = function (current) {\r\n if (current) {\r\n this.message.ledger_index = this.remote._ledger_current_index;\r\n } else {\r\n this.message.ledger_hash = this.remote._ledger_hash;\r\n }\r\n return this;\r\n};\r\n\r\n// Set the ledger for a request.\r\n// - ledger_entry\r\n// - transaction_entry\r\nRequest.prototype.ledger_hash = function (hash) {\r\n this.message.ledger_hash = hash;\r\n return this;\r\n};\r\n\r\n// Set the ledger_index for a request.\r\n// - ledger_entry\r\nRequest.prototype.ledger_index = function (ledger_index) {\r\n this.message.ledger_index = ledger_index;\r\n return this;\r\n};\r\n\r\nRequest.prototype.ledger_select = function (ledger_spec) {\r\n switch (ledger_spec) {\r\n case 'current':\r\n case 'closed':\r\n case 'verified':\r\n this.message.ledger_index = ledger_spec;\r\n break;\r\n\r\n default:\r\n // XXX Better test needed\r\n if (Number(ledger_spec)) {\r\n this.message.ledger_index = ledger_spec;\r\n } else {\r\n this.message.ledger_hash = ledger_spec;\r\n }\r\n break;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nRequest.prototype.account_root = function (account) {\r\n this.message.account_root = UInt160.json_rewrite(account);\r\n return this;\r\n};\r\n\r\nRequest.prototype.index = function (hash) {\r\n this.message.index = hash;\r\n return this;\r\n};\r\n\r\n// Provide the information id an offer.\r\n// --> account\r\n// --> seq : sequence number of transaction creating offer (integer)\r\nRequest.prototype.offer_id = function (account, seq) {\r\n this.message.offer = {\r\n account: UInt160.json_rewrite(account),\r\n seq: seq\r\n };\r\n return this;\r\n};\r\n\r\n// --> index : ledger entry index.\r\nRequest.prototype.offer_index = function (index) {\r\n this.message.offer = index;\r\n return this;\r\n};\r\n\r\nRequest.prototype.secret = function (secret) {\r\n if (secret) {\r\n this.message.secret = secret;\r\n }\r\n return this;\r\n};\r\n\r\nRequest.prototype.tx_hash = function (hash) {\r\n this.message.tx_hash = hash;\r\n return this;\r\n};\r\n\r\nRequest.prototype.tx_json = function (json) {\r\n this.message.tx_json = json;\r\n return this;\r\n};\r\n\r\nRequest.prototype.tx_blob = function (json) {\r\n this.message.tx_blob = json;\r\n return this;\r\n};\r\n\r\nRequest.prototype.ripple_state = function (account, issuer, currency) {\r\n this.message.ripple_state = {\r\n currency : currency,\r\n accounts : [\r\n UInt160.json_rewrite(account),\r\n UInt160.json_rewrite(issuer)\r\n ]\r\n };\r\n return this;\r\n};\r\n\r\nRequest.prototype.accounts = function (accounts, realtime) {\r\n if (!Array.isArray(accounts)) {\r\n accounts = [ accounts ];\r\n }\r\n\r\n // Process accounts parameters\r\n var processedAccounts = accounts.map(function(account) {\r\n return UInt160.json_rewrite(account);\r\n });\r\n\r\n if (realtime) {\r\n this.message.rt_accounts = processedAccounts;\r\n } else {\r\n this.message.accounts = processedAccounts;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nRequest.prototype.rt_accounts = function (accounts) {\r\n return this.accounts(accounts, true);\r\n};\r\n\r\nRequest.prototype.books = function (books, snapshot) {\r\n var processedBooks = [ ];\r\n\r\n for (var i = 0, l = books.length; i < l; i++) {\r\n var book = books[i];\r\n var json = { };\r\n\r\n function processSide(side) {\r\n if (!book[side]) {\r\n throw new Error('Missing ' + side);\r\n }\r\n\r\n var obj = json[side] = {\r\n currency: Currency.json_rewrite(book[side].currency)\r\n };\r\n if (obj.currency !== 'XRP') {\r\n obj.issuer = UInt160.json_rewrite(book[side].issuer);\r\n }\r\n }\r\n\r\n processSide('taker_gets');\r\n processSide('taker_pays');\r\n\r\n if (snapshot) {\r\n json.snapshot = true;\r\n }\r\n\r\n if (book.both) {\r\n json.both = true;\r\n }\r\n\r\n processedBooks.push(json);\r\n }\r\n\r\n this.message.books = processedBooks;\r\n\r\n return this;\r\n};\r\n\r\nexports.Request = Request;\r\n\n\n// WEBPACK FOOTER\n// module.id = 14\n// module.readableIdentifier = ./src/js/ripple/request.js\n//@ sourceURL=webpack-module:///./src/js/ripple/request.js");
/***/ },
/***/ 15:
/***/ function(module, exports, require) {
eval("var sjcl = require(10);\r\nvar utils = require(9);\r\nvar config = require(12);\r\nvar jsbn = require(20);\r\nvar extend = require(29);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\nvar nbi = jsbn.nbi;\r\n\r\nvar UInt = require(30).UInt;\r\nvar Base = require(4).Base;\r\n\r\n//\r\n// UInt160 support\r\n//\r\n\r\nvar UInt160 = extend(function () {\r\n // Internal form: NaN or BigInteger\r\n this._value = NaN;\r\n}, UInt);\r\n\r\nUInt160.width = 20;\r\nUInt160.prototype = extend({}, UInt.prototype);\r\nUInt160.prototype.constructor = UInt160;\r\n\r\nvar ACCOUNT_ZERO = UInt160.ACCOUNT_ZERO = 'rrrrrrrrrrrrrrrrrrrrrhoLvTp';\r\nvar ACCOUNT_ONE = UInt160.ACCOUNT_ONE = 'rrrrrrrrrrrrrrrrrrrrBZbvji';\r\nvar HEX_ZERO = UInt160.HEX_ZERO = '0000000000000000000000000000000000000000';\r\nvar HEX_ONE = UInt160.HEX_ONE = '0000000000000000000000000000000000000001';\r\nvar STR_ZERO = UInt160.STR_ZERO = utils.hexToString(HEX_ZERO);\r\nvar STR_ONE = UInt160.STR_ONE = utils.hexToString(HEX_ONE);\r\n\r\n// value = NaN on error.\r\nUInt160.prototype.parse_json = function (j) {\r\n // Canonicalize and validate\r\n if (config.accounts && j in config.accounts) {\r\n j = config.accounts[j].account;\r\n }\r\n\r\n if (typeof j === 'number' && !isNaN(j)) {\r\n this._value = new BigInteger(String(j));\r\n } else if (typeof j !== 'string') {\r\n this._value = NaN;\r\n } else if (j[0] === 'r') {\r\n this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);\r\n } else {\r\n this._value = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\n// XXX Json form should allow 0 and 1, C++ doesn't currently allow it.\r\nUInt160.prototype.to_json = function (opts) {\r\n var opts = opts || {};\r\n var output = NaN;\r\n\r\n if (this._value instanceof BigInteger) {\r\n output = Base.encode_check(Base.VER_ACCOUNT_ID, this.to_bytes());\r\n if (opts.gateways && output in opts.gateways) {\r\n output = opts.gateways[output];\r\n }\r\n }\r\n \r\n return output;\r\n};\r\n\r\nexports.UInt160 = UInt160;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 15\n// module.readableIdentifier = ./src/js/ripple/uint160.js\n//@ sourceURL=webpack-module:///./src/js/ripple/uint160.js");
/***/ },
/***/ 16:
/***/ function(module, exports, require) {
eval("// Routines for working with an account.\r\n//\r\n// You should not instantiate this class yourself, instead use Remote#account.\r\n//\r\n// Events:\r\n// wallet_clean\t: True, iff the wallet has been updated.\r\n// wallet_dirty\t: True, iff the wallet needs to be updated.\r\n// balance\t\t: The current stamp balance.\r\n// balance_proposed\r\n//\r\n\r\n// var network = require(\"./network.js\");\r\n\r\nvar EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\nvar extend = require(29);\r\n\r\nvar Amount = require(2).Amount;\r\nvar UInt160 = require(15).UInt160;\r\nvar TransactionManager = require(31).TransactionManager;\r\n\r\n\r\nfunction Account(remote, account) {\r\n EventEmitter.call(this);\r\n\r\n var self = this;\r\n\r\n this._remote = remote;\r\n this._account = UInt160.from_json(account);\r\n this._account_id = this._account.to_json();\r\n this._subs = 0;\r\n\r\n // Ledger entry object\r\n // Important: This must never be overwritten, only extend()-ed\r\n this._entry = { };\r\n\r\n function listener_added(type, listener) {\r\n if (~Account.subscribe_events.indexOf(type)) {\r\n if (!self._subs && self._remote._connected) {\r\n self._remote.request_subscribe()\r\n .accounts(self._account_id)\r\n .request();\r\n }\r\n self._subs += 1;\r\n }\r\n }\r\n\r\n function listener_removed(type, listener) {\r\n if (~Account.subscribe_events.indexOf(type)) {\r\n self._subs -= 1;\r\n if (!self._subs && self._remote._connected) {\r\n self._remote.request_unsubscribe()\r\n .accounts(self._account_id)\r\n .request();\r\n }\r\n }\r\n }\r\n\r\n this.on('newListener', listener_added);\r\n this.on('removeListener', listener_removed);\r\n\r\n function prepare_subscribe(request) {\r\n if (self._account.is_valid() && self._subs) {\r\n request.accounts(self._account_id);\r\n }\r\n }\r\n\r\n this._remote.on('prepare_subscribe', prepare_subscribe);\r\n\r\n function handle_transaction(transaction) {\r\n var changed = false;\r\n\r\n transaction.mmeta.each(function(an) {\r\n var isAccountRoot = an.entryType === 'AccountRoot' \r\n && an.fields.Account === self._account_id;\r\n if (isAccountRoot) {\r\n extend(self._entry, an.fieldsNew, an.fieldsFinal);\r\n changed = true;\r\n }\r\n });\r\n\r\n if (changed) {\r\n self.emit('entry', self._entry);\r\n }\r\n }\r\n\r\n this.on('transaction', handle_transaction);\r\n\r\n return this;\r\n};\r\n\r\nutil.inherits(Account, EventEmitter);\r\n\r\n/**\r\n * List of events that require a remote subscription to the account.\r\n */\r\nAccount.subscribe_events = [ 'transaction', 'entry' ];\r\n\r\nAccount.prototype.to_json = function () {\r\n return this._account.to_json();\r\n};\r\n\r\n/**\r\n * Whether the AccountId is valid.\r\n *\r\n * Note: This does not tell you whether the account exists in the ledger.\r\n */\r\nAccount.prototype.is_valid = function () {\r\n return this._account.is_valid();\r\n};\r\n\r\nAccount.prototype.get_info = function(callback) {\r\n var callback = typeof callback === 'function' ? callback : function(){};\r\n var request = this._remote.request_account_info(this._account_id, callback);\r\n return request;\r\n};\r\n\r\n/**\r\n * Retrieve the current AccountRoot entry.\r\n *\r\n * To keep up-to-date with changes to the AccountRoot entry, subscribe to the\r\n * \"entry\" event.\r\n *\r\n * @param {function (err, entry)} callback Called with the result\r\n */\r\nAccount.prototype.entry = function (callback) {\r\n var self = this;\r\n var callback = typeof callback === 'function' ? callback : function(){};\r\n\r\n this.get_info(function account_info(err, info) {\r\n if (err) {\r\n callback(err);\r\n } else {\r\n extend(self._entry, info.account_data);\r\n self.emit('entry', self._entry);\r\n callback(null, info);\r\n }\r\n });\r\n\r\n return this;\r\n};\r\n\r\nAccount.prototype.get_next_sequence = function(callback) {\r\n var callback = typeof callback === 'function' ? callback : function(){};\r\n\r\n this.get_info(function account_info(err, info) {\r\n if (err) {\r\n callback(err);\r\n } else {\r\n callback(null, info.account_data.Sequence); \r\n }\r\n });\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Retrieve this account's Ripple trust lines.\r\n *\r\n * To keep up-to-date with changes to the AccountRoot entry, subscribe to the\r\n * \"lines\" event. (Not yet implemented.)\r\n *\r\n * @param {function (err, lines)} callback Called with the result\r\n */\r\nAccount.prototype.lines = function (callback) {\r\n var self = this;\r\n var callback = typeof callback === 'function' ? callback : function(){};\r\n\r\n function account_lines(err, res) {\r\n if (err) {\r\n callback(err);\r\n } else {\r\n self._lines = res.lines;\r\n self.emit('lines', self._lines);\r\n callback(null, res);\r\n }\r\n }\r\n\r\n this._remote.request_account_lines(this._account_id, account_lines);\r\n\r\n return this;\r\n};\r\n\r\n/**\r\n * Notify object of a relevant transaction.\r\n *\r\n * This is only meant to be called by the Remote class. You should never have to\r\n * call this yourself.\r\n */\r\nAccount.prototype.notify = \r\nAccount.prototype.notifyTx = function (message) {\r\n // Only trigger the event if the account object is actually\r\n // subscribed - this prevents some weird phantom events from\r\n // occurring.\r\n if (this._subs) {\r\n this.emit('transaction', message);\r\n var account = message.transaction.Account;\r\n if (!account) return;\r\n if (account === this._account_id) {\r\n this.emit('transaction-outbound', message);\r\n } else {\r\n this.emit('transaction-inbound', message);\r\n }\r\n }\r\n};\r\n\r\nAccount.prototype.submit = function(tx) {\r\n if (!this._tx_manager) {\r\n this._tx_manager = new TransactionManager(this);\r\n }\r\n this._tx_manager.submit(tx);\r\n};\r\n\r\nexports.Account = Account;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 16\n// module.readableIdentifier = ./src/js/ripple/account.js\n//@ sourceURL=webpack-module:///./src/js/ripple/account.js");
/***/ },
/***/ 17:
/***/ function(module, exports, require) {
eval("// Routines for working with an orderbook.\r\n//\r\n// One OrderBook object represents one half of an order book. (i.e. bids OR\r\n// asks) Which one depends on the ordering of the parameters.\r\n//\r\n// Events:\r\n// - transaction A transaction that affects the order book.\r\n\r\n// var network = require(\"./network.js\");\r\n\r\nvar EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\n\r\nvar Amount = require(2).Amount;\r\nvar UInt160 = require(15).UInt160;\r\nvar Currency = require(3).Currency;\r\n\r\nvar extend = require(29);\r\n\r\nfunction OrderBook(remote, currency_gets, issuer_gets, currency_pays, issuer_pays) {\r\n EventEmitter.call(this);\r\n\r\n var self = this;\r\n\r\n this._remote = remote;\r\n this._currency_gets = currency_gets;\r\n this._issuer_gets = issuer_gets;\r\n this._currency_pays = currency_pays;\r\n this._issuer_pays = issuer_pays;\r\n this._subs = 0;\r\n\r\n // We consider ourselves synchronized if we have a current copy of the offers,\r\n // we are online and subscribed to updates.\r\n this._sync = false;\r\n\r\n // Offers\r\n this._offers = [ ];\r\n\r\n this.on('newListener', function (type, listener) {\r\n if (OrderBook.subscribe_events.indexOf(type) !== -1) {\r\n if (!self._subs && self._remote._connected) {\r\n self._subscribe();\r\n }\r\n self._subs += 1;\r\n }\r\n });\r\n\r\n this.on('removeListener', function (type, listener) {\r\n if (~OrderBook.subscribe_events.indexOf(type)) {\r\n self._subs -= 1;\r\n if (!self._subs && self._remote._connected) {\r\n self._sync = false;\r\n self._remote.request_unsubscribe()\r\n .books([self.to_json()])\r\n .request();\r\n }\r\n }\r\n });\r\n\r\n this._remote.on('connect', function () {\r\n if (self._subs) {\r\n self._subscribe();\r\n }\r\n });\r\n\r\n this._remote.on('disconnect', function () {\r\n self._sync = false;\r\n });\r\n\r\n return this;\r\n};\r\n\r\nutil.inherits(OrderBook, EventEmitter);\r\n\r\n/**\r\n * List of events that require a remote subscription to the orderbook.\r\n */\r\nOrderBook.subscribe_events = ['transaction', 'model', 'trade'];\r\n\r\n/**\r\n * Subscribes to orderbook.\r\n *\r\n * @private\r\n */\r\nOrderBook.prototype._subscribe = function () {\r\n var self = this;\r\n var request = self._remote.request_subscribe()\r\n request.books([ self.to_json() ], true)\r\n request.callback(function(err, res) {\r\n if (err) {\r\n // XXX What now?\r\n } else {\r\n self._sync = true;\r\n self._offers = res.offers;\r\n self.emit('model', self._offers);\r\n }\r\n });\r\n};\r\n\r\nOrderBook.prototype.to_json = function () {\r\n var json = {\r\n taker_gets: {\r\n currency: this._currency_gets\r\n },\r\n taker_pays: {\r\n currency: this._currency_pays\r\n }\r\n };\r\n\r\n if (this._currency_gets !== 'XRP') {\r\n json['taker_gets']['issuer'] = this._issuer_gets;\r\n }\r\n\r\n if (this._currency_pays !== 'XRP') {\r\n json['taker_pays']['issuer'] = this._issuer_pays;\r\n }\r\n\r\n return json;\r\n};\r\n\r\n/**\r\n * Whether the OrderBook is valid.\r\n *\r\n * Note: This only checks whether the parameters (currencies and issuer) are\r\n * syntactically valid. It does not check anything against the ledger.\r\n */\r\nOrderBook.prototype.is_valid = function () {\r\n // XXX Should check for same currency (non-native) && same issuer\r\n return (\r\n Currency.is_valid(this._currency_pays) &&\r\n (this._currency_pays === 'XRP' || UInt160.is_valid(this._issuer_pays)) &&\r\n Currency.is_valid(this._currency_gets) &&\r\n (this._currency_gets === 'XRP' || UInt160.is_valid(this._issuer_gets)) &&\r\n !(this._currency_pays === 'XRP' && this._currency_gets === 'XRP')\r\n );\r\n};\r\n\r\nOrderBook.prototype.trade = function(type) {\r\n var tradeStr = '0'\r\n + (this['_currency_' + type] === 'XRP') ? '' : '/' \r\n + this['_currency_' + type ] + '/' \r\n + this['_issuer_' + type];\r\n return Amount.from_json(tradeStr);\r\n};\r\n\r\n/**\r\n * Notify object of a relevant transaction.\r\n *\r\n * This is only meant to be called by the Remote class. You should never have to\r\n * call this yourself.\r\n */\r\nOrderBook.prototype.notify =\r\nOrderBook.prototype.notifyTx = function (message) {\r\n var self = this;\r\n var changed = false;\r\n var trade_gets = this.trade('gets');\r\n var trade_pays = this.trade('pays');\r\n\r\n message.mmeta.each(function (an) {\r\n if (an.entryType !== 'Offer') return;\r\n\r\n var i, l, offer;\r\n\r\n switch(an.diffType) {\r\n case 'DeletedNode':\r\n case 'ModifiedNode':\r\n var deletedNode = an.diffType === 'DeletedNode';\r\n\r\n for (i = 0, l = self._offers.length; i < l; i++) {\r\n offer = self._offers[i];\r\n if (offer.index === an.ledgerIndex) {\r\n if (deletedNode) {\r\n self._offers.splice(i, 1);\r\n } else {\r\n extend(offer, an.fieldsFinal);\r\n }\r\n changed = true;\r\n break;\r\n }\r\n }\r\n\r\n // We don't want to count a OfferCancel as a trade\r\n if (message.transaction.TransactionType === 'OfferCancel') return;\r\n\r\n trade_gets = trade_gets.add(an.fieldsPrev.TakerGets);\r\n trade_pays = trade_pays.add(an.fieldsPrev.TakerPays);\r\n\r\n if (!deletedNode) {\r\n trade_gets = trade_gets.subtract(an.fieldsFinal.TakerGets);\r\n trade_pays = trade_pays.subtract(an.fieldsFinal.TakerPays);\r\n }\r\n break;\r\n\r\n case 'CreatedNode':\r\n var price = Amount.from_json(an.fields.TakerPays).ratio_human(an.fields.TakerGets);\r\n\r\n for (i = 0, l = self._offers.length; i < l; i++) {\r\n offer = self._offers[i];\r\n var priceItem = Amount.from_json(offer.TakerPays).ratio_human(offer.TakerGets);\r\n\r\n if (price.compareTo(priceItem) <= 0) {\r\n var obj = an.fields;\r\n obj.index = an.ledgerIndex;\r\n self._offers.splice(i, 0, an.fields);\r\n changed = true;\r\n break;\r\n }\r\n }\r\n break;\r\n }\r\n });\r\n\r\n // Only trigger the event if the account object is actually\r\n // subscribed - this prevents some weird phantom events from\r\n // occurring.\r\n if (this._subs) {\r\n this.emit('transaction', message);\r\n if (changed) this.emit('model', this._offers);\r\n if (!trade_gets.is_zero()) this.emit('trade', trade_pays, trade_gets);\r\n }\r\n};\r\n\r\n/**\r\n * Get offers model asynchronously.\r\n *\r\n * This function takes a callback and calls it with an array containing the\r\n * current set of offers in this order book.\r\n *\r\n * If the data is available immediately, the callback may be called synchronously.\r\n */\r\nOrderBook.prototype.offers = function (callback) {\r\n var self = this;\r\n if (typeof callback === 'function') {\r\n if (this._sync) {\r\n callback(this._offers);\r\n } else {\r\n this.once('model', callback);\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Return latest known offers.\r\n *\r\n * Usually, this will just be an empty array if the order book hasn't been\r\n * loaded yet. But this accessor may be convenient in some circumstances.\r\n */\r\nOrderBook.prototype.offersSync = function () {\r\n return this._offers;\r\n};\r\n\r\nexports.OrderBook = OrderBook;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 17\n// module.readableIdentifier = ./src/js/ripple/orderbook.js\n//@ sourceURL=webpack-module:///./src/js/ripple/orderbook.js");
/***/ },
/***/ 18:
/***/ function(module, exports, require) {
eval("var EventEmitter = require(27).EventEmitter;\r\nvar util = require(28);\r\n\r\nvar Amount = require(2).Amount;\r\n\r\nvar extend = require(29);\r\n\r\n/**\r\n * Represents a persistent path finding request.\r\n *\r\n * Only one path find request is allowed per connection, so when another path\r\n * find request is triggered it will supercede the existing one, making it emit\r\n * the 'end' and 'superceded' events.\r\n */\r\nvar PathFind = function (remote, src_account, dst_account,\r\n dst_amount, src_currencies)\r\n{\r\n EventEmitter.call(this);\r\n\r\n this.remote = remote;\r\n\r\n this.src_account = src_account;\r\n this.dst_account = dst_account;\r\n this.dst_amount = dst_amount;\r\n this.src_currencies = src_currencies;\r\n};\r\n\r\nutil.inherits(PathFind, EventEmitter);\r\n\r\n/**\r\n * Submits a path_find_create request to the network.\r\n *\r\n * This starts a path find request, superceding all previous path finds.\r\n *\r\n * This will be called automatically by Remote when this object is instantiated,\r\n * so you should only have to call it if the path find was closed or superceded\r\n * and you wish to restart it.\r\n */\r\nPathFind.prototype.create = function ()\r\n{\r\n var self = this;\r\n\r\n var req = this.remote.request_path_find_create(this.src_account,\r\n this.dst_account,\r\n this.dst_amount,\r\n this.src_currencies,\r\n handleInitialPath);\r\n\r\n function handleInitialPath(err, msg) {\r\n if (err) {\r\n self.emit('error', err);\r\n return;\r\n }\r\n self.notify_update(msg);\r\n }\r\n\r\n // XXX We should add ourselves to prepare_subscribe or a similar mechanism so\r\n // that we can resubscribe after a reconnection.\r\n\r\n req.request();\r\n};\r\n\r\nPathFind.prototype.close = function ()\r\n{\r\n this.remote.request_path_find_close().request();\r\n this.emit('end');\r\n this.emit('close');\r\n};\r\n\r\nPathFind.prototype.notify_update = function (message)\r\n{\r\n var src_account = message.source_account;\r\n var dst_account = message.destination_account;\r\n var dst_amount = Amount.from_json(message.destination_amount);\r\n\r\n // Only pass the event along if this path find response matches what we were\r\n // looking for.\r\n if (this.src_account === src_account &&\r\n this.dst_account === dst_account &&\r\n this.dst_amount.equals(dst_amount)) {\r\n this.emit('update', message);\r\n }\r\n};\r\n\r\nPathFind.prototype.notify_superceded = function ()\r\n{\r\n // XXX If we're set to re-subscribe whenever we connect to a new server, then\r\n // we should cancel that behavior here. See PathFind#create.\r\n\r\n this.emit('end');\r\n this.emit('superceded');\r\n};\r\n\r\nexports.PathFind = PathFind;\r\n\n\n// WEBPACK FOOTER\n// module.id = 18\n// module.readableIdentifier = ./src/js/ripple/pathfind.js\n//@ sourceURL=webpack-module:///./src/js/ripple/pathfind.js");
/***/ },
/***/ 19:
/***/ function(module, exports, require) {
eval("var util = require(28);\r\nvar extend = require(29);\r\n\r\nfunction RippleError(code, message) {\r\n switch (typeof code) {\r\n case 'object':\r\n extend(this, code);\r\n break;\r\n case 'string':\r\n this.result = code;\r\n this.result_message = message;\r\n break;\r\n }\r\n\r\n this.result = this.result || this.error || 'Error';\r\n this.result_message = this.result_message || this.error_message || 'Error';\r\n this.message = this.result_message;\r\n\r\n Error.captureStackTrace(this, code || this);\r\n}\r\n\r\nutil.inherits(RippleError, Error);\r\n\r\nRippleError.prototype.name = 'RippleError';\r\n\r\nexports.RippleError = RippleError;\r\n\n\n// WEBPACK FOOTER\n// module.id = 19\n// module.readableIdentifier = ./src/js/ripple/rippleerror.js\n//@ sourceURL=webpack-module:///./src/js/ripple/rippleerror.js");
/***/ },
/***/ 20:
/***/ function(module, exports, require) {
eval("// Derived from Tom Wu's jsbn code.\r\n//\r\n// Changes made for clean up and to package as a node.js module.\r\n\r\n// Copyright (c) 2005-2009 Tom Wu\r\n// All Rights Reserved.\r\n// See \"LICENSE\" for details.\r\n\r\n// Basic JavaScript BN library - subset useful for RSA encryption.\r\n// Extended JavaScript BN functions, required for RSA private ops.\r\n// Version 1.1: new BigInteger(\"0\", 10) returns \"proper\" zero\r\n// Version 1.2: square() API, isProbablePrime fix\r\n\r\n// Bits per digit\r\nvar dbits;\r\n\r\n// JavaScript engine analysis\r\nvar canary = 0xdeadbeefcafe;\r\nvar j_lm = ((canary&0xffffff)==0xefcafe);\r\n\r\n// (public) Constructor\r\nvar BigInteger = function BigInteger(a,b,c) {\r\n if(a != null)\r\n if(\"number\" == typeof a) this.fromNumber(a,b,c);\r\n else if(b == null && \"string\" != typeof a) this.fromString(a,256);\r\n else this.fromString(a,b);\r\n};\r\n\r\n// return new, unset BigInteger\r\nvar nbi\t= function nbi() { return new BigInteger(null); };\r\n\r\n// am: Compute w_j += (x*this_i), propagate carries,\r\n// c is initial carry, returns final carry.\r\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\r\n// We need to select the fastest one that works in this environment.\r\n\r\n// am1: use a single mult and divide to get the high bits,\r\n// max digit bits should be 26 because\r\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\r\nfunction am1(i,x,w,j,c,n) {\r\n while(--n >= 0) {\r\n var v = x*this[i++]+w[j]+c;\r\n c = Math.floor(v/0x4000000);\r\n w[j++] = v&0x3ffffff;\r\n }\r\n return c;\r\n}\r\n// am2 avoids a big mult-and-extract completely.\r\n// Max digit bits should be <= 30 because we do bitwise ops\r\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\r\nfunction am2(i,x,w,j,c,n) {\r\n var xl = x&0x7fff, xh = x>>15;\r\n while(--n >= 0) {\r\n var l = this[i]&0x7fff;\r\n var h = this[i++]>>15;\r\n var m = xh*l+h*xl;\r\n l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);\r\n c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);\r\n w[j++] = l&0x3fffffff;\r\n }\r\n return c;\r\n}\r\n// Alternately, set max digit bits to 28 since some\r\n// browsers slow down when dealing with 32-bit numbers.\r\nfunction am3(i,x,w,j,c,n) {\r\n var xl = x&0x3fff, xh = x>>14;\r\n while(--n >= 0) {\r\n var l = this[i]&0x3fff;\r\n var h = this[i++]>>14;\r\n var m = xh*l+h*xl;\r\n l = xl*l+((m&0x3fff)<<14)+w[j]+c;\r\n c = (l>>28)+(m>>14)+xh*h;\r\n w[j++] = l&0xfffffff;\r\n }\r\n return c;\r\n}\r\n\r\nif(j_lm && 'undefined' !== typeof navigator && (navigator.appName == \"Microsoft Internet Explorer\")) {\r\n BigInteger.prototype.am = am2;\r\n dbits = 30;\r\n}\r\nelse if(j_lm && 'undefined' !== typeof navigator && (navigator.appName != \"Netscape\")) {\r\n BigInteger.prototype.am = am1;\r\n dbits = 26;\r\n}\r\nelse { // Mozilla/Netscape seems to prefer am3\r\n BigInteger.prototype.am = am3;\r\n dbits = 28;\r\n}\r\n\r\nBigInteger.prototype.DB = dbits;\r\nBigInteger.prototype.DM = ((1<<dbits)-1);\r\nBigInteger.prototype.DV = (1<<dbits);\r\n\r\nvar BI_FP = 52;\r\nBigInteger.prototype.FV = Math.pow(2,BI_FP);\r\nBigInteger.prototype.F1 = BI_FP-dbits;\r\nBigInteger.prototype.F2 = 2*dbits-BI_FP;\r\n\r\n// Digit conversions\r\nvar BI_RM = \"0123456789abcdefghijklmnopqrstuvwxyz\";\r\nvar BI_RC = new Array();\r\nvar rr,vv;\r\nrr = \"0\".charCodeAt(0);\r\nfor(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;\r\nrr = \"a\".charCodeAt(0);\r\nfor(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;\r\nrr = \"A\".charCodeAt(0);\r\nfor(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;\r\n\r\nfunction int2char(n) { return BI_RM.charAt(n); }\r\nfunction intAt(s,i) {\r\n var c = BI_RC[s.charCodeAt(i)];\r\n return (c==null)?-1:c;\r\n}\r\n\r\n// (protected) copy this to r\r\nfunction bnpCopyTo(r) {\r\n for(var i = this.t-1; i >= 0; --i) r[i] = this[i];\r\n r.t = this.t;\r\n r.s = this.s;\r\n}\r\n\r\n// (protected) set from integer value x, -DV <= x < DV\r\nfunction bnpFromInt(x) {\r\n this.t = 1;\r\n this.s = (x<0)?-1:0;\r\n if(x > 0) this[0] = x;\r\n else if(x < -1) this[0] = x+DV;\r\n else this.t = 0;\r\n}\r\n\r\n// return bigint initialized to value\r\nfunction nbv(i) { var r = nbi(); r.fromInt(i); return r; }\r\n\r\n// (protected) set from string and radix\r\nfunction bnpFromString(s,b) {\r\n var k;\r\n if(b == 16) k = 4;\r\n else if(b == 8) k = 3;\r\n else if(b == 256) k = 8; // byte array\r\n else if(b == 2) k = 1;\r\n else if(b == 32) k = 5;\r\n else if(b == 4) k = 2;\r\n else { this.fromRadix(s,b); return; }\r\n this.t = 0;\r\n this.s = 0;\r\n var i = s.length, mi = false, sh = 0;\r\n while(--i >= 0) {\r\n var x = (k==8)?s[i]&0xff:intAt(s,i);\r\n if(x < 0) {\r\n if(s.charAt(i) == \"-\") mi = true;\r\n continue;\r\n }\r\n mi = false;\r\n if(sh == 0)\r\n this[this.t++] = x;\r\n else if(sh+k > this.DB) {\r\n this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;\r\n this[this.t++] = (x>>(this.DB-sh));\r\n }\r\n else\r\n this[this.t-1] |= x<<sh;\r\n sh += k;\r\n if(sh >= this.DB) sh -= this.DB;\r\n }\r\n if(k == 8 && (s[0]&0x80) != 0) {\r\n this.s = -1;\r\n if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;\r\n }\r\n this.clamp();\r\n if(mi) BigInteger.ZERO.subTo(this,this);\r\n}\r\n\r\n// (protected) clamp off excess high words\r\nfunction bnpClamp() {\r\n var c = this.s&this.DM;\r\n while(this.t > 0 && this[this.t-1] == c) --this.t;\r\n}\r\n\r\n// (public) return string representation in given radix\r\nfunction bnToString(b) {\r\n if(this.s < 0) return \"-\"+this.negate().toString(b);\r\n var k;\r\n if(b == 16) k = 4;\r\n else if(b == 8) k = 3;\r\n else if(b == 2) k = 1;\r\n else if(b == 32) k = 5;\r\n else if(b == 4) k = 2;\r\n else return this.toRadix(b);\r\n var km = (1<<k)-1, d, m = false, r = \"\", i = this.t;\r\n var p = this.DB-(i*this.DB)%k;\r\n if(i-- > 0) {\r\n if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }\r\n while(i >= 0) {\r\n if(p < k) {\r\n d = (this[i]&((1<<p)-1))<<(k-p);\r\n d |= this[--i]>>(p+=this.DB-k);\r\n }\r\n else {\r\n d = (this[i]>>(p-=k))&km;\r\n if(p <= 0) { p += this.DB; --i; }\r\n }\r\n if(d > 0) m = true;\r\n if(m) r += int2char(d);\r\n }\r\n }\r\n return m?r:\"0\";\r\n}\r\n\r\n// (public) -this\r\nfunction bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }\r\n\r\n// (public) |this|\r\nfunction bnAbs() { return (this.s<0)?this.negate():this; }\r\n\r\n// (public) return + if this > a, - if this < a, 0 if equal\r\nfunction bnCompareTo(a) {\r\n var r = this.s-a.s;\r\n if(r != 0) return r;\r\n var i = this.t;\r\n r = i-a.t;\r\n if(r != 0) return (this.s<0)?-r:r;\r\n while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;\r\n return 0;\r\n}\r\n\r\n// returns bit length of the integer x\r\nfunction nbits(x) {\r\n var r = 1, t;\r\n if((t=x>>>16) != 0) { x = t; r += 16; }\r\n if((t=x>>8) != 0) { x = t; r += 8; }\r\n if((t=x>>4) != 0) { x = t; r += 4; }\r\n if((t=x>>2) != 0) { x = t; r += 2; }\r\n if((t=x>>1) != 0) { x = t; r += 1; }\r\n return r;\r\n}\r\n\r\n// (public) return the number of bits in \"this\"\r\nfunction bnBitLength() {\r\n if(this.t <= 0) return 0;\r\n return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));\r\n}\r\n\r\n// (protected) r = this << n*DB\r\nfunction bnpDLShiftTo(n,r) {\r\n var i;\r\n for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];\r\n for(i = n-1; i >= 0; --i) r[i] = 0;\r\n r.t = this.t+n;\r\n r.s = this.s;\r\n}\r\n\r\n// (protected) r = this >> n*DB\r\nfunction bnpDRShiftTo(n,r) {\r\n for(var i = n; i < this.t; ++i) r[i-n] = this[i];\r\n r.t = Math.max(this.t-n,0);\r\n r.s = this.s;\r\n}\r\n\r\n// (protected) r = this << n\r\nfunction bnpLShiftTo(n,r) {\r\n var bs = n%this.DB;\r\n var cbs = this.DB-bs;\r\n var bm = (1<<cbs)-1;\r\n var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;\r\n for(i = this.t-1; i >= 0; --i) {\r\n r[i+ds+1] = (this[i]>>cbs)|c;\r\n c = (this[i]&bm)<<bs;\r\n }\r\n for(i = ds-1; i >= 0; --i) r[i] = 0;\r\n r[ds] = c;\r\n r.t = this.t+ds+1;\r\n r.s = this.s;\r\n r.clamp();\r\n}\r\n\r\n// (protected) r = this >> n\r\nfunction bnpRShiftTo(n,r) {\r\n r.s = this.s;\r\n var ds = Math.floor(n/this.DB);\r\n if(ds >= this.t) { r.t = 0; return; }\r\n var bs = n%this.DB;\r\n var cbs = this.DB-bs;\r\n var bm = (1<<bs)-1;\r\n r[0] = this[ds]>>bs;\r\n for(var i = ds+1; i < this.t; ++i) {\r\n r[i-ds-1] |= (this[i]&bm)<<cbs;\r\n r[i-ds] = this[i]>>bs;\r\n }\r\n if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;\r\n r.t = this.t-ds;\r\n r.clamp();\r\n}\r\n\r\n// (protected) r = this - a\r\nfunction bnpSubTo(a,r) {\r\n var i = 0, c = 0, m = Math.min(a.t,this.t);\r\n while(i < m) {\r\n c += this[i]-a[i];\r\n r[i++] = c&this.DM;\r\n c >>= this.DB;\r\n }\r\n if(a.t < this.t) {\r\n c -= a.s;\r\n while(i < this.t) {\r\n c += this[i];\r\n r[i++] = c&this.DM;\r\n c >>= this.DB;\r\n }\r\n c += this.s;\r\n }\r\n else {\r\n c += this.s;\r\n while(i < a.t) {\r\n c -= a[i];\r\n r[i++] = c&this.DM;\r\n c >>= this.DB;\r\n }\r\n c -= a.s;\r\n }\r\n r.s = (c<0)?-1:0;\r\n if(c < -1) r[i++] = this.DV+c;\r\n else if(c > 0) r[i++] = c;\r\n r.t = i;\r\n r.clamp();\r\n}\r\n\r\n// (protected) r = this * a, r != this,a (HAC 14.12)\r\n// \"this\" should be the larger one if appropriate.\r\nfunction bnpMultiplyTo(a,r) {\r\n var x = this.abs(), y = a.abs();\r\n var i = x.t;\r\n r.t = i+y.t;\r\n while(--i >= 0) r[i] = 0;\r\n for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);\r\n r.s = 0;\r\n r.clamp();\r\n if(this.s != a.s) BigInteger.ZERO.subTo(r,r);\r\n}\r\n\r\n// (protected) r = this^2, r != this (HAC 14.16)\r\nfunction bnpSquareTo(r) {\r\n var x = this.abs();\r\n var i = r.t = 2*x.t;\r\n while(--i >= 0) r[i] = 0;\r\n for(i = 0; i < x.t-1; ++i) {\r\n var c = x.am(i,x[i],r,2*i,0,1);\r\n if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {\r\n r[i+x.t] -= x.DV;\r\n r[i+x.t+1] = 1;\r\n }\r\n }\r\n if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);\r\n r.s = 0;\r\n r.clamp();\r\n}\r\n\r\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\r\n// r != q, this != m. q or r may be null.\r\nfunction bnpDivRemTo(m,q,r) {\r\n var pm = m.abs();\r\n if(pm.t <= 0) return;\r\n var pt = this.abs();\r\n if(pt.t < pm.t) {\r\n if(q != null) q.fromInt(0);\r\n if(r != null) this.copyTo(r);\r\n return;\r\n }\r\n if(r == null) r = nbi();\r\n var y = nbi(), ts = this.s, ms = m.s;\r\n var nsh = this.DB-nbits(pm[pm.t-1]);\t// normalize modulus\r\n if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }\r\n else { pm.copyTo(y); pt.copyTo(r); }\r\n var ys = y.t;\r\n var y0 = y[ys-1];\r\n if(y0 == 0) return;\r\n var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);\r\n var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;\r\n var i = r.t, j = i-ys, t = (q==null)?nbi():q;\r\n y.dlShiftTo(j,t);\r\n if(r.compareTo(t) >= 0) {\r\n r[r.t++] = 1;\r\n r.subTo(t,r);\r\n }\r\n BigInteger.ONE.dlShiftTo(ys,t);\r\n t.subTo(y,y);\t// \"negative\" y so we can replace sub with am later\r\n while(y.t < ys) y[y.t++] = 0;\r\n while(--j >= 0) {\r\n // Estimate quotient digit\r\n var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);\r\n if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) {\t// Try it out\r\n y.dlShiftTo(j,t);\r\n r.subTo(t,r);\r\n while(r[i] < --qd) r.subTo(t,r);\r\n }\r\n }\r\n if(q != null) {\r\n r.drShiftTo(ys,q);\r\n if(ts != ms) BigInteger.ZERO.subTo(q,q);\r\n }\r\n r.t = ys;\r\n r.clamp();\r\n if(nsh > 0) r.rShiftTo(nsh,r);\t// Denormalize remainder\r\n if(ts < 0) BigInteger.ZERO.subTo(r,r);\r\n}\r\n\r\n// (public) this mod a\r\nfunction bnMod(a) {\r\n var r = nbi();\r\n this.abs().divRemTo(a,null,r);\r\n if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);\r\n return r;\r\n}\r\n\r\n// Modular reduction using \"classic\" algorithm\r\nfunction Classic(m) { this.m = m; }\r\nfunction cConvert(x) {\r\n if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);\r\n else return x;\r\n}\r\nfunction cRevert(x) { return x; }\r\nfunction cReduce(x) { x.divRemTo(this.m,null,x); }\r\nfunction cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\r\nfunction cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\r\n\r\nClassic.prototype.convert = cConvert;\r\nClassic.prototype.revert = cRevert;\r\nClassic.prototype.reduce = cReduce;\r\nClassic.prototype.mulTo = cMulTo;\r\nClassic.prototype.sqrTo = cSqrTo;\r\n\r\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\r\n// justification:\r\n// xy == 1 (mod m)\r\n// xy = 1+km\r\n// xy(2-xy) = (1+km)(1-km)\r\n// x[y(2-xy)] = 1-k^2m^2\r\n// x[y(2-xy)] == 1 (mod m^2)\r\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\r\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\r\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\r\nfunction bnpInvDigit() {\r\n if(this.t < 1) return 0;\r\n var x = this[0];\r\n if((x&1) == 0) return 0;\r\n var y = x&3;\t\t// y == 1/x mod 2^2\r\n y = (y*(2-(x&0xf)*y))&0xf;\t// y == 1/x mod 2^4\r\n y = (y*(2-(x&0xff)*y))&0xff;\t// y == 1/x mod 2^8\r\n y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;\t// y == 1/x mod 2^16\r\n // last step - calculate inverse mod DV directly;\r\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\r\n y = (y*(2-x*y%this.DV))%this.DV;\t\t// y == 1/x mod 2^dbits\r\n // we really want the negative inverse, and -DV < y < DV\r\n return (y>0)?this.DV-y:-y;\r\n}\r\n\r\n// Montgomery reduction\r\nfunction Montgomery(m) {\r\n this.m = m;\r\n this.mp = m.invDigit();\r\n this.mpl = this.mp&0x7fff;\r\n this.mph = this.mp>>15;\r\n this.um = (1<<(m.DB-15))-1;\r\n this.mt2 = 2*m.t;\r\n}\r\n\r\n// xR mod m\r\nfunction montConvert(x) {\r\n var r = nbi();\r\n x.abs().dlShiftTo(this.m.t,r);\r\n r.divRemTo(this.m,null,r);\r\n if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);\r\n return r;\r\n}\r\n\r\n// x/R mod m\r\nfunction montRevert(x) {\r\n var r = nbi();\r\n x.copyTo(r);\r\n this.reduce(r);\r\n return r;\r\n}\r\n\r\n// x = x/R mod m (HAC 14.32)\r\nfunction montReduce(x) {\r\n while(x.t <= this.mt2)\t// pad x so am has enough room later\r\n x[x.t++] = 0;\r\n for(var i = 0; i < this.m.t; ++i) {\r\n // faster way of calculating u0 = x[i]*mp mod DV\r\n var j = x[i]&0x7fff;\r\n var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;\r\n // use am to combine the multiply-shift-add into one call\r\n j = i+this.m.t;\r\n x[j] += this.m.am(0,u0,x,i,0,this.m.t);\r\n // propagate carry\r\n while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }\r\n }\r\n x.clamp();\r\n x.drShiftTo(this.m.t,x);\r\n if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\r\n}\r\n\r\n// r = \"x^2/R mod m\"; x != r\r\nfunction montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\r\n\r\n// r = \"xy/R mod m\"; x,y != r\r\nfunction montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\r\n\r\nMontgomery.prototype.convert = montConvert;\r\nMontgomery.prototype.revert = montRevert;\r\nMontgomery.prototype.reduce = montReduce;\r\nMontgomery.prototype.mulTo = montMulTo;\r\nMontgomery.prototype.sqrTo = montSqrTo;\r\n\r\n// (protected) true iff this is even\r\nfunction bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }\r\n\r\n// (protected) this^e, e < 2^32, doing sqr and mul with \"r\" (HAC 14.79)\r\nfunction bnpExp(e,z) {\r\n if(e > 0xffffffff || e < 1) return BigInteger.ONE;\r\n var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;\r\n g.copyTo(r);\r\n while(--i >= 0) {\r\n z.sqrTo(r,r2);\r\n if((e&(1<<i)) > 0) z.mulTo(r2,g,r);\r\n else { var t = r; r = r2; r2 = t; }\r\n }\r\n return z.revert(r);\r\n}\r\n\r\n// (public) this^e % m, 0 <= e < 2^32\r\nfunction bnModPowInt(e,m) {\r\n var z;\r\n if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);\r\n return this.exp(e,z);\r\n}\r\n\r\n// (public)\r\nfunction bnClone() { var r = nbi(); this.copyTo(r); return r; }\r\n\r\n// (public) return value as integer\r\nfunction bnIntValue() {\r\n if(this.s < 0) {\r\n if(this.t == 1) return this[0]-this.DV;\r\n else if(this.t == 0) return -1;\r\n }\r\n else if(this.t == 1) return this[0];\r\n else if(this.t == 0) return 0;\r\n // assumes 16 < DB < 32\r\n return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];\r\n}\r\n\r\n// (public) return value as byte\r\nfunction bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }\r\n\r\n// (public) return value as short (assumes DB>=16)\r\nfunction bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }\r\n\r\n// (protected) return x s.t. r^x < DV\r\nfunction bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }\r\n\r\n// (public) 0 if this == 0, 1 if this > 0\r\nfunction bnSigNum() {\r\n if(this.s < 0) return -1;\r\n else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;\r\n else return 1;\r\n}\r\n\r\n// (protected) convert to radix string\r\nfunction bnpToRadix(b) {\r\n if(b == null) b = 10;\r\n if(this.signum() == 0 || b < 2 || b > 36) return \"0\";\r\n var cs = this.chunkSize(b);\r\n var a = Math.pow(b,cs);\r\n var d = nbv(a), y = nbi(), z = nbi(), r = \"\";\r\n this.divRemTo(d,y,z);\r\n while(y.signum() > 0) {\r\n r = (a+z.intValue()).toString(b).substr(1) + r;\r\n y.divRemTo(d,y,z);\r\n }\r\n return z.intValue().toString(b) + r;\r\n}\r\n\r\n// (protected) convert from radix string\r\nfunction bnpFromRadix(s,b) {\r\n this.fromInt(0);\r\n if(b == null) b = 10;\r\n var cs = this.chunkSize(b);\r\n var d = Math.pow(b,cs), mi = false, j = 0, w = 0;\r\n for(var i = 0; i < s.length; ++i) {\r\n var x = intAt(s,i);\r\n if(x < 0) {\r\n if(s.charAt(i) == \"-\" && this.signum() == 0) mi = true;\r\n continue;\r\n }\r\n w = b*w+x;\r\n if(++j >= cs) {\r\n this.dMultiply(d);\r\n this.dAddOffset(w,0);\r\n j = 0;\r\n w = 0;\r\n }\r\n }\r\n if(j > 0) {\r\n this.dMultiply(Math.pow(b,j));\r\n this.dAddOffset(w,0);\r\n }\r\n if(mi) BigInteger.ZERO.subTo(this,this);\r\n}\r\n\r\n// (protected) alternate constructor\r\nfunction bnpFromNumber(a,b,c) {\r\n if(\"number\" == typeof b) {\r\n // new BigInteger(int,int,RNG)\r\n if(a < 2) this.fromInt(1);\r\n else {\r\n this.fromNumber(a,c);\r\n if(!this.testBit(a-1))\t// force MSB set\r\n this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);\r\n if(this.isEven()) this.dAddOffset(1,0); // force odd\r\n while(!this.isProbablePrime(b)) {\r\n this.dAddOffset(2,0);\r\n if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);\r\n }\r\n }\r\n }\r\n else {\r\n // new BigInteger(int,RNG)\r\n var x = new Array(), t = a&7;\r\n x.length = (a>>3)+1;\r\n b.nextBytes(x);\r\n if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;\r\n this.fromString(x,256);\r\n }\r\n}\r\n\r\n// (public) convert to bigendian byte array\r\nfunction bnToByteArray() {\r\n var i = this.t, r = new Array();\r\n r[0] = this.s;\r\n var p = this.DB-(i*this.DB)%8, d, k = 0;\r\n if(i-- > 0) {\r\n if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)\r\n r[k++] = d|(this.s<<(this.DB-p));\r\n while(i >= 0) {\r\n if(p < 8) {\r\n d = (this[i]&((1<<p)-1))<<(8-p);\r\n d |= this[--i]>>(p+=this.DB-8);\r\n }\r\n else {\r\n d = (this[i]>>(p-=8))&0xff;\r\n if(p <= 0) { p += this.DB; --i; }\r\n }\r\n if((d&0x80) != 0) d |= -256;\r\n if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;\r\n if(k > 0 || d != this.s) r[k++] = d;\r\n }\r\n }\r\n return r;\r\n}\r\n\r\nfunction bnEquals(a) { return(this.compareTo(a)==0); }\r\nfunction bnMin(a) { return(this.compareTo(a)<0)?this:a; }\r\nfunction bnMax(a) { return(this.compareTo(a)>0)?this:a; }\r\n\r\n// (protected) r = this op a (bitwise)\r\nfunction bnpBitwiseTo(a,op,r) {\r\n var i, f, m = Math.min(a.t,this.t);\r\n for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);\r\n if(a.t < this.t) {\r\n f = a.s&this.DM;\r\n for(i = m; i < this.t; ++i) r[i] = op(this[i],f);\r\n r.t = this.t;\r\n }\r\n else {\r\n f = this.s&this.DM;\r\n for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);\r\n r.t = a.t;\r\n }\r\n r.s = op(this.s,a.s);\r\n r.clamp();\r\n}\r\n\r\n// (public) this & a\r\nfunction op_and(x,y) { return x&y; }\r\nfunction bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }\r\n\r\n// (public) this | a\r\nfunction op_or(x,y) { return x|y; }\r\nfunction bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }\r\n\r\n// (public) this ^ a\r\nfunction op_xor(x,y) { return x^y; }\r\nfunction bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }\r\n\r\n// (public) this & ~a\r\nfunction op_andnot(x,y) { return x&~y; }\r\nfunction bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }\r\n\r\n// (public) ~this\r\nfunction bnNot() {\r\n var r = nbi();\r\n for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];\r\n r.t = this.t;\r\n r.s = ~this.s;\r\n return r;\r\n}\r\n\r\n// (public) this << n\r\nfunction bnShiftLeft(n) {\r\n var r = nbi();\r\n if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);\r\n return r;\r\n}\r\n\r\n// (public) this >> n\r\nfunction bnShiftRight(n) {\r\n var r = nbi();\r\n if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);\r\n return r;\r\n}\r\n\r\n// return index of lowest 1-bit in x, x < 2^31\r\nfunction lbit(x) {\r\n if(x == 0) return -1;\r\n var r = 0;\r\n if((x&0xffff) == 0) { x >>= 16; r += 16; }\r\n if((x&0xff) == 0) { x >>= 8; r += 8; }\r\n if((x&0xf) == 0) { x >>= 4; r += 4; }\r\n if((x&3) == 0) { x >>= 2; r += 2; }\r\n if((x&1) == 0) ++r;\r\n return r;\r\n}\r\n\r\n// (public) returns index of lowest 1-bit (or -1 if none)\r\nfunction bnGetLowestSetBit() {\r\n for(var i = 0; i < this.t; ++i)\r\n if(this[i] != 0) return i*this.DB+lbit(this[i]);\r\n if(this.s < 0) return this.t*this.DB;\r\n return -1;\r\n}\r\n\r\n// return number of 1 bits in x\r\nfunction cbit(x) {\r\n var r = 0;\r\n while(x != 0) { x &= x-1; ++r; }\r\n return r;\r\n}\r\n\r\n// (public) return number of set bits\r\nfunction bnBitCount() {\r\n var r = 0, x = this.s&this.DM;\r\n for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);\r\n return r;\r\n}\r\n\r\n// (public) true iff nth bit is set\r\nfunction bnTestBit(n) {\r\n var j = Math.floor(n/this.DB);\r\n if(j >= this.t) return(this.s!=0);\r\n return((this[j]&(1<<(n%this.DB)))!=0);\r\n}\r\n\r\n// (protected) this op (1<<n)\r\nfunction bnpChangeBit(n,op) {\r\n var r = BigInteger.ONE.shiftLeft(n);\r\n this.bitwiseTo(r,op,r);\r\n return r;\r\n}\r\n\r\n// (public) this | (1<<n)\r\nfunction bnSetBit(n) { return this.changeBit(n,op_or); }\r\n\r\n// (public) this & ~(1<<n)\r\nfunction bnClearBit(n) { return this.changeBit(n,op_andnot); }\r\n\r\n// (public) this ^ (1<<n)\r\nfunction bnFlipBit(n) { return this.changeBit(n,op_xor); }\r\n\r\n// (protected) r = this + a\r\nfunction bnpAddTo(a,r) {\r\n var i = 0, c = 0, m = Math.min(a.t,this.t);\r\n while(i < m) {\r\n c += this[i]+a[i];\r\n r[i++] = c&this.DM;\r\n c >>= this.DB;\r\n }\r\n if(a.t < this.t) {\r\n c += a.s;\r\n while(i < this.t) {\r\n c += this[i];\r\n r[i++] = c&this.DM;\r\n c >>= this.DB;\r\n }\r\n c += this.s;\r\n }\r\n else {\r\n c += this.s;\r\n while(i < a.t) {\r\n c += a[i];\r\n r[i++] = c&this.DM;\r\n c >>= this.DB;\r\n }\r\n c += a.s;\r\n }\r\n r.s = (c<0)?-1:0;\r\n if(c > 0) r[i++] = c;\r\n else if(c < -1) r[i++] = this.DV+c;\r\n r.t = i;\r\n r.clamp();\r\n}\r\n\r\n// (public) this + a\r\nfunction bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }\r\n\r\n// (public) this - a\r\nfunction bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }\r\n\r\n// (public) this * a\r\nfunction bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }\r\n\r\n// (public) this^2\r\nfunction bnSquare() { var r = nbi(); this.squareTo(r); return r; }\r\n\r\n// (public) this / a\r\nfunction bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }\r\n\r\n// (public) this % a\r\nfunction bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }\r\n\r\n// (public) [this/a,this%a]\r\nfunction bnDivideAndRemainder(a) {\r\n var q = nbi(), r = nbi();\r\n this.divRemTo(a,q,r);\r\n return new Array(q,r);\r\n}\r\n\r\n// (protected) this *= n, this >= 0, 1 < n < DV\r\nfunction bnpDMultiply(n) {\r\n this[this.t] = this.am(0,n-1,this,0,0,this.t);\r\n ++this.t;\r\n this.clamp();\r\n}\r\n\r\n// (protected) this += n << w words, this >= 0\r\nfunction bnpDAddOffset(n,w) {\r\n if(n == 0) return;\r\n while(this.t <= w) this[this.t++] = 0;\r\n this[w] += n;\r\n while(this[w] >= this.DV) {\r\n this[w] -= this.DV;\r\n if(++w >= this.t) this[this.t++] = 0;\r\n ++this[w];\r\n }\r\n}\r\n\r\n// A \"null\" reducer\r\nfunction NullExp() {}\r\nfunction nNop(x) { return x; }\r\nfunction nMulTo(x,y,r) { x.multiplyTo(y,r); }\r\nfunction nSqrTo(x,r) { x.squareTo(r); }\r\n\r\nNullExp.prototype.convert = nNop;\r\nNullExp.prototype.revert = nNop;\r\nNullExp.prototype.mulTo = nMulTo;\r\nNullExp.prototype.sqrTo = nSqrTo;\r\n\r\n// (public) this^e\r\nfunction bnPow(e) { return this.exp(e,new NullExp()); }\r\n\r\n// (protected) r = lower n words of \"this * a\", a.t <= n\r\n// \"this\" should be the larger one if appropriate.\r\nfunction bnpMultiplyLowerTo(a,n,r) {\r\n var i = Math.min(this.t+a.t,n);\r\n r.s = 0; // assumes a,this >= 0\r\n r.t = i;\r\n while(i > 0) r[--i] = 0;\r\n var j;\r\n for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);\r\n for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);\r\n r.clamp();\r\n}\r\n\r\n// (protected) r = \"this * a\" without lower n words, n > 0\r\n// \"this\" should be the larger one if appropriate.\r\nfunction bnpMultiplyUpperTo(a,n,r) {\r\n --n;\r\n var i = r.t = this.t+a.t-n;\r\n r.s = 0; // assumes a,this >= 0\r\n while(--i >= 0) r[i] = 0;\r\n for(i = Math.max(n-this.t,0); i < a.t; ++i)\r\n r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);\r\n r.clamp();\r\n r.drShiftTo(1,r);\r\n}\r\n\r\n// Barrett modular reduction\r\nfunction Barrett(m) {\r\n // setup Barrett\r\n this.r2 = nbi();\r\n this.q3 = nbi();\r\n BigInteger.ONE.dlShiftTo(2*m.t,this.r2);\r\n this.mu = this.r2.divide(m);\r\n this.m = m;\r\n}\r\n\r\nfunction barrettConvert(x) {\r\n if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);\r\n else if(x.compareTo(this.m) < 0) return x;\r\n else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }\r\n}\r\n\r\nfunction barrettRevert(x) { return x; }\r\n\r\n// x = x mod m (HAC 14.42)\r\nfunction barrettReduce(x) {\r\n x.drShiftTo(this.m.t-1,this.r2);\r\n if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\r\n this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\r\n this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\r\n while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\r\n x.subTo(this.r2,x);\r\n while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\r\n}\r\n\r\n// r = x^2 mod m; x != r\r\nfunction barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }\r\n\r\n// r = x*y mod m; x,y != r\r\nfunction barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }\r\n\r\nBarrett.prototype.convert = barrettConvert;\r\nBarrett.prototype.revert = barrettRevert;\r\nBarrett.prototype.reduce = barrettReduce;\r\nBarrett.prototype.mulTo = barrettMulTo;\r\nBarrett.prototype.sqrTo = barrettSqrTo;\r\n\r\n// (public) this^e % m (HAC 14.85)\r\nfunction bnModPow(e,m) {\r\n var i = e.bitLength(), k, r = nbv(1), z;\r\n if(i <= 0) return r;\r\n else if(i < 18) k = 1;\r\n else if(i < 48) k = 3;\r\n else if(i < 144) k = 4;\r\n else if(i < 768) k = 5;\r\n else k = 6;\r\n if(i < 8)\r\n z = new Classic(m);\r\n else if(m.isEven())\r\n z = new Barrett(m);\r\n else\r\n z = new Montgomery(m);\r\n\r\n // precomputation\r\n var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;\r\n g[1] = z.convert(this);\r\n if(k > 1) {\r\n var g2 = nbi();\r\n z.sqrTo(g[1],g2);\r\n while(n <= km) {\r\n g[n] = nbi();\r\n z.mulTo(g2,g[n-2],g[n]);\r\n n += 2;\r\n }\r\n }\r\n\r\n var j = e.t-1, w, is1 = true, r2 = nbi(), t;\r\n i = nbits(e[j])-1;\r\n while(j >= 0) {\r\n if(i >= k1) w = (e[j]>>(i-k1))&km;\r\n else {\r\n w = (e[j]&((1<<(i+1))-1))<<(k1-i);\r\n if(j > 0) w |= e[j-1]>>(this.DB+i-k1);\r\n }\r\n\r\n n = k;\r\n while((w&1) == 0) { w >>= 1; --n; }\r\n if((i -= n) < 0) { i += this.DB; --j; }\r\n if(is1) {\t// ret == 1, don't bother squaring or multiplying it\r\n g[w].copyTo(r);\r\n is1 = false;\r\n }\r\n else {\r\n while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }\r\n if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }\r\n z.mulTo(r2,g[w],r);\r\n }\r\n\r\n while(j >= 0 && (e[j]&(1<<i)) == 0) {\r\n z.sqrTo(r,r2); t = r; r = r2; r2 = t;\r\n if(--i < 0) { i = this.DB-1; --j; }\r\n }\r\n }\r\n return z.revert(r);\r\n}\r\n\r\n// (public) gcd(this,a) (HAC 14.54)\r\nfunction bnGCD(a) {\r\n var x = (this.s<0)?this.negate():this.clone();\r\n var y = (a.s<0)?a.negate():a.clone();\r\n if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }\r\n var i = x.getLowestSetBit(), g = y.getLowestSetBit();\r\n if(g < 0) return x;\r\n if(i < g) g = i;\r\n if(g > 0) {\r\n x.rShiftTo(g,x);\r\n y.rShiftTo(g,y);\r\n }\r\n while(x.signum() > 0) {\r\n if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);\r\n if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);\r\n if(x.compareTo(y) >= 0) {\r\n x.subTo(y,x);\r\n x.rShiftTo(1,x);\r\n }\r\n else {\r\n y.subTo(x,y);\r\n y.rShiftTo(1,y);\r\n }\r\n }\r\n if(g > 0) y.lShiftTo(g,y);\r\n return y;\r\n}\r\n\r\n// (protected) this % n, n < 2^26\r\nfunction bnpModInt(n) {\r\n if(n <= 0) return 0;\r\n var d = this.DV%n, r = (this.s<0)?n-1:0;\r\n if(this.t > 0)\r\n if(d == 0) r = this[0]%n;\r\n else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;\r\n return r;\r\n}\r\n\r\n// (public) 1/this % m (HAC 14.61)\r\nfunction bnModInverse(m) {\r\n var ac = m.isEven();\r\n if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;\r\n var u = m.clone(), v = this.clone();\r\n var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);\r\n while(u.signum() != 0) {\r\n while(u.isEven()) {\r\n u.rShiftTo(1,u);\r\n if(ac) {\r\n if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }\r\n a.rShiftTo(1,a);\r\n }\r\n else if(!b.isEven()) b.subTo(m,b);\r\n b.rShiftTo(1,b);\r\n }\r\n while(v.isEven()) {\r\n v.rShiftTo(1,v);\r\n if(ac) {\r\n if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }\r\n c.rShiftTo(1,c);\r\n }\r\n else if(!d.isEven()) d.subTo(m,d);\r\n d.rShiftTo(1,d);\r\n }\r\n if(u.compareTo(v) >= 0) {\r\n u.subTo(v,u);\r\n if(ac) a.subTo(c,a);\r\n b.subTo(d,b);\r\n }\r\n else {\r\n v.subTo(u,v);\r\n if(ac) c.subTo(a,c);\r\n d.subTo(b,d);\r\n }\r\n }\r\n if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;\r\n if(d.compareTo(m) >= 0) return d.subtract(m);\r\n if(d.signum() < 0) d.addTo(m,d); else return d;\r\n if(d.signum() < 0) return d.add(m); else return d;\r\n}\r\n\r\nvar lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];\r\nvar lplim = (1<<26)/lowprimes[lowprimes.length-1];\r\n\r\n// (public) test primality with certainty >= 1-.5^t\r\nfunction bnIsProbablePrime(t) {\r\n var i, x = this.abs();\r\n if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {\r\n for(i = 0; i < lowprimes.length; ++i)\r\n if(x[0] == lowprimes[i]) return true;\r\n return false;\r\n }\r\n if(x.isEven()) return false;\r\n i = 1;\r\n while(i < lowprimes.length) {\r\n var m = lowprimes[i], j = i+1;\r\n while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];\r\n m = x.modInt(m);\r\n while(i < j) if(m%lowprimes[i++] == 0) return false;\r\n }\r\n return x.millerRabin(t);\r\n}\r\n\r\n// (protected) true if probably prime (HAC 4.24, Miller-Rabin)\r\nfunction bnpMillerRabin(t) {\r\n var n1 = this.subtract(BigInteger.ONE);\r\n var k = n1.getLowestSetBit();\r\n if(k <= 0) return false;\r\n var r = n1.shiftRight(k);\r\n t = (t+1)>>1;\r\n if(t > lowprimes.length) t = lowprimes.length;\r\n var a = nbi();\r\n for(var i = 0; i < t; ++i) {\r\n //Pick bases at random, instead of starting at 2\r\n a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);\r\n var y = a.modPow(r,this);\r\n if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {\r\n var j = 1;\r\n while(j++ < k && y.compareTo(n1) != 0) {\r\n y = y.modPowInt(2,this);\r\n if(y.compareTo(BigInteger.ONE) == 0) return false;\r\n }\r\n if(y.compareTo(n1) != 0) return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\n// protected\r\nBigInteger.prototype.chunkSize = bnpChunkSize;\r\nBigInteger.prototype.toRadix = bnpToRadix;\r\nBigInteger.prototype.fromRadix = bnpFromRadix;\r\nBigInteger.prototype.fromNumber = bnpFromNumber;\r\nBigInteger.prototype.bitwiseTo = bnpBitwiseTo;\r\nBigInteger.prototype.changeBit = bnpChangeBit;\r\nBigInteger.prototype.addTo = bnpAddTo;\r\nBigInteger.prototype.dMultiply = bnpDMultiply;\r\nBigInteger.prototype.dAddOffset = bnpDAddOffset;\r\nBigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;\r\nBigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;\r\nBigInteger.prototype.modInt = bnpModInt;\r\nBigInteger.prototype.millerRabin = bnpMillerRabin;\r\n\r\n// public\r\nBigInteger.prototype.clone = bnClone;\r\nBigInteger.prototype.intValue = bnIntValue;\r\nBigInteger.prototype.byteValue = bnByteValue;\r\nBigInteger.prototype.shortValue = bnShortValue;\r\nBigInteger.prototype.signum = bnSigNum;\r\nBigInteger.prototype.toByteArray = bnToByteArray;\r\nBigInteger.prototype.equals = bnEquals;\r\nBigInteger.prototype.min = bnMin;\r\nBigInteger.prototype.max = bnMax;\r\nBigInteger.prototype.and = bnAnd;\r\nBigInteger.prototype.or = bnOr;\r\nBigInteger.prototype.xor = bnXor;\r\nBigInteger.prototype.andNot = bnAndNot;\r\nBigInteger.prototype.not = bnNot;\r\nBigInteger.prototype.shiftLeft = bnShiftLeft;\r\nBigInteger.prototype.shiftRight = bnShiftRight;\r\nBigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;\r\nBigInteger.prototype.bitCount = bnBitCount;\r\nBigInteger.prototype.testBit = bnTestBit;\r\nBigInteger.prototype.setBit = bnSetBit;\r\nBigInteger.prototype.clearBit = bnClearBit;\r\nBigInteger.prototype.flipBit = bnFlipBit;\r\nBigInteger.prototype.add = bnAdd;\r\nBigInteger.prototype.subtract = bnSubtract;\r\nBigInteger.prototype.multiply = bnMultiply;\r\nBigInteger.prototype.divide = bnDivide;\r\nBigInteger.prototype.remainder = bnRemainder;\r\nBigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;\r\nBigInteger.prototype.modPow = bnModPow;\r\nBigInteger.prototype.modInverse = bnModInverse;\r\nBigInteger.prototype.pow = bnPow;\r\nBigInteger.prototype.gcd = bnGCD;\r\nBigInteger.prototype.isProbablePrime = bnIsProbablePrime;\r\n\r\n// JSBN-specific extension\r\nBigInteger.prototype.square = bnSquare;\r\n\r\n// BigInteger interfaces not implemented in jsbn:\r\n\r\n// BigInteger(int signum, byte[] magnitude)\r\n// double doubleValue()\r\n// float floatValue()\r\n// int hashCode()\r\n// long longValue()\r\n// static BigInteger valueOf(long val)\r\n// protected\r\nBigInteger.prototype.copyTo = bnpCopyTo;\r\nBigInteger.prototype.fromInt = bnpFromInt;\r\nBigInteger.prototype.fromString = bnpFromString;\r\nBigInteger.prototype.clamp = bnpClamp;\r\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\r\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\r\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\r\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\r\nBigInteger.prototype.subTo = bnpSubTo;\r\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\r\nBigInteger.prototype.squareTo = bnpSquareTo;\r\nBigInteger.prototype.divRemTo = bnpDivRemTo;\r\nBigInteger.prototype.invDigit = bnpInvDigit;\r\nBigInteger.prototype.isEven = bnpIsEven;\r\nBigInteger.prototype.exp = bnpExp;\r\n\r\n// public\r\nBigInteger.prototype.toString = bnToString;\r\nBigInteger.prototype.negate = bnNegate;\r\nBigInteger.prototype.abs = bnAbs;\r\nBigInteger.prototype.compareTo = bnCompareTo;\r\nBigInteger.prototype.bitLength = bnBitLength;\r\nBigInteger.prototype.mod = bnMod;\r\nBigInteger.prototype.modPowInt = bnModPowInt;\r\n\r\n// \"constants\"\r\nBigInteger.ZERO = nbv(0);\r\nBigInteger.ONE = nbv(1);\r\n\r\nexports.nbi\t = nbi;\r\nexports.BigInteger = BigInteger;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 20\n// module.readableIdentifier = ./src/js/ripple/jsbn.js\n//@ sourceURL=webpack-module:///./src/js/ripple/jsbn.js");
/***/ },
/***/ 21:
/***/ function(module, exports, require) {
eval("//\r\n// Seed support\r\n//\r\n\r\nvar sjcl = require(10);\r\nvar utils = require(9);\r\nvar jsbn = require(20);\r\nvar extend = require(29);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\n\r\nvar Base = require(4).Base,\r\n UInt = require(30).UInt,\r\n UInt256 = require(23).UInt256,\r\n KeyPair = require(32).KeyPair;\r\n\r\nvar Seed = extend(function () {\r\n // Internal form: NaN or BigInteger\r\n this._curve = sjcl.ecc.curves['c256'];\r\n this._value = NaN;\r\n}, UInt);\r\n\r\nSeed.width = 16;\r\nSeed.prototype = extend({}, UInt.prototype);\r\nSeed.prototype.constructor = Seed;\r\n\r\n// value = NaN on error.\r\n// One day this will support rfc1751 too.\r\nSeed.prototype.parse_json = function (j) {\r\n if ('string' === typeof j) {\r\n if (!j.length) {\r\n this._value = NaN;\r\n // XXX Should actually always try and continue if it failed.\r\n } else if (j[0] === \"s\") {\r\n this._value = Base.decode_check(Base.VER_FAMILY_SEED, j);\r\n } else if (j.length === 32) {\r\n this._value = this.parse_hex(j);\r\n // XXX Should also try 1751\r\n } else {\r\n this.parse_passphrase(j);\r\n }\r\n } else {\r\n this._value = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nSeed.prototype.parse_passphrase = function (j) {\r\n if (\"string\" !== typeof j) {\r\n throw new Error(\"Passphrase must be a string\");\r\n }\r\n\r\n var hash = sjcl.hash.sha512.hash(sjcl.codec.utf8String.toBits(j));\r\n var bits = sjcl.bitArray.bitSlice(hash, 0, 128);\r\n\r\n this.parse_bits(bits);\r\n\r\n return this;\r\n};\r\n\r\nSeed.prototype.to_json = function () {\r\n if (!(this._value instanceof BigInteger))\r\n return NaN;\r\n\r\n var output = Base.encode_check(Base.VER_FAMILY_SEED, this.to_bytes());\r\n\r\n return output;\r\n};\r\n\r\nfunction append_int(a, i) {\r\n return [].concat(a, i >> 24, (i >> 16) & 0xff, (i >> 8) & 0xff, i & 0xff);\r\n}\r\n\r\nfunction firstHalfOfSHA512(bytes) {\r\n return sjcl.bitArray.bitSlice(\r\n sjcl.hash.sha512.hash(sjcl.codec.bytes.toBits(bytes)),\r\n 0, 256\r\n );\r\n}\r\n\r\nfunction SHA256_RIPEMD160(bits) {\r\n return sjcl.hash.ripemd160.hash(sjcl.hash.sha256.hash(bits));\r\n}\r\n\r\nSeed.prototype.get_key = function (account_id) {\r\n if (!this.is_valid()) {\r\n throw new Error(\"Cannot generate keys from invalid seed!\");\r\n }\r\n // XXX Should loop over keys until we find the right one\r\n\r\n var curve = this._curve;\r\n\r\n var seq = 0;\r\n\r\n var private_gen, public_gen, i = 0;\r\n do {\r\n private_gen = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(this.to_bytes(), i)));\r\n i++;\r\n } while (!curve.r.greaterEquals(private_gen));\r\n\r\n public_gen = curve.G.mult(private_gen);\r\n\r\n var sec;\r\n i = 0;\r\n do {\r\n sec = sjcl.bn.fromBits(firstHalfOfSHA512(append_int(append_int(public_gen.toBytesCompressed(), seq), i)));\r\n i++;\r\n } while (!curve.r.greaterEquals(sec));\r\n\r\n sec = sec.add(private_gen).mod(curve.r);\r\n\r\n return KeyPair.from_bn_secret(sec);\r\n};\r\n\r\nexports.Seed = Seed;\r\n\n\n// WEBPACK FOOTER\n// module.id = 21\n// module.readableIdentifier = ./src/js/ripple/seed.js\n//@ sourceURL=webpack-module:///./src/js/ripple/seed.js");
/***/ },
/***/ 22:
/***/ function(module, exports, require) {
eval("/**\r\n * Type definitions for binary format.\r\n *\r\n * This file should not be included directly. Instead, find the format you're\r\n * trying to parse or serialize in binformat.js and pass that to\r\n * SerializedObject.parse() or SerializedObject.serialize().\r\n */\r\n\r\nvar extend = require(29),\r\n utils = require(9),\r\n sjcl = require(10);\r\n\r\nvar amount = require(2),\r\n UInt128 = require(33).UInt128,\r\n UInt160 = require(15).UInt160,\r\n UInt256 = require(23).UInt256,\r\n Amount = amount.Amount,\r\n Currency= amount.Currency;\r\n\r\n// Shortcuts\r\nvar hex = sjcl.codec.hex,\r\n bytes = sjcl.codec.bytes;\r\n\r\nvar jsbn = require(20);\r\nvar BigInteger = jsbn.BigInteger;\r\n\r\n\r\nvar SerializedType = function (methods) {\r\n extend(this, methods);\r\n};\r\n\r\nfunction serialize_hex(so, hexData, noLength) {\r\n var byteData = bytes.fromBits(hex.toBits(hexData));\r\n if (!noLength) {\r\n SerializedType.serialize_varint(so, byteData.length);\r\n }\r\n so.append(byteData);\r\n};\r\n\r\n\r\n\r\n/**\r\n * parses bytes as hex\r\n */\r\nfunction convert_bytes_to_hex (byte_array) {\r\n return sjcl.codec.hex.fromBits(sjcl.codec.bytes.toBits(byte_array)).toUpperCase();\r\n}\r\n\r\nSerializedType.serialize_varint = function (so, val) {\r\n if (val < 0) {\r\n throw new Error(\"Variable integers are unsigned.\");\r\n }\r\n if (val <= 192) {\r\n so.append([val]);\r\n } else if (val <= 12,480) {\r\n val -= 193;\r\n so.append([193 + (val >>> 8), val & 0xff]);\r\n } else if (val <= 918744) {\r\n val -= 12481;\r\n so.append([\r\n 241 + (val >>> 16),\r\n val >>> 8 & 0xff,\r\n val & 0xff\r\n ]);\r\n } else throw new Error(\"Variable integer overflow.\");\r\n};\r\n\r\n\r\nSerializedType.prototype.parse_varint = function (so) {\r\n var b1 = so.read(1)[0], b2, b3;\r\n if (b1 <= 192) {\r\n return b1;\r\n } else if (b1 <= 240) {\r\n b2 = so.read(1)[0];\r\n return 193 + (b1-193)*256 + b2;\r\n } else if (b1 <= 254) {\r\n b2 = so.read(1)[0];\r\n b3 = so.read(1)[0];\r\n return 12481 + (b1-241)*65536 + b2*256 + b3\r\n }\r\n else {\r\n throw new Error(\"Invalid varint length indicator\");\r\n }\r\n};\r\n\r\n\r\n\r\n\r\n\r\n// In the following, we assume that the inputs are in the proper range. Is this correct?\r\n\r\n// Helper functions for 1-, 2-, and 4-byte integers.\r\n\r\n/**\r\n * Convert an integer value into an array of bytes.\r\n *\r\n * The result is appended to the serialized object (\"so\").\r\n */\r\nfunction append_byte_array(so, val, bytes) {\r\n if (\"number\" !== typeof val) {\r\n throw new Error(\"Integer is not a number\");\r\n }\r\n if (val < 0 || val >= (Math.pow(256, bytes))) {\r\n throw new Error(\"Integer out of bounds\");\r\n }\r\n var newBytes = [];\r\n for (var i=0; i<bytes; i++) {\r\n newBytes.unshift(val >>> (i*8) & 0xff);\r\n }\r\n so.append(newBytes);\r\n}\r\n\r\n// Convert a certain number of bytes from the serialized object (\"so\") into an integer.\r\nfunction readAndSum(so, bytes) {\r\n var sum = 0;\r\n for (var i = 0; i<bytes; i++) {\r\n sum += (so.read(1)[0] << (8*(bytes-1-i)) );\r\n }\r\n return sum;\r\n}\r\n\r\n\r\nvar STInt8 = exports.Int8 = new SerializedType({\r\n serialize: function (so, val) {\r\n append_byte_array(so, val, 1);\r\n },\r\n parse: function (so) {\r\n return readAndSum(so, 1);\r\n }\r\n});\r\n\r\nvar STInt16 = exports.Int16 = new SerializedType({\r\n serialize: function (so, val) {\r\n append_byte_array(so, val, 2);\r\n },\r\n parse: function (so) {\r\n return readAndSum(so, 2);\r\n }\r\n});\r\n\r\nvar STInt32 = exports.Int32 = new SerializedType({\r\n serialize: function (so, val) {\r\n append_byte_array(so, val, 4)\r\n },\r\n parse: function (so) {\r\n return readAndSum(so, 4);\r\n }\r\n});\r\n\r\n\r\nvar STInt64 = exports.Int64 = new SerializedType({\r\n serialize: function (so, val) {\r\n var bigNumObject;\r\n if (\"number\" === typeof val) {\r\n val = Math.floor(val);\r\n if (val < 0) {\r\n throw new Error(\"Negative value for unsigned Int64 is invalid.\");\r\n }\r\n bigNumObject = new BigInteger(\"\"+val, 10);\r\n } else if (\"string\" === typeof val) {\r\n if (!/^[0-9A-F]{0,16}$/i.test(val)) {\r\n throw new Error(\"Not a valid hex Int64.\");\r\n }\r\n bigNumObject = new BigInteger(val, 16);\r\n } else if (val instanceof BigInteger) {\r\n if (val.compareTo(BigInteger.ZERO) < 0) {\r\n throw new Error(\"Negative value for unsigned Int64 is invalid.\");\r\n }\r\n bigNumObject = val;\r\n } else {\r\n throw new Error(\"Invalid type for Int64\");\r\n }\r\n\r\n var hex = bigNumObject.toString(16);\r\n if (hex.length > 16) {\r\n throw new Error(\"Int64 is too large\");\r\n }\r\n while (hex.length < 16) {\r\n hex = \"0\" + hex;\r\n }\r\n return serialize_hex(so, hex, true); //noLength = true\r\n },\r\n parse: function (so) {\r\n var hi = readAndSum(so, 4);\r\n var lo = readAndSum(so, 4);\r\n\r\n var result = new BigInteger(\"\"+hi);\r\n result.shiftLeft(32);\r\n result.add(lo);\r\n return result;\r\n }\r\n});\r\n\r\nvar STHash128 = exports.Hash128 = new SerializedType({\r\n serialize: function (so, val) {\r\n var hash = UInt128.from_json(val);\r\n if (!hash.is_valid()) {\r\n throw new Error(\"Invalid Hash128\");\r\n }\r\n serialize_hex(so, hash.to_hex(), true); //noLength = true\r\n },\r\n parse: function (so) {\r\n return UInt128.from_bytes(so.read(16));\r\n }\r\n});\r\n\r\nvar STHash256 = exports.Hash256 = new SerializedType({\r\n serialize: function (so, val) {\r\n var hash = UInt256.from_json(val);\r\n if (!hash.is_valid()) {\r\n throw new Error(\"Invalid Hash256\");\r\n }\r\n serialize_hex(so, hash.to_hex(), true); //noLength = true\r\n },\r\n parse: function (so) {\r\n return UInt256.from_bytes(so.read(32));\r\n }\r\n});\r\n\r\nvar STHash160 = exports.Hash160 = new SerializedType({\r\n serialize: function (so, val) {\r\n var hash = UInt160.from_json(val);\r\n if (!hash.is_valid()) {\r\n throw new Error(\"Invalid Hash160\");\r\n }\r\n serialize_hex(so, hash.to_hex(), true); //noLength = true\r\n },\r\n parse: function (so) {\r\n return UInt160.from_bytes(so.read(20));\r\n }\r\n});\r\n\r\n// Internal\r\nvar STCurrency = new SerializedType({\r\n serialize: function (so, val) {\r\n var currency = val.to_json();\r\n if (\"XRP\" === currency) {\r\n serialize_hex(so, UInt160.HEX_ZERO, true);\r\n } else if (\"string\" === typeof currency && currency.length === 3) {\r\n var currencyCode = currency.toUpperCase(),\r\n currencyData = utils.arraySet(20, 0);\r\n\r\n if (!/^[A-Z]{3}$/.test(currencyCode) || currencyCode === \"XRP\" ) {\r\n throw new Error('Invalid currency code');\r\n }\r\n\r\n currencyData[12] = currencyCode.charCodeAt(0) & 0xff;\r\n currencyData[13] = currencyCode.charCodeAt(1) & 0xff;\r\n currencyData[14] = currencyCode.charCodeAt(2) & 0xff;\r\n\r\n so.append(currencyData);\r\n } else {\r\n throw new Error('Tried to serialize invalid/unimplemented currency type.');\r\n }\r\n },\r\n parse: function (so) {\r\n var bytes = so.read(20);\r\n var currency = Currency.from_bytes(bytes);\r\n // XXX Disabled check. Theoretically, the Currency class should support any\r\n // UInt160 value and consider it valid. But it doesn't, so for the\r\n // deserialization to be usable, we need to allow invalid results for now.\r\n //if (!currency.is_valid()) {\r\n // throw new Error(\"Invalid currency: \"+convert_bytes_to_hex(bytes));\r\n //}\r\n return currency;\r\n }\r\n});\r\n\r\nvar STAmount = exports.Amount = new SerializedType({\r\n serialize: function (so, val) {\r\n var amount = Amount.from_json(val);\r\n if (!amount.is_valid()) {\r\n throw new Error(\"Not a valid Amount object.\");\r\n }\r\n\r\n // Amount (64-bit integer)\r\n var valueBytes = utils.arraySet(8, 0);\r\n if (amount.is_native()) {\r\n var valueHex = amount._value.toString(16);\r\n\r\n // Enforce correct length (64 bits)\r\n if (valueHex.length > 16) {\r\n throw new Error('Value out of bounds');\r\n }\r\n while (valueHex.length < 16) {\r\n valueHex = \"0\" + valueHex;\r\n }\r\n\r\n valueBytes = bytes.fromBits(hex.toBits(valueHex));\r\n // Clear most significant two bits - these bits should already be 0 if\r\n // Amount enforces the range correctly, but we'll clear them anyway just\r\n // so this code can make certain guarantees about the encoded value.\r\n valueBytes[0] &= 0x3f;\r\n if (!amount.is_negative()) valueBytes[0] |= 0x40;\r\n } else {\r\n var hi = 0, lo = 0;\r\n\r\n // First bit: non-native\r\n hi |= 1 << 31;\r\n\r\n if (!amount.is_zero()) {\r\n // Second bit: non-negative?\r\n if (!amount.is_negative()) hi |= 1 << 30;\r\n\r\n // Next eight bits: offset/exponent\r\n hi |= ((97 + amount._offset) & 0xff) << 22;\r\n\r\n // Remaining 52 bits: mantissa\r\n hi |= amount._value.shiftRight(32).intValue() & 0x3fffff;\r\n lo = amount._value.intValue() & 0xffffffff;\r\n }\r\n\r\n valueBytes = sjcl.codec.bytes.fromBits([hi, lo]);\r\n }\r\n\r\n so.append(valueBytes);\r\n\r\n if (!amount.is_native()) {\r\n // Currency (160-bit hash)\r\n var currency = amount.currency();\r\n STCurrency.serialize(so, currency);\r\n\r\n // Issuer (160-bit hash)\r\n so.append(amount.issuer().to_bytes());\r\n }\r\n },\r\n parse: function (so) {\r\n var amount = new Amount();\r\n var value_bytes = so.read(8);\r\n var is_zero = !(value_bytes[0] & 0x7f);\r\n for (var i=1; i<8; i++) {\r\n is_zero = is_zero && !value_bytes[i];\r\n }\r\n if (value_bytes[0] & 0x80) {\r\n //non-native\r\n var currency = STCurrency.parse(so);\r\n var issuer_bytes = so.read(20);\r\n var issuer = UInt160.from_bytes(issuer_bytes);\r\n\r\n var offset = ((value_bytes[0] & 0x3f) << 2) + (value_bytes[1] >>> 6) - 97;\r\n var mantissa_bytes = value_bytes.slice(1);\r\n mantissa_bytes[0] &= 0x3f;\r\n var value = new BigInteger(mantissa_bytes, 256);\r\n\r\n if (value.equals(BigInteger.ZERO) && !is_zero ) {\r\n throw new Error(\"Invalid zero representation\");\r\n }\r\n\r\n amount._value = value;\r\n amount._offset = offset;\r\n amount._currency = currency;\r\n amount._issuer = issuer;\r\n amount._is_native = false;\r\n\r\n } else {\r\n //native\r\n var integer_bytes = value_bytes.slice();\r\n integer_bytes[0] &= 0x3f;\r\n amount._value = new BigInteger(integer_bytes, 256);\r\n amount._is_native = true;\r\n }\r\n amount._is_negative = !is_zero && !(value_bytes[0] & 0x40);\r\n return amount;\r\n }\r\n});\r\n\r\nvar STVL = exports.VariableLength = new SerializedType({\r\n serialize: function (so, val) {\r\n if (\"string\" === typeof val) serialize_hex(so, val);\r\n else throw new Error(\"Unknown datatype.\");\r\n },\r\n parse: function (so) {\r\n var len = this.parse_varint(so);\r\n return convert_bytes_to_hex(so.read(len));\r\n }\r\n});\r\n\r\nvar STAccount = exports.Account = new SerializedType({\r\n serialize: function (so, val) {\r\n var account = UInt160.from_json(val);\r\n if (!account.is_valid()) {\r\n throw new Error(\"Invalid account!\");\r\n }\r\n serialize_hex(so, account.to_hex());\r\n },\r\n parse: function (so) {\r\n var len = this.parse_varint(so);\r\n\t//console.log(\"KKKKKKKKKKK\",len);\r\n if (len !== 20) {\r\n throw new Error(\"Non-standard-length account ID\");\r\n }\r\n var result = UInt160.from_bytes(so.read(len));\r\n if (false && !result.is_valid()) {\r\n throw new Error(\"Invalid Account\");\r\n }\r\n return result;\r\n }\r\n});\r\n\r\nvar STPathSet = exports.PathSet = new SerializedType({\r\n typeBoundary: 0xff,\r\n typeEnd: 0x00,\r\n typeAccount: 0x01,\r\n typeCurrency: 0x10,\r\n typeIssuer: 0x20,\r\n serialize: function (so, val) {\r\n // XXX\r\n for (var i = 0, l = val.length; i < l; i++) {\r\n // Boundary\r\n if (i) STInt8.serialize(so, this.typeBoundary);\r\n\r\n for (var j = 0, l2 = val[i].length; j < l2; j++) {\r\n var entry = val[i][j];\r\n\t\t//if (entry.hasOwnProperty(\"_value\")) {entry = entry._value;}\r\n var type = 0;\r\n\r\n if (entry.account) type |= this.typeAccount;\r\n if (entry.currency) type |= this.typeCurrency;\r\n if (entry.issuer) type |= this.typeIssuer;\r\n\r\n STInt8.serialize(so, type);\r\n\r\n if (entry.account) {\r\n so.append(UInt160.from_json(entry.account).to_bytes());\r\n }\r\n if (entry.currency) {\r\n var currency = Currency.from_json(entry.currency);\r\n STCurrency.serialize(so, currency);\r\n }\r\n if (entry.issuer) {\r\n so.append(UInt160.from_json(entry.issuer).to_bytes());\r\n }\r\n }\r\n }\r\n STInt8.serialize(so, this.typeEnd);\r\n },\r\n parse: function (so) {\r\n // XXX\r\n\t// should return a list of lists:\r\n\t/*\r\n\t[\r\n\t\t[entry, entry],\r\n\t\t[entry, entry, entry]\r\n\t\t[entry]\r\n\t\t[]\r\n\t]\r\n\t\r\n\teach entry has one or more of the following attributes: amount, currency, issuer.\r\n\t*/\r\n\t\r\n\tvar path_list = [];\r\n\tvar current_path = [];\r\n\t\r\n\twhile (true) { //TODO: try/catch this loop, and catch when we run out of data without reaching the end of the data structure.\r\n\t\tvar tag_byte = so.read(1)[0];\r\n\t\t//Now determine: is this an end, boundary, or entry-begin-tag?\r\n\t\t//console.log(\"Tag byte:\", tag_byte);\r\n\t\tif (tag_byte == this.typeEnd) { //We're done.\r\n\t\t\t//console.log(\"End.\");\r\n\t\t\tif (current_path) { //close the current path, if there is one,\r\n\t\t\t\tpath_list.push(current_path);\r\n\t\t\t}\r\n\t\t\tbreak; //and conclude.\r\n\t\t} else if (tag_byte == this.typeBoundary) {\r\n\t\t\t//console.log(\"Boundary\");\r\n\t\t\tif (current_path) { //close the current path, if there is one,\r\n\t\t\t\tpath_list.push(current_path);\r\n\t\t\t}\r\n\t\t\tcurrent_path = []; //and start a new one.\r\n\t\t} else {\r\n\t\t\t//It's an entry-begin tag.\r\n\t\t\t//console.log(\"It's an entry-begin tag.\");\r\n\t\t\tvar entry = {};\r\n\t\t\tif (tag_byte & this.typeAccount) {\r\n\t\t\t\t//console.log(\"entry.account\");\r\n\t\t\t\t/*var bta = so.read(20);\r\n\t\t\t\tconsole.log(\"BTA:\", bta);*/\r\n\t\t\t\tentry.account = STHash160.parse(so);\r\n\t\t\t}\r\n\t\t\tif (tag_byte & this.typeCurrency) {\r\n\t\t\t\t//console.log(\"entry.currency\");\r\n\t\t\t\tentry.currency = STCurrency.parse(so)\r\n\t\t\t}\r\n\t\t\tif (tag_byte & this.typeIssuer) {\r\n\t\t\t\t//console.log(\"entry.issuer\");\r\n\t\t\t\tentry.issuer = STHash160.parse(so); //should know to use Base58?\r\n\t\t\t\t//console.log(\"DONE WITH ISSUER!\");\r\n\t\t\t}\r\n\t\t\tif (entry.account || entry.currency || entry.issuer) {\r\n\t\t\t\tcurrent_path.push(entry);\r\n\t\t\t} else {\r\n\t\t\t\tthrow new Error(\"Invalid path entry\"); //It must have at least something in it.\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn path_list;\r\n }\r\n});\r\n\r\nvar STVector256 = exports.Vector256 = new SerializedType({\r\n serialize: function (so, val) { //Assume val is an array of STHash256 objects.\r\n var length_as_varint = SerializedType.serialize_varint(so, val.length);\r\n\tfor (var i = 0; i<val.length; i++){\r\n\t\tSTHash256.serialize(so, val[i]);\r\n\t}\r\n },\r\n parse: function (so) {\r\n var length_from_varint = this.parse_varint(so);\r\n\tvar output = [];\r\n\tfor (var i=0; i<length_from_varint; i++) {\r\n\t\toutput.push(STHash256.parse(so));\r\n\t}\r\n\treturn output;\r\n }\r\n});\r\n\r\n\r\n\r\nfunction serialize_whatever(so, field_name, value) {\r\n\t//so: a byte-stream to serialize into.\r\n\t//field_name: a string for the field name (\"LedgerEntryType\" etc.)\r\n\t//value: the value of that field.\r\n\t\r\n\tvar field_coordinates = INVERSE_FIELDS_MAP[field_name];\r\n\tvar type_bits = parseInt(field_coordinates[0]);\r\n\tvar field_bits = parseInt(field_coordinates[1]);\r\n\tvar tag_byte = (type_bits < 16 ? type_bits<<4 : 0) | (field_bits < 16 ? field_bits : 0)\r\n\tSTInt8.serialize(so, tag_byte)\r\n\tif (type_bits >= 16) {\r\n\t\tSTInt8.serialize(so, type_bits)\r\n\t}\r\n\tif (field_bits >= 16) {\r\n\t\tSTInt8.serialize(so, field_bits)\r\n\t}\r\n\tvar serialized_object_type = TYPES_MAP[type_bits];\r\n\t//do something with val[keys] and val[keys[i]];\r\n\tserialized_object_type.serialize(so, value);\r\n}\r\n\r\n\r\n//What should this helper function be attached to?\r\n//Take the serialized object, figure out what type/field it is, and return the parsing of that.\r\nvar parse_whatever = exports.parse_whatever = function(so) {\r\n\tvar tag_byte = so.read(1)[0];\r\n\tvar type_bits = tag_byte >> 4;\r\n\tvar field_bits = tag_byte & 0x0f;\r\n\tvar type;\r\n\tvar field_name;\r\n\tif (type_bits === 0) {\r\n\t\ttype_bits = so.read(1)[0];\r\n\t}\r\n\ttype = TYPES_MAP[type_bits];\r\n\tif (\"undefined\" === typeof type) {\r\n\t\tthrow Error(\"Unknown type\");\r\n\t} else {\r\n\t\tif (field_bits === 0) {\r\n\t\t\tfield_name = FIELDS_MAP[type_bits][so.read(1)[0]];\r\n\t\t} else {\r\n\t\t\tfield_name = FIELDS_MAP[type_bits][field_bits];\r\n\t\t}\r\n\t\tif (\"undefined\" === typeof field_name) {\r\n\t\t\tthrow Error(\"Unknown field \"+tag_byte);\r\n\t\t} else {\r\n\t\t\treturn [field_name, type.parse(so)]; //key, value\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\r\nvar STObject = exports.Object = new SerializedType({\r\n serialize: function (so, val) {\r\n var keys = Object.keys(val);\r\n\tfor (var i=0; i<keys.length; i++) {\r\n\t\tserialize_whatever(so, keys[i], val[keys[i]]);\r\n\t\t//make this a function called \"serialize_whatever\"\r\n\t\t//figure out the type corresponding to field so named\r\n\t\t/*\r\n\t\tvar field_coordinates = INVERSE_FIELDS_MAP[keys[i]];\r\n\r\n\t\tvar type_bits = parseInt(field_coordinates[0]);\r\n\t\tvar field_bits = parseInt(field_coordinates[1]);\r\n\t\tconsole.log(type_bits, field_bits);\r\n\t\tvar tag_byte=(type_bits < 16 ? type_bits<<4 : 0) | (field_bits < 16 ? field_bits : 0)\r\n\t\tSTInt8.serialize(so, tag_byte)\r\n\t\tif (type_bits >= 16) {\r\n\t\t\tSTInt8.serialize(so, type_bits)\r\n\t\t}\r\n\t\tif (field_bits >= 16) {\r\n\t\t\tSTInt8.serialize(so, field_bits)\r\n\t\t}\r\n\t\tvar serialized_object_type = TYPES_MAP[type_bits];\r\n\t\t//do something with val[keys] and val[keys[i]];\r\n\t\tserialized_object_type.serialize(so, val[keys[i]]);\r\n\t\t*/\r\n\t}\r\n\tSTInt8.serialize(so, 0xe1); //Object ending marker\r\n },\r\n parse: function (so) {\r\n\t//console.log(\"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\", so.buffer, so.pointer);\r\n var output = {};\r\n\twhile (true) {\r\n\t\tif (so.peek(1)[0] === 0xe1) { //ending marker\r\n\t\t\tso.read(1);\r\n\t\t\tbreak;\r\n\t\t} else {\r\n\t\t\t//console.log(\"WTF M8\");\r\n\t\t\tvar key_and_value = parse_whatever(so);\r\n\t\t\toutput[key_and_value[0]] = key_and_value[1];\r\n\t\t\t//console.log(\"BBBBBBBBBBBBB\", key_and_value, output);\r\n\t\t}\r\n\t}\r\n\treturn output;\r\n }\r\n});\r\n\r\nvar STArray = exports.Array = new SerializedType({\r\n serialize: function (so, val) { \r\n for (var i=0; i<val.length; i++) {\r\n\t\tvar keys = Object.keys(val[i]);\r\n\t\tif (keys.length != 1) {\r\n\t\t\tthrow Error(\"Cannot serialize an array containing non-single-key objects\");\r\n\t\t} else {\r\n\t\t\tvar field_name = keys[0];\r\n\t\t\tvar value = val[i][field_name];\r\n\t\t\tserialize_whatever(so, field_name, value);\r\n\t\t}\r\n\t}\r\n\tSTInt8.serialize(so, 0xf1); //Array ending marker\r\n },\r\n parse: function (so) {\r\n var output = [];\r\n\twhile (true) {\r\n\t\tif (so.peek(1)[0] === 0xf1) { //ending marker\r\n\t\t\tso.read(1);\r\n\t\t\tbreak;\r\n\t\t} else {\r\n\t\t\tvar key_and_value = parse_whatever(so);\r\n\t\t\tvar obj = {};\r\n\t\t\tobj[key_and_value[0]] = key_and_value[1];\r\n\t\t\toutput.push(obj);\r\n\t\t}\r\n\t}\r\n return output;\r\n }\r\n});\r\n\r\n\r\nvar TYPES_MAP = [ undefined,\r\n\t//Common:\r\n\tSTInt16,\t// 1\r\n\tSTInt32,\t// 2\r\n\tSTInt64,\t// 3\r\n\tSTHash128,\t// 4\r\n\tSTHash256,\t// 5\r\n\tSTAmount,\t// 6\r\n\tSTVL,\t\t// 7\r\n\tSTAccount,\t// 8\r\n\tundefined, undefined, undefined, undefined, undefined, // 9-13 reserved\r\n\tSTObject,\t// 14\r\n\tSTArray,\t// 15\r\n\t//Uncommon:\r\n\tSTInt8,\t\t// 16\r\n\tSTHash160,\t// 17\r\n\tSTPathSet,\t// 18\r\n STVector256\t// 19\r\n]\r\n\r\nvar FIELDS_MAP = {\r\n\t//Common types\r\n\t1: { //Int16\r\n\t\t1: \"LedgerEntryType\",2: \"TransactionType\"\r\n\t},\r\n\t2: { //Int32\r\n\t\t2:\"Flags\",3:\"SourceTag\",4:\"Sequence\",5:\"PreviousTxnLgrSeq\",6:\"LedgerSequence\",\r\n\t\t7:\"CloseTime\",8:\"ParentCloseTime\",9:\"SigningTime\",10:\"Expiration\",11:\"TransferRate\",\r\n\t\t12:\"WalletSize\",13:\"OwnerCount\",14:\"DestinationTag\",\r\n\t\t//Skip 15\r\n\t\t16:\"HighQualityIn\",17:\"HighQualityOut\",18:\"LowQualityIn\",19:\"LowQualityOut\",\r\n\t\t20:\"QualityIn\",21:\"QualityOut\",22:\"StampEscrow\",23:\"BondAmount\",24:\"LoadFee\",\r\n\t\t25:\"OfferSequence\",26:\"FirstLedgerSequence\",27:\"LastLedgerSequence\",28:\"TransactionIndex\",\r\n\t\t29:\"OperationLimit\",30:\"ReferenceFeeUnits\",31:\"ReserveBase\",32:\"ReserveIncrement\",\r\n\t\t33:\"SetFlag\",34:\"ClearFlag\",\r\n\t},\r\n\t3: { // Int64\r\n\t\t1:\"IndexNext\",2:\"IndexPrevious\",3:\"BookNode\",4:\"OwnerNode\",\r\n\t\t5:\"BaseFee\",6:\"ExchangeRate\",7:\"LowNode\",8:\"HighNode\"\r\n\t},\r\n\t4: { //Hash128\r\n\t\t1:\"EmailHash\"\r\n\t},\r\n\t5: { //Hash256\r\n\t\t1:\"LedgerHash\",2:\"ParentHash\",3:\"TransactionHash\",4:\"AccountHash\",5:\"PreviousTxnID\",\r\n\t\t6:\"LedgerIndex\",7:\"WalletLocator\",8:\"RootIndex\",16:\"BookDirectory\",17:\"InvoiceID\",\r\n\t\t18:\"Nickname\",19:\"Feature\"\r\n\t},\r\n\t6: { //Amount\r\n\t\t1:\"Amount\",2:\"Balance\",3:\"LimitAmount\",4:\"TakerPays\",5:\"TakerGets\",6:\"LowLimit\",\r\n\t\t7:\"HighLimit\",8:\"Fee\",9:\"SendMax\",16:\"MinimumOffer\",17:\"RippleEscrow\"\r\n\t},\r\n\t7: { //VL\r\n\t\t1:\"PublicKey\",2:\"MessageKey\",3:\"SigningPubKey\",4:\"TxnSignature\",5:\"Generator\",\r\n\t\t6:\"Signature\",7:\"Domain\",8:\"FundCode\",9:\"RemoveCode\",10:\"ExpireCode\",11:\"CreateCode\"\r\n\t},\r\n\t8: { //Account\r\n\t\t1:\"Account\",2:\"Owner\",3:\"Destination\",4:\"Issuer\",7:\"Target\",8:\"RegularKey\"\r\n\t},\r\n\t14: { //Object\r\n\t\t1:undefined, //end of Object\r\n\t\t2:\"TransactionMetaData\",3:\"CreatedNode\",4:\"DeletedNode\",5:\"ModifiedNode\", \r\n\t\t6:\"PreviousFields\",7:\"FinalFields\",8:\"NewFields\",9:\"TemplateEntry\",\r\n\t},\r\n\t15: { //Array\r\n\t\t1:undefined, //end of Array\r\n\t\t2:\"SigningAccounts\",3:\"TxnSignatures\",4:\"Signatures\",5:\"Template\", \t\r\n\t\t6:\"Necessary\",7:\"Sufficient\",8:\"AffectedNodes\", \t\r\n\t},\r\n\t\r\n\t//Uncommon types\r\n\t16: { //Int8\r\n\t\t1:\"CloseResolution\",2:\"TemplateEntryType\",3:\"TransactionResult\"\r\n\t},\r\n\t17: { //Hash160\r\n\t\t1:\"TakerPaysCurrency\",2:\"TakerPaysIssuer\",3:\"TakerGetsCurrency\",4:\"TakerGetsIssuer\"\r\n\t},\r\n\t18: { //PathSet\r\n\t\t1:\"Paths\"\r\n\t},\r\n\t19: { //Vector256\r\n\t\t1:\"Indexes\",2:\"Hashes\",3:\"Features\"\r\n\t}\r\n};\r\n\r\nvar INVERSE_FIELDS_MAP = {};\r\nfor (var key1 in FIELDS_MAP) {\r\n\tfor (var key2 in FIELDS_MAP[key1]) {\r\n\t\tINVERSE_FIELDS_MAP[FIELDS_MAP[key1][key2]] = [key1, key2];\r\n\t}\r\n}\r\n\n\n// WEBPACK FOOTER\n// module.id = 22\n// module.readableIdentifier = ./src/js/ripple/serializedtypes.js\n//@ sourceURL=webpack-module:///./src/js/ripple/serializedtypes.js");
/***/ },
/***/ 23:
/***/ function(module, exports, require) {
eval("\r\nvar sjcl = require(10);\r\nvar utils = require(9);\r\nvar config = require(12);\r\nvar jsbn = require(20);\r\nvar extend = require(29);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\nvar nbi = jsbn.nbi;\r\n\r\nvar UInt = require(30).UInt,\r\n Base = require(4).Base;\r\n\r\n//\r\n// UInt256 support\r\n//\r\n\r\nvar UInt256 = extend(function () {\r\n // Internal form: NaN or BigInteger\r\n this._value = NaN;\r\n}, UInt);\r\n\r\nUInt256.width = 32;\r\nUInt256.prototype = extend({}, UInt.prototype);\r\nUInt256.prototype.constructor = UInt256;\r\n\r\nvar HEX_ZERO = UInt256.HEX_ZERO = \"00000000000000000000000000000000\" +\r\n \"00000000000000000000000000000000\";\r\nvar HEX_ONE = UInt256.HEX_ONE = \"00000000000000000000000000000000\" +\r\n \"00000000000000000000000000000001\";\r\nvar STR_ZERO = UInt256.STR_ZERO = utils.hexToString(HEX_ZERO);\r\nvar STR_ONE = UInt256.STR_ONE = utils.hexToString(HEX_ONE);\r\n\r\nexports.UInt256 = UInt256;\r\n\n\n// WEBPACK FOOTER\n// module.id = 23\n// module.readableIdentifier = ./src/js/ripple/uint256.js\n//@ sourceURL=webpack-module:///./src/js/ripple/uint256.js");
/***/ },
/***/ 24:
/***/ function(module, exports, require) {
eval("/* WEBPACK VAR INJECTION */(function(require, Buffer) {function SlowBuffer (size) {\n this.length = size;\n};\n\nvar assert = require(41);\n\nexports.INSPECT_MAX_BYTES = 50;\n\n\nfunction toHex(n) {\n if (n < 16) return '0' + n.toString(16);\n return n.toString(16);\n}\n\nfunction utf8ToBytes(str) {\n var byteArray = [];\n for (var i = 0; i < str.length; i++)\n if (str.charCodeAt(i) <= 0x7F)\n byteArray.push(str.charCodeAt(i));\n else {\n var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');\n for (var j = 0; j < h.length; j++)\n byteArray.push(parseInt(h[j], 16));\n }\n\n return byteArray;\n}\n\nfunction asciiToBytes(str) {\n var byteArray = []\n for (var i = 0; i < str.length; i++ )\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push( str.charCodeAt(i) & 0xFF );\n\n return byteArray;\n}\n\nfunction base64ToBytes(str) {\n return require(43).toByteArray(str);\n}\n\nSlowBuffer.byteLength = function (str, encoding) {\n switch (encoding || \"utf8\") {\n case 'hex':\n return str.length / 2;\n\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(str).length;\n\n case 'ascii':\n return str.length;\n\n case 'base64':\n return base64ToBytes(str).length;\n\n default:\n throw new Error('Unknown encoding');\n }\n};\n\nfunction blitBuffer(src, dst, offset, length) {\n var pos, i = 0;\n while (i < length) {\n if ((i+offset >= dst.length) || (i >= src.length))\n break;\n\n dst[i + offset] = src[i];\n i++;\n }\n return i;\n}\n\nSlowBuffer.prototype.utf8Write = function (string, offset, length) {\n var bytes, pos;\n return SlowBuffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length);\n};\n\nSlowBuffer.prototype.asciiWrite = function (string, offset, length) {\n var bytes, pos;\n return SlowBuffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length);\n};\n\nSlowBuffer.prototype.base64Write = function (string, offset, length) {\n var bytes, pos;\n return SlowBuffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length);\n};\n\nSlowBuffer.prototype.base64Slice = function (start, end) {\n var bytes = Array.prototype.slice.apply(this, arguments)\n return require(43).fromByteArray(bytes);\n}\n\nfunction decodeUtf8Char(str) {\n try {\n return decodeURIComponent(str);\n } catch (err) {\n return String.fromCharCode(0xFFFD); // UTF 8 invalid char\n }\n}\n\nSlowBuffer.prototype.utf8Slice = function () {\n var bytes = Array.prototype.slice.apply(this, arguments);\n var res = \"\";\n var tmp = \"\";\n var i = 0;\n while (i < bytes.length) {\n if (bytes[i] <= 0x7F) {\n res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]);\n tmp = \"\";\n } else\n tmp += \"%\" + bytes[i].toString(16);\n\n i++;\n }\n\n return res + decodeUtf8Char(tmp);\n}\n\nSlowBuffer.prototype.asciiSlice = function () {\n var bytes = Array.prototype.slice.apply(this, arguments);\n var ret = \"\";\n for (var i = 0; i < bytes.length; i++)\n ret += String.fromCharCode(bytes[i]);\n return ret;\n}\n\nSlowBuffer.prototype.inspect = function() {\n var out = [],\n len = this.length;\n for (var i = 0; i < len; i++) {\n out[i] = toHex(this[i]);\n if (i == exports.INSPECT_MAX_BYTES) {\n out[i + 1] = '...';\n break;\n }\n }\n return '<SlowBuffer ' + out.join(' ') + '>';\n};\n\n\nSlowBuffer.prototype.hexSlice = function(start, end) {\n var len = this.length;\n\n if (!start || start < 0) start = 0;\n if (!end || end < 0 || end > len) end = len;\n\n var out = '';\n for (var i = start; i < end; i++) {\n out += toHex(this[i]);\n }\n return out;\n};\n\n\nSlowBuffer.prototype.toString = function(encoding, start, end) {\n encoding = String(encoding || 'utf8').toLowerCase();\n start = +start || 0;\n if (typeof end == 'undefined') end = this.length;\n\n // Fastpath empty strings\n if (+end == start) {\n return '';\n }\n\n switch (encoding) {\n case 'hex':\n return this.hexSlice(start, end);\n\n case 'utf8':\n case 'utf-8':\n return this.utf8Slice(start, end);\n\n case 'ascii':\n return this.asciiSlice(start, end);\n\n case 'binary':\n return this.binarySlice(start, end);\n\n case 'base64':\n return this.base64Slice(start, end);\n\n case 'ucs2':\n case 'ucs-2':\n return this.ucs2Slice(start, end);\n\n default:\n throw new Error('Unknown encoding');\n }\n};\n\n\nSlowBuffer.prototype.hexWrite = function(string, offset, length) {\n offset = +offset || 0;\n var remaining = this.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = +length;\n if (length > remaining) {\n length = remaining;\n }\n }\n\n // must be an even number of digits\n var strLen = string.length;\n if (strLen % 2) {\n throw new Error('Invalid hex string');\n }\n if (length > strLen / 2) {\n length = strLen / 2;\n }\n for (var i = 0; i < length; i++) {\n var byte = parseInt(string.substr(i * 2, 2), 16);\n if (isNaN(byte)) throw new Error('Invalid hex string');\n this[offset + i] = byte;\n }\n SlowBuffer._charsWritten = i * 2;\n return i;\n};\n\n\nSlowBuffer.prototype.write = function(string, offset, length, encoding) {\n // Support both (string, offset, length, encoding)\n // and the legacy (string, encoding, offset, length)\n if (isFinite(offset)) {\n if (!isFinite(length)) {\n encoding = length;\n length = undefined;\n }\n } else { // legacy\n var swap = encoding;\n encoding = offset;\n offset = length;\n length = swap;\n }\n\n offset = +offset || 0;\n var remaining = this.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = +length;\n if (length > remaining) {\n length = remaining;\n }\n }\n encoding = String(encoding || 'utf8').toLowerCase();\n\n switch (encoding) {\n case 'hex':\n return this.hexWrite(string, offset, length);\n\n case 'utf8':\n case 'utf-8':\n return this.utf8Write(string, offset, length);\n\n case 'ascii':\n return this.asciiWrite(string, offset, length);\n\n case 'binary':\n return this.binaryWrite(string, offset, length);\n\n case 'base64':\n return this.base64Write(string, offset, length);\n\n case 'ucs2':\n case 'ucs-2':\n return this.ucs2Write(string, offset, length);\n\n default:\n throw new Error('Unknown encoding');\n }\n};\n\n\n// slice(start, end)\nSlowBuffer.prototype.slice = function(start, end) {\n if (end === undefined) end = this.length;\n\n if (end > this.length) {\n throw new Error('oob');\n }\n if (start > end) {\n throw new Error('oob');\n }\n\n return new Buffer(this, end - start, +start);\n};\n\nSlowBuffer.prototype.copy = function(target, targetstart, sourcestart, sourceend) {\n var temp = [];\n for (var i=sourcestart; i<sourceend; i++) {\n assert.ok(typeof this[i] !== 'undefined', \"copying undefined buffer bytes!\");\n temp.push(this[i]);\n }\n\n for (var i=targetstart; i<targetstart+temp.length; i++) {\n target[i] = temp[i-targetstart];\n }\n};\n\nfunction coerce(length) {\n // Coerce length to a number (possibly NaN), round up\n // in case it's fractional (e.g. 123.456) then do a\n // double negate to coerce a NaN to 0. Easy, right?\n length = ~~Math.ceil(+length);\n return length < 0 ? 0 : length;\n}\n\n\n// Buffer\n\nfunction Buffer(subject, encoding, offset) {\n if (!(this instanceof Buffer)) {\n return new Buffer(subject, encoding, offset);\n }\n\n var type;\n\n // Are we slicing?\n if (typeof offset === 'number') {\n this.length = coerce(encoding);\n this.parent = subject;\n this.offset = offset;\n } else {\n // Find the length\n switch (type = typeof subject) {\n case 'number':\n this.length = coerce(subject);\n break;\n\n case 'string':\n this.length = Buffer.byteLength(subject, encoding);\n break;\n\n case 'object': // Assume object is an array\n this.length = coerce(subject.length);\n break;\n\n default:\n throw new Error('First argument needs to be a number, ' +\n 'array or string.');\n }\n\n if (this.length > Buffer.poolSize) {\n // Big buffer, just alloc one.\n this.parent = new SlowBuffer(this.length);\n this.offset = 0;\n\n } else {\n // Small buffer.\n if (!pool || pool.length - pool.used < this.length) allocPool();\n this.parent = pool;\n this.offset = pool.used;\n pool.used += this.length;\n }\n\n // Treat array-ish objects as a byte array.\n if (isArrayIsh(subject)) {\n for (var i = 0; i < this.length; i++) {\n this.parent[i + this.offset] = subject[i];\n }\n } else if (type == 'string') {\n // We are a string\n this.length = this.write(subject, 0, encoding);\n }\n }\n\n}\n\nfunction isArrayIsh(subject) {\n return Array.isArray(subject) || Buffer.isBuffer(subject) ||\n subject && typeof subject === 'object' &&\n typeof subject.length === 'number';\n}\n\nexports.SlowBuffer = SlowBuffer;\nexports.Buffer = Buffer;\n\nBuffer.poolSize = 8 * 1024;\nvar pool;\n\nfunction allocPool() {\n pool = new SlowBuffer(Buffer.poolSize);\n pool.used = 0;\n}\n\n\n// Static methods\nBuffer.isBuffer = function isBuffer(b) {\n return b instanceof Buffer || b instanceof SlowBuffer;\n};\n\nBuffer.concat = function (list, totalLength) {\n if (!Array.isArray(list)) {\n throw new Error(\"Usage: Buffer.concat(list, [totalLength])\\n \\\n list should be an Array.\");\n }\n\n if (list.length === 0) {\n return new Buffer(0);\n } else if (list.length === 1) {\n return list[0];\n }\n\n if (typeof totalLength !== 'number') {\n totalLength = 0;\n for (var i = 0; i < list.length; i++) {\n var buf = list[i];\n totalLength += buf.length;\n }\n }\n\n var buffer = new Buffer(totalLength);\n var pos = 0;\n for (var i = 0; i < list.length; i++) {\n var buf = list[i];\n buf.copy(buffer, pos);\n pos += buf.length;\n }\n return buffer;\n};\n\n// Inspect\nBuffer.prototype.inspect = function inspect() {\n var out = [],\n len = this.length;\n\n for (var i = 0; i < len; i++) {\n out[i] = toHex(this.parent[i + this.offset]);\n if (i == exports.INSPECT_MAX_BYTES) {\n out[i + 1] = '...';\n break;\n }\n }\n\n return '<Buffer ' + out.join(' ') + '>';\n};\n\n\nBuffer.prototype.get = function get(i) {\n if (i < 0 || i >= this.length) throw new Error('oob');\n return this.parent[this.offset + i];\n};\n\n\nBuffer.prototype.set = function set(i, v) {\n if (i < 0 || i >= this.length) throw new Error('oob');\n return this.parent[this.offset + i] = v;\n};\n\n\n// write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')\nBuffer.prototype.write = function(string, offset, length, encoding) {\n // Support both (string, offset, length, encoding)\n // and the legacy (string, encoding, offset, length)\n if (isFinite(offset)) {\n if (!isFinite(length)) {\n encoding = length;\n length = undefined;\n }\n } else { // legacy\n var swap = encoding;\n encoding = offset;\n offset = length;\n length = swap;\n }\n\n offset = +offset || 0;\n var remaining = this.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = +length;\n if (length > remaining) {\n length = remaining;\n }\n }\n encoding = String(encoding || 'utf8').toLowerCase();\n\n var ret;\n switch (encoding) {\n case 'hex':\n ret = this.parent.hexWrite(string, this.offset + offset, length);\n break;\n\n case 'utf8':\n case 'utf-8':\n ret = this.parent.utf8Write(string, this.offset + offset, length);\n break;\n\n case 'ascii':\n ret = this.parent.asciiWrite(string, this.offset + offset, length);\n break;\n\n case 'binary':\n ret = this.parent.binaryWrite(string, this.offset + offset, length);\n break;\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n ret = this.parent.base64Write(string, this.offset + offset, length);\n break;\n\n case 'ucs2':\n case 'ucs-2':\n ret = this.parent.ucs2Write(string, this.offset + offset, length);\n break;\n\n default:\n throw new Error('Unknown encoding');\n }\n\n Buffer._charsWritten = SlowBuffer._charsWritten;\n\n return ret;\n};\n\n\n// toString(encoding, start=0, end=buffer.length)\nBuffer.prototype.toString = function(encoding, start, end) {\n encoding = String(encoding || 'utf8').toLowerCase();\n\n if (typeof start == 'undefined' || start < 0) {\n start = 0;\n } else if (start > this.length) {\n start = this.length;\n }\n\n if (typeof end == 'undefined' || end > this.length) {\n end = this.length;\n } else if (end < 0) {\n end = 0;\n }\n\n start = start + this.offset;\n end = end + this.offset;\n\n switch (encoding) {\n case 'hex':\n return this.parent.hexSlice(start, end);\n\n case 'utf8':\n case 'utf-8':\n return this.parent.utf8Slice(start, end);\n\n case 'ascii':\n return this.parent.asciiSlice(start, end);\n\n case 'binary':\n return this.parent.binarySlice(start, end);\n\n case 'base64':\n return this.parent.base64Slice(start, end);\n\n case 'ucs2':\n case 'ucs-2':\n return this.parent.ucs2Slice(start, end);\n\n default:\n throw new Error('Unknown encoding');\n }\n};\n\n\n// byteLength\nBuffer.byteLength = SlowBuffer.byteLength;\n\n\n// fill(value, start=0, end=buffer.length)\nBuffer.prototype.fill = function fill(value, start, end) {\n value || (value = 0);\n start || (start = 0);\n end || (end = this.length);\n\n if (typeof value === 'string') {\n value = value.charCodeAt(0);\n }\n if (!(typeof value === 'number') || isNaN(value)) {\n throw new Error('value is not a number');\n }\n\n if (end < start) throw new Error('end < start');\n\n // Fill 0 bytes; we're done\n if (end === start) return 0;\n if (this.length == 0) return 0;\n\n if (start < 0 || start >= this.length) {\n throw new Error('start out of bounds');\n }\n\n if (end < 0 || end > this.length) {\n throw new Error('end out of bounds');\n }\n\n return this.parent.fill(value,\n start + this.offset,\n end + this.offset);\n};\n\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function(target, target_start, start, end) {\n var source = this;\n start || (start = 0);\n end || (end = this.length);\n target_start || (target_start = 0);\n\n if (end < start) throw new Error('sourceEnd < sourceStart');\n\n // Copy 0 bytes; we're done\n if (end === start) return 0;\n if (target.length == 0 || source.length == 0) return 0;\n\n if (target_start < 0 || target_start >= target.length) {\n throw new Error('targetStart out of bounds');\n }\n\n if (start < 0 || start >= source.length) {\n throw new Error('sourceStart out of bounds');\n }\n\n if (end < 0 || end > source.length) {\n throw new Error('sourceEnd out of bounds');\n }\n\n // Are we oob?\n if (end > this.length) {\n end = this.length;\n }\n\n if (target.length - target_start < end - start) {\n end = target.length - target_start + start;\n }\n\n return this.parent.copy(target.parent,\n target_start + target.offset,\n start + this.offset,\n end + this.offset);\n};\n\n\n// slice(start, end)\nBuffer.prototype.slice = function(start, end) {\n if (end === undefined) end = this.length;\n if (end > this.length) throw new Error('oob');\n if (start > end) throw new Error('oob');\n\n return new Buffer(this.parent, end - start, +start + this.offset);\n};\n\n\n// Legacy methods for backwards compatibility.\n\nBuffer.prototype.utf8Slice = function(start, end) {\n return this.toString('utf8', start, end);\n};\n\nBuffer.prototype.binarySlice = function(start, end) {\n return this.toString('binary', start, end);\n};\n\nBuffer.prototype.asciiSlice = function(start, end) {\n return this.toString('ascii', start, end);\n};\n\nBuffer.prototype.utf8Write = function(string, offset) {\n return this.write(string, offset, 'utf8');\n};\n\nBuffer.prototype.binaryWrite = function(string, offset) {\n return this.write(string, offset, 'binary');\n};\n\nBuffer.prototype.asciiWrite = function(string, offset) {\n return this.write(string, offset, 'ascii');\n};\n\nBuffer.prototype.readUInt8 = function(offset, noAssert) {\n var buffer = this;\n\n if (!noAssert) {\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n return buffer.parent[buffer.offset + offset];\n};\n\nfunction readUInt16(buffer, offset, isBigEndian, noAssert) {\n var val = 0;\n\n\n if (!noAssert) {\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 1 < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n if (isBigEndian) {\n val = buffer.parent[buffer.offset + offset] << 8;\n val |= buffer.parent[buffer.offset + offset + 1];\n } else {\n val = buffer.parent[buffer.offset + offset];\n val |= buffer.parent[buffer.offset + offset + 1] << 8;\n }\n\n return val;\n}\n\nBuffer.prototype.readUInt16LE = function(offset, noAssert) {\n return readUInt16(this, offset, false, noAssert);\n};\n\nBuffer.prototype.readUInt16BE = function(offset, noAssert) {\n return readUInt16(this, offset, true, noAssert);\n};\n\nfunction readUInt32(buffer, offset, isBigEndian, noAssert) {\n var val = 0;\n\n if (!noAssert) {\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 3 < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n if (isBigEndian) {\n val = buffer.parent[buffer.offset + offset + 1] << 16;\n val |= buffer.parent[buffer.offset + offset + 2] << 8;\n val |= buffer.parent[buffer.offset + offset + 3];\n val = val + (buffer.parent[buffer.offset + offset] << 24 >>> 0);\n } else {\n val = buffer.parent[buffer.offset + offset + 2] << 16;\n val |= buffer.parent[buffer.offset + offset + 1] << 8;\n val |= buffer.parent[buffer.offset + offset];\n val = val + (buffer.parent[buffer.offset + offset + 3] << 24 >>> 0);\n }\n\n return val;\n}\n\nBuffer.prototype.readUInt32LE = function(offset, noAssert) {\n return readUInt32(this, offset, false, noAssert);\n};\n\nBuffer.prototype.readUInt32BE = function(offset, noAssert) {\n return readUInt32(this, offset, true, noAssert);\n};\n\n\n/*\n * Signed integer types, yay team! A reminder on how two's complement actually\n * works. The first bit is the signed bit, i.e. tells us whether or not the\n * number should be positive or negative. If the two's complement value is\n * positive, then we're done, as it's equivalent to the unsigned representation.\n *\n * Now if the number is positive, you're pretty much done, you can just leverage\n * the unsigned translations and return those. Unfortunately, negative numbers\n * aren't quite that straightforward.\n *\n * At first glance, one might be inclined to use the traditional formula to\n * translate binary numbers between the positive and negative values in two's\n * complement. (Though it doesn't quite work for the most negative value)\n * Mainly:\n * - invert all the bits\n * - add one to the result\n *\n * Of course, this doesn't quite work in Javascript. Take for example the value\n * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of\n * course, Javascript will do the following:\n *\n * > ~0xff80\n * -65409\n *\n * Whoh there, Javascript, that's not quite right. But wait, according to\n * Javascript that's perfectly correct. When Javascript ends up seeing the\n * constant 0xff80, it has no notion that it is actually a signed number. It\n * assumes that we've input the unsigned value 0xff80. Thus, when it does the\n * binary negation, it casts it into a signed value, (positive 0xff80). Then\n * when you perform binary negation on that, it turns it into a negative number.\n *\n * Instead, we're going to have to use the following general formula, that works\n * in a rather Javascript friendly way. I'm glad we don't support this kind of\n * weird numbering scheme in the kernel.\n *\n * (BIT-MAX - (unsigned)val + 1) * -1\n *\n * The astute observer, may think that this doesn't make sense for 8-bit numbers\n * (really it isn't necessary for them). However, when you get 16-bit numbers,\n * you do. Let's go back to our prior example and see how this will look:\n *\n * (0xffff - 0xff80 + 1) * -1\n * (0x007f + 1) * -1\n * (0x0080) * -1\n */\nBuffer.prototype.readInt8 = function(offset, noAssert) {\n var buffer = this;\n var neg;\n\n if (!noAssert) {\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n neg = buffer.parent[buffer.offset + offset] & 0x80;\n if (!neg) {\n return (buffer.parent[buffer.offset + offset]);\n }\n\n return ((0xff - buffer.parent[buffer.offset + offset] + 1) * -1);\n};\n\nfunction readInt16(buffer, offset, isBigEndian, noAssert) {\n var neg, val;\n\n if (!noAssert) {\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 1 < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n val = readUInt16(buffer, offset, isBigEndian, noAssert);\n neg = val & 0x8000;\n if (!neg) {\n return val;\n }\n\n return (0xffff - val + 1) * -1;\n}\n\nBuffer.prototype.readInt16LE = function(offset, noAssert) {\n return readInt16(this, offset, false, noAssert);\n};\n\nBuffer.prototype.readInt16BE = function(offset, noAssert) {\n return readInt16(this, offset, true, noAssert);\n};\n\nfunction readInt32(buffer, offset, isBigEndian, noAssert) {\n var neg, val;\n\n if (!noAssert) {\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 3 < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n val = readUInt32(buffer, offset, isBigEndian, noAssert);\n neg = val & 0x80000000;\n if (!neg) {\n return (val);\n }\n\n return (0xffffffff - val + 1) * -1;\n}\n\nBuffer.prototype.readInt32LE = function(offset, noAssert) {\n return readInt32(this, offset, false, noAssert);\n};\n\nBuffer.prototype.readInt32BE = function(offset, noAssert) {\n return readInt32(this, offset, true, noAssert);\n};\n\nfunction readFloat(buffer, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset + 3 < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n return require(34).readIEEE754(buffer, offset, isBigEndian,\n 23, 4);\n}\n\nBuffer.prototype.readFloatLE = function(offset, noAssert) {\n return readFloat(this, offset, false, noAssert);\n};\n\nBuffer.prototype.readFloatBE = function(offset, noAssert) {\n return readFloat(this, offset, true, noAssert);\n};\n\nfunction readDouble(buffer, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset + 7 < buffer.length,\n 'Trying to read beyond buffer length');\n }\n\n return require(34).readIEEE754(buffer, offset, isBigEndian,\n 52, 8);\n}\n\nBuffer.prototype.readDoubleLE = function(offset, noAssert) {\n return readDouble(this, offset, false, noAssert);\n};\n\nBuffer.prototype.readDoubleBE = function(offset, noAssert) {\n return readDouble(this, offset, true, noAssert);\n};\n\n\n/*\n * We have to make sure that the value is a valid integer. This means that it is\n * non-negative. It has no fractional component and that it does not exceed the\n * maximum allowed value.\n *\n * value The number to check for validity\n *\n * max The maximum value\n */\nfunction verifuint(value, max) {\n assert.ok(typeof (value) == 'number',\n 'cannot write a non-number as a number');\n\n assert.ok(value >= 0,\n 'specified a negative value for writing an unsigned value');\n\n assert.ok(value <= max, 'value is larger than maximum value for type');\n\n assert.ok(Math.floor(value) === value, 'value has a fractional component');\n}\n\nBuffer.prototype.writeUInt8 = function(value, offset, noAssert) {\n var buffer = this;\n\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset < buffer.length,\n 'trying to write beyond buffer length');\n\n verifuint(value, 0xff);\n }\n\n buffer.parent[buffer.offset + offset] = value;\n};\n\nfunction writeUInt16(buffer, value, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 1 < buffer.length,\n 'trying to write beyond buffer length');\n\n verifuint(value, 0xffff);\n }\n\n if (isBigEndian) {\n buffer.parent[buffer.offset + offset] = (value & 0xff00) >>> 8;\n buffer.parent[buffer.offset + offset + 1] = value & 0x00ff;\n } else {\n buffer.parent[buffer.offset + offset + 1] = (value & 0xff00) >>> 8;\n buffer.parent[buffer.offset + offset] = value & 0x00ff;\n }\n}\n\nBuffer.prototype.writeUInt16LE = function(value, offset, noAssert) {\n writeUInt16(this, value, offset, false, noAssert);\n};\n\nBuffer.prototype.writeUInt16BE = function(value, offset, noAssert) {\n writeUInt16(this, value, offset, true, noAssert);\n};\n\nfunction writeUInt32(buffer, value, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 3 < buffer.length,\n 'trying to write beyond buffer length');\n\n verifuint(value, 0xffffffff);\n }\n\n if (isBigEndian) {\n buffer.parent[buffer.offset + offset] = (value >>> 24) & 0xff;\n buffer.parent[buffer.offset + offset + 1] = (value >>> 16) & 0xff;\n buffer.parent[buffer.offset + offset + 2] = (value >>> 8) & 0xff;\n buffer.parent[buffer.offset + offset + 3] = value & 0xff;\n } else {\n buffer.parent[buffer.offset + offset + 3] = (value >>> 24) & 0xff;\n buffer.parent[buffer.offset + offset + 2] = (value >>> 16) & 0xff;\n buffer.parent[buffer.offset + offset + 1] = (value >>> 8) & 0xff;\n buffer.parent[buffer.offset + offset] = value & 0xff;\n }\n}\n\nBuffer.prototype.writeUInt32LE = function(value, offset, noAssert) {\n writeUInt32(this, value, offset, false, noAssert);\n};\n\nBuffer.prototype.writeUInt32BE = function(value, offset, noAssert) {\n writeUInt32(this, value, offset, true, noAssert);\n};\n\n\n/*\n * We now move onto our friends in the signed number category. Unlike unsigned\n * numbers, we're going to have to worry a bit more about how we put values into\n * arrays. Since we are only worrying about signed 32-bit values, we're in\n * slightly better shape. Unfortunately, we really can't do our favorite binary\n * & in this system. It really seems to do the wrong thing. For example:\n *\n * > -32 & 0xff\n * 224\n *\n * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of\n * this aren't treated as a signed number. Ultimately a bad thing.\n *\n * What we're going to want to do is basically create the unsigned equivalent of\n * our representation and pass that off to the wuint* functions. To do that\n * we're going to do the following:\n *\n * - if the value is positive\n * we can pass it directly off to the equivalent wuint\n * - if the value is negative\n * we do the following computation:\n * mb + val + 1, where\n * mb is the maximum unsigned value in that byte size\n * val is the Javascript negative integer\n *\n *\n * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If\n * you do out the computations:\n *\n * 0xffff - 128 + 1\n * 0xffff - 127\n * 0xff80\n *\n * You can then encode this value as the signed version. This is really rather\n * hacky, but it should work and get the job done which is our goal here.\n */\n\n/*\n * A series of checks to make sure we actually have a signed 32-bit number\n */\nfunction verifsint(value, max, min) {\n assert.ok(typeof (value) == 'number',\n 'cannot write a non-number as a number');\n\n assert.ok(value <= max, 'value larger than maximum allowed value');\n\n assert.ok(value >= min, 'value smaller than minimum allowed value');\n\n assert.ok(Math.floor(value) === value, 'value has a fractional component');\n}\n\nfunction verifIEEE754(value, max, min) {\n assert.ok(typeof (value) == 'number',\n 'cannot write a non-number as a number');\n\n assert.ok(value <= max, 'value larger than maximum allowed value');\n\n assert.ok(value >= min, 'value smaller than minimum allowed value');\n}\n\nBuffer.prototype.writeInt8 = function(value, offset, noAssert) {\n var buffer = this;\n\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset < buffer.length,\n 'Trying to write beyond buffer length');\n\n verifsint(value, 0x7f, -0x80);\n }\n\n if (value >= 0) {\n buffer.writeUInt8(value, offset, noAssert);\n } else {\n buffer.writeUInt8(0xff + value + 1, offset, noAssert);\n }\n};\n\nfunction writeInt16(buffer, value, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 1 < buffer.length,\n 'Trying to write beyond buffer length');\n\n verifsint(value, 0x7fff, -0x8000);\n }\n\n if (value >= 0) {\n writeUInt16(buffer, value, offset, isBigEndian, noAssert);\n } else {\n writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert);\n }\n}\n\nBuffer.prototype.writeInt16LE = function(value, offset, noAssert) {\n writeInt16(this, value, offset, false, noAssert);\n};\n\nBuffer.prototype.writeInt16BE = function(value, offset, noAssert) {\n writeInt16(this, value, offset, true, noAssert);\n};\n\nfunction writeInt32(buffer, value, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 3 < buffer.length,\n 'Trying to write beyond buffer length');\n\n verifsint(value, 0x7fffffff, -0x80000000);\n }\n\n if (value >= 0) {\n writeUInt32(buffer, value, offset, isBigEndian, noAssert);\n } else {\n writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert);\n }\n}\n\nBuffer.prototype.writeInt32LE = function(value, offset, noAssert) {\n writeInt32(this, value, offset, false, noAssert);\n};\n\nBuffer.prototype.writeInt32BE = function(value, offset, noAssert) {\n writeInt32(this, value, offset, true, noAssert);\n};\n\nfunction writeFloat(buffer, value, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 3 < buffer.length,\n 'Trying to write beyond buffer length');\n\n verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38);\n }\n\n require(34).writeIEEE754(buffer, value, offset, isBigEndian,\n 23, 4);\n}\n\nBuffer.prototype.writeFloatLE = function(value, offset, noAssert) {\n writeFloat(this, value, offset, false, noAssert);\n};\n\nBuffer.prototype.writeFloatBE = function(value, offset, noAssert) {\n writeFloat(this, value, offset, true, noAssert);\n};\n\nfunction writeDouble(buffer, value, offset, isBigEndian, noAssert) {\n if (!noAssert) {\n assert.ok(value !== undefined && value !== null,\n 'missing value');\n\n assert.ok(typeof (isBigEndian) === 'boolean',\n 'missing or invalid endian');\n\n assert.ok(offset !== undefined && offset !== null,\n 'missing offset');\n\n assert.ok(offset + 7 < buffer.length,\n 'Trying to write beyond buffer length');\n\n verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308);\n }\n\n require(34).writeIEEE754(buffer, value, offset, isBigEndian,\n 52, 8);\n}\n\nBuffer.prototype.writeDoubleLE = function(value, offset, noAssert) {\n writeDouble(this, value, offset, false, noAssert);\n};\n\nBuffer.prototype.writeDoubleBE = function(value, offset, noAssert) {\n writeDouble(this, value, offset, true, noAssert);\n};\n\nSlowBuffer.prototype.readUInt8 = Buffer.prototype.readUInt8;\nSlowBuffer.prototype.readUInt16LE = Buffer.prototype.readUInt16LE;\nSlowBuffer.prototype.readUInt16BE = Buffer.prototype.readUInt16BE;\nSlowBuffer.prototype.readUInt32LE = Buffer.prototype.readUInt32LE;\nSlowBuffer.prototype.readUInt32BE = Buffer.prototype.readUInt32BE;\nSlowBuffer.prototype.readInt8 = Buffer.prototype.readInt8;\nSlowBuffer.prototype.readInt16LE = Buffer.prototype.readInt16LE;\nSlowBuffer.prototype.readInt16BE = Buffer.prototype.readInt16BE;\nSlowBuffer.prototype.readInt32LE = Buffer.prototype.readInt32LE;\nSlowBuffer.prototype.readInt32BE = Buffer.prototype.readInt32BE;\nSlowBuffer.prototype.readFloatLE = Buffer.prototype.readFloatLE;\nSlowBuffer.prototype.readFloatBE = Buffer.prototype.readFloatBE;\nSlowBuffer.prototype.readDoubleLE = Buffer.prototype.readDoubleLE;\nSlowBuffer.prototype.readDoubleBE = Buffer.prototype.readDoubleBE;\nSlowBuffer.prototype.writeUInt8 = Buffer.prototype.writeUInt8;\nSlowBuffer.prototype.writeUInt16LE = Buffer.prototype.writeUInt16LE;\nSlowBuffer.prototype.writeUInt16BE = Buffer.prototype.writeUInt16BE;\nSlowBuffer.prototype.writeUInt32LE = Buffer.prototype.writeUInt32LE;\nSlowBuffer.prototype.writeUInt32BE = Buffer.prototype.writeUInt32BE;\nSlowBuffer.prototype.writeInt8 = Buffer.prototype.writeInt8;\nSlowBuffer.prototype.writeInt16LE = Buffer.prototype.writeInt16LE;\nSlowBuffer.prototype.writeInt16BE = Buffer.prototype.writeInt16BE;\nSlowBuffer.prototype.writeInt32LE = Buffer.prototype.writeInt32LE;\nSlowBuffer.prototype.writeInt32BE = Buffer.prototype.writeInt32BE;\nSlowBuffer.prototype.writeFloatLE = Buffer.prototype.writeFloatLE;\nSlowBuffer.prototype.writeFloatBE = Buffer.prototype.writeFloatBE;\nSlowBuffer.prototype.writeDoubleLE = Buffer.prototype.writeDoubleLE;\nSlowBuffer.prototype.writeDoubleBE = Buffer.prototype.writeDoubleBE;\n\n/* WEBPACK VAR INJECTION */}(require, require(24).Buffer))\n\n// WEBPACK FOOTER\n// module.id = 24\n// module.readableIdentifier = (webpack)/~/node-libs-browser/~/buffer-browserify/index.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/~/buffer-browserify/index.js");
/***/ },
/***/ 25:
/***/ function(module, exports, require) {
eval("module.exports = function(module) {\r\n\tif(!module.webpackPolyfill) {\r\n\t\tmodule.deprecate = function() {};\r\n\t\tmodule.paths = [];\r\n\t\t// module.parent = undefined by default\r\n\t\tmodule.children = [];\r\n\t\tmodule.webpackPolyfill = 1;\r\n\t}\r\n\treturn module;\r\n}\r\n\n\n// WEBPACK FOOTER\n// module.id = 25\n// module.readableIdentifier = (webpack)/buildin/module.js\n//@ sourceURL=webpack-module:///(webpack)/buildin/module.js");
/***/ },
/***/ 26:
/***/ function(module, exports, require) {
eval("// If there is no WebSocket, try MozWebSocket (support for some old browsers)\r\ntry {\r\n module.exports = WebSocket\r\n} catch(err) {\r\n module.exports = MozWebSocket\r\n}\n\n// WEBPACK FOOTER\n// module.id = 26\n// module.readableIdentifier = ./web_modules/ws.js\n//@ sourceURL=webpack-module:///./web_modules/ws.js");
/***/ },
/***/ 27:
/***/ function(module, exports, require) {
eval("var EventEmitter = exports.EventEmitter = function EventEmitter() {};\nvar isArray = require(35);\nvar indexOf = require(40);\n\n\n\n// By default EventEmitters will print a warning if more than\n// 10 listeners are added to it. This is a useful default which\n// helps finding memory leaks.\n//\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nvar defaultMaxListeners = 10;\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!this._events) this._events = {};\n this._maxListeners = n;\n};\n\n\nEventEmitter.prototype.emit = function(type) {\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events || !this._events.error ||\n (isArray(this._events.error) && !this._events.error.length))\n {\n if (arguments[1] instanceof Error) {\n throw arguments[1]; // Unhandled 'error' event\n } else {\n throw new Error(\"Uncaught, unspecified 'error' event.\");\n }\n return false;\n }\n }\n\n if (!this._events) return false;\n var handler = this._events[type];\n if (!handler) return false;\n\n if (typeof handler == 'function') {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n var args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n return true;\n\n } else if (isArray(handler)) {\n var args = Array.prototype.slice.call(arguments, 1);\n\n var listeners = handler.slice();\n for (var i = 0, l = listeners.length; i < l; i++) {\n listeners[i].apply(this, args);\n }\n return true;\n\n } else {\n return false;\n }\n};\n\n// EventEmitter is defined in src/node_events.cc\n// EventEmitter.prototype.emit() is also defined there.\nEventEmitter.prototype.addListener = function(type, listener) {\n if ('function' !== typeof listener) {\n throw new Error('addListener only takes instances of Function');\n }\n\n if (!this._events) this._events = {};\n\n // To avoid recursion in the case that type == \"newListeners\"! Before\n // adding it to the listeners, first emit \"newListeners\".\n this.emit('newListener', type, listener);\n if (!this._events[type]) {\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n } else if (isArray(this._events[type])) {\n\n // If we've already got an array, just append.\n this._events[type].push(listener);\n\n } else {\n // Adding the second element, need to change to array.\n this._events[type] = [this._events[type], listener];\n }\n\n // Check for listener leak\n if (isArray(this._events[type]) && !this._events[type].warned) {\n var m;\n if (this._maxListeners !== undefined) {\n m = this._maxListeners;\n } else {\n m = defaultMaxListeners;\n }\n\n if (m && m > 0 && this._events[type].length > m) {\n this._events[type].warned = true;\n console.error('(events) warning: possible EventEmitter memory ' +\n 'leak detected. %d listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit.',\n this._events[type].length);\n console.trace();\n }\n }\n return this;\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.once = function(type, listener) {\n if ('function' !== typeof listener) {\n throw new Error('.once only takes instances of Function');\n }\n\n var self = this;\n function g() {\n self.removeListener(type, g);\n listener.apply(this, arguments);\n }\n\n g.listener = listener;\n self.on(type, g);\n\n return this;\n};\n\nEventEmitter.prototype.removeListener = function(type, listener) {\n if ('function' !== typeof listener) {\n throw new Error('removeListener only takes instances of Function');\n }\n\n // does not use listeners(), so no side effect of creating _events[type]\n if (!this._events || !this._events[type]) return this;\n\n var list = this._events[type];\n\n if (isArray(list)) {\n var position = -1;\n for (var i = 0, length = list.length; i < length; i++) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener))\n {\n position = i;\n break;\n }\n }\n\n if (position < 0) return this;\n list.splice(position, 1);\n if (list.length == 0)\n delete this._events[type];\n } else if (list === listener ||\n (list.listener && list.listener === listener)) {\n delete this._events[type];\n }\n\n return this;\n};\n\nEventEmitter.prototype.removeAllListeners = function(type) {\n if (arguments.length === 0) {\n this._events = {};\n return this;\n }\n\n // does not use listeners(), so no side effect of creating _events[type]\n if (type && this._events && this._events[type]) this._events[type] = null;\n return this;\n};\n\nEventEmitter.prototype.listeners = function(type) {\n if (!this._events) this._events = {};\n if (!this._events[type]) this._events[type] = [];\n if (!isArray(this._events[type])) {\n this._events[type] = [this._events[type]];\n }\n return this._events[type];\n};\n\n\n// WEBPACK FOOTER\n// module.id = 27\n// module.readableIdentifier = (webpack)/~/node-libs-browser/lib/events.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/lib/events.js");
/***/ },
/***/ 28:
/***/ function(module, exports, require) {
eval("var events = require(27);\n\nvar isArray = require(35);\nvar Object_keys = require(36);\nvar Object_getOwnPropertyNames = require(37);\nvar Object_create = require(38);\nvar isRegExp = require(39);\n\nexports.isArray = isArray;\nexports.isDate = isDate;\nexports.isRegExp = isRegExp;\n\n\nexports.print = function () {};\nexports.puts = function () {};\nexports.debug = function() {};\n\nexports.inspect = function(obj, showHidden, depth, colors) {\n var seen = [];\n\n var stylize = function(str, styleType) {\n // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\n var styles =\n { 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39] };\n\n var style =\n { 'special': 'cyan',\n 'number': 'blue',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red' }[styleType];\n\n if (style) {\n return '\\033[' + styles[style][0] + 'm' + str +\n '\\033[' + styles[style][1] + 'm';\n } else {\n return str;\n }\n };\n if (! colors) {\n stylize = function(str, styleType) { return str; };\n }\n\n function format(value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (value && typeof value.inspect === 'function' &&\n // Filter out the util module, it's inspect function is special\n value !== exports &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n return value.inspect(recurseTimes);\n }\n\n // Primitive types cannot have properties\n switch (typeof value) {\n case 'undefined':\n return stylize('undefined', 'undefined');\n\n case 'string':\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return stylize(simple, 'string');\n\n case 'number':\n return stylize('' + value, 'number');\n\n case 'boolean':\n return stylize('' + value, 'boolean');\n }\n // For some reason typeof null is \"object\", so special case here.\n if (value === null) {\n return stylize('null', 'null');\n }\n\n // Look up the keys of the object.\n var visible_keys = Object_keys(value);\n var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys;\n\n // Functions without properties can be shortcutted.\n if (typeof value === 'function' && keys.length === 0) {\n if (isRegExp(value)) {\n return stylize('' + value, 'regexp');\n } else {\n var name = value.name ? ': ' + value.name : '';\n return stylize('[Function' + name + ']', 'special');\n }\n }\n\n // Dates without properties can be shortcutted\n if (isDate(value) && keys.length === 0) {\n return stylize(value.toUTCString(), 'date');\n }\n\n var base, type, braces;\n // Determine the object type\n if (isArray(value)) {\n type = 'Array';\n braces = ['[', ']'];\n } else {\n type = 'Object';\n braces = ['{', '}'];\n }\n\n // Make functions say that they are functions\n if (typeof value === 'function') {\n var n = value.name ? ': ' + value.name : '';\n base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';\n } else {\n base = '';\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + value.toUTCString();\n }\n\n if (keys.length === 0) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return stylize('' + value, 'regexp');\n } else {\n return stylize('[Object]', 'special');\n }\n }\n\n seen.push(value);\n\n var output = keys.map(function(key) {\n var name, str;\n if (value.__lookupGetter__) {\n if (value.__lookupGetter__(key)) {\n if (value.__lookupSetter__(key)) {\n str = stylize('[Getter/Setter]', 'special');\n } else {\n str = stylize('[Getter]', 'special');\n }\n } else {\n if (value.__lookupSetter__(key)) {\n str = stylize('[Setter]', 'special');\n }\n }\n }\n if (visible_keys.indexOf(key) < 0) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (seen.indexOf(value[key]) < 0) {\n if (recurseTimes === null) {\n str = format(value[key]);\n } else {\n str = format(value[key], recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (isArray(value)) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = stylize('[Circular]', 'special');\n }\n }\n if (typeof name === 'undefined') {\n if (type === 'Array' && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n });\n\n seen.pop();\n\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.length + 1;\n }, 0);\n\n if (length > 50) {\n output = braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n\n } else {\n output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n }\n\n return output;\n }\n return format(obj, (typeof depth === 'undefined' ? 2 : depth));\n};\n\n\nfunction isDate(d) {\n if (d instanceof Date) return true;\n if (typeof d !== 'object') return false;\n var properties = Date.prototype && Object_getOwnPropertyNames(Date.prototype);\n var proto = d.__proto__ && Object_getOwnPropertyNames(d.__proto__);\n return JSON.stringify(proto) === JSON.stringify(properties);\n}\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\nexports.log = function (msg) {};\n\nexports.pump = null;\n\nexports.inherits = function(ctor, superCtor) {\n ctor.super_ = superCtor;\n ctor.prototype = Object_create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n};\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (typeof f !== 'string') {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(exports.inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j': return JSON.stringify(args[i++]);\n default:\n return x;\n }\n });\n for(var x = args[i]; i < len; x = args[++i]){\n if (x === null || typeof x !== 'object') {\n str += ' ' + x;\n } else {\n str += ' ' + exports.inspect(x);\n }\n }\n return str;\n};\n\n\n// WEBPACK FOOTER\n// module.id = 28\n// module.readableIdentifier = (webpack)/~/node-libs-browser/lib/util.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/lib/util.js");
/***/ },
/***/ 29:
/***/ function(module, exports, require) {
eval("var hasOwn = Object.prototype.hasOwnProperty;\n\nfunction isPlainObject(obj) {\n\tif (!obj || toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval)\n\t\treturn false;\n\n\tvar has_own_constructor = hasOwnProperty.call(obj, 'constructor');\n\tvar has_is_property_of_method = hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf');\n\t// Not own constructor property must be Object\n\tif (obj.constructor && !has_own_constructor && !has_is_property_of_method)\n\t\treturn false;\n\n\t// Own properties are enumerated firstly, so to speed up,\n\t// if last one is own, then all properties are own.\n\tvar key;\n\tfor ( key in obj ) {}\n\n\treturn key === undefined || hasOwn.call( obj, key );\n};\n\nmodule.exports = function extend() {\n\tvar options, name, src, copy, copyIsArray, clone,\n\t target = arguments[0] || {},\n\t i = 1,\n\t length = arguments.length,\n\t deep = false;\n\n\t// Handle a deep copy situation\n\tif ( typeof target === \"boolean\" ) {\n\t\tdeep = target;\n\t\ttarget = arguments[1] || {};\n\t\t// skip the boolean and the target\n\t\ti = 2;\n\t}\n\n\t// Handle case when target is a string or something (possible in deep copy)\n\tif ( typeof target !== \"object\" && typeof target !== \"function\") {\n\t\ttarget = {};\n\t}\n\n\tfor ( ; i < length; i++ ) {\n\t\t// Only deal with non-null/undefined values\n\t\tif ( (options = arguments[ i ]) != null ) {\n\t\t\t// Extend the base object\n\t\t\tfor ( name in options ) {\n\t\t\t\tsrc = target[ name ];\n\t\t\t\tcopy = options[ name ];\n\n\t\t\t\t// Prevent never-ending loop\n\t\t\t\tif ( target === copy ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Recurse if we're merging plain objects or arrays\n\t\t\t\tif ( deep && copy && ( isPlainObject(copy) || (copyIsArray = Array.isArray(copy)) ) ) {\n\t\t\t\t\tif ( copyIsArray ) {\n\t\t\t\t\t\tcopyIsArray = false;\n\t\t\t\t\t\tclone = src && Array.isArray(src) ? src : [];\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclone = src && isPlainObject(src) ? src : {};\n\t\t\t\t\t}\n\n\t\t\t\t\t// Never move original objects, clone them\n\t\t\t\t\ttarget[ name ] = extend( deep, clone, copy );\n\n\t\t\t\t// Don't bring in undefined values\n\t\t\t\t} else if ( copy !== undefined ) {\n\t\t\t\t\ttarget[ name ] = copy;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return the modified object\n\treturn target;\n};\n\n\n// WEBPACK FOOTER\n// module.id = 29\n// module.readableIdentifier = ./~/extend/index.js\n//@ sourceURL=webpack-module:///./~/extend/index.js");
/***/ },
/***/ 30:
/***/ function(module, exports, require) {
eval("\r\nvar sjcl = require(10);\r\nvar utils = require(9);\r\nvar config = require(12);\r\nvar jsbn = require(20);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\nvar nbi = jsbn.nbi;\r\n\r\nvar Base = require(4).Base;\r\n\r\n//\r\n// Abstract UInt class\r\n//\r\n// Base class for UInt??? classes\r\n//\r\n\r\nvar UInt = function () {\r\n // Internal form: NaN or BigInteger\r\n this._value = NaN;\r\n};\r\n\r\nUInt.json_rewrite = function (j, opts) {\r\n return this.from_json(j).to_json(opts);\r\n};\r\n\r\n// Return a new UInt from j.\r\nUInt.from_generic = function (j) {\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_generic(j);\r\n }\r\n};\r\n\r\n// Return a new UInt from j.\r\nUInt.from_hex = function (j) {\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_hex(j);\r\n }\r\n};\r\n\r\n// Return a new UInt from j.\r\nUInt.from_json = function (j) {\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_json(j);\r\n }\r\n};\r\n\r\n// Return a new UInt from j.\r\nUInt.from_bits = function (j) {\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_bits(j);\r\n }\r\n};\r\n\r\n// Return a new UInt from j.\r\nUInt.from_bytes = function (j) {\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_bytes(j);\r\n }\r\n};\r\n\r\n// Return a new UInt from j.\r\nUInt.from_bn = function (j) {\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_bn(j);\r\n }\r\n};\r\n\r\nUInt.is_valid = function (j) {\r\n return this.from_json(j).is_valid();\r\n};\r\n\r\nUInt.prototype.clone = function () {\r\n return this.copyTo(new this.constructor());\r\n};\r\n\r\n// Returns copy.\r\nUInt.prototype.copyTo = function (d) {\r\n d._value = this._value;\r\n\r\n return d;\r\n};\r\n\r\nUInt.prototype.equals = function (d) {\r\n return this._value instanceof BigInteger && d._value instanceof BigInteger && this._value.equals(d._value);\r\n};\r\n\r\nUInt.prototype.is_valid = function () {\r\n return this._value instanceof BigInteger;\r\n};\r\n\r\nUInt.prototype.is_zero = function () {\r\n return this._value.equals(BigInteger.ZERO);\r\n};\r\n\r\n// value = NaN on error.\r\nUInt.prototype.parse_generic = function (j) {\r\n // Canonicalize and validate\r\n if (config.accounts && j in config.accounts)\r\n j = config.accounts[j].account;\r\n\r\n switch (j) {\r\n case undefined:\r\n case \"0\":\r\n case this.constructor.STR_ZERO:\r\n case this.constructor.ACCOUNT_ZERO:\r\n case this.constructor.HEX_ZERO:\r\n this._value = nbi();\r\n break;\r\n\r\n case \"1\":\r\n case this.constructor.STR_ONE:\r\n case this.constructor.ACCOUNT_ONE:\r\n case this.constructor.HEX_ONE:\r\n this._value = new BigInteger([1]);\r\n\r\n break;\r\n\r\n default:\r\n if ('string' !== typeof j) {\r\n\t this._value = NaN;\r\n }\r\n else if (j[0] === \"r\") {\r\n\t this._value = Base.decode_check(Base.VER_ACCOUNT_ID, j);\r\n }\r\n else if (this.constructor.width === j.length) {\r\n\t this._value = new BigInteger(utils.stringToArray(j), 256);\r\n }\r\n else if ((this.constructor.width*2) === j.length) {\r\n\t // XXX Check char set!\r\n\t this._value = new BigInteger(j, 16);\r\n }\r\n else {\r\n\t this._value = NaN;\r\n }\r\n }\r\n\r\n return this;\r\n};\r\n\r\nUInt.prototype.parse_hex = function (j) {\r\n if ('string' === typeof j &&\r\n j.length === (this.constructor.width * 2)) {\r\n this._value = new BigInteger(j, 16);\r\n } else {\r\n this._value = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\nUInt.prototype.parse_bits = function (j) {\r\n if (sjcl.bitArray.bitLength(j) !== this.constructor.width * 8) {\r\n this._value = NaN;\r\n } else {\r\n var bytes = sjcl.codec.bytes.fromBits(j);\r\n this.parse_bytes(bytes);\r\n }\r\n\r\n return this;\r\n};\r\n\r\n\r\nUInt.prototype.parse_bytes = function (j) {\r\n if (!Array.isArray(j) || j.length !== this.constructor.width) {\r\n\tthis._value = NaN;\r\n } else {\r\n\t this._value = new BigInteger(j, 256);\r\n }\r\n\r\n return this;\r\n};\r\n\r\n\r\nUInt.prototype.parse_json = UInt.prototype.parse_hex;\r\n\r\nUInt.prototype.parse_bn = function (j) {\r\n if (j instanceof sjcl.bn &&\r\n j.bitLength() <= this.constructor.width * 8) {\r\n var bytes = sjcl.codec.bytes.fromBits(j.toBits());\r\n\t this._value = new BigInteger(bytes, 256);\r\n } else {\r\n this._value = NaN;\r\n }\r\n\r\n return this;\r\n};\r\n\r\n// Convert from internal form.\r\nUInt.prototype.to_bytes = function () {\r\n if (!(this._value instanceof BigInteger))\r\n return null;\r\n\r\n var bytes = this._value.toByteArray();\r\n bytes = bytes.map(function (b) { return (b+256) % 256; });\r\n var target = this.constructor.width;\r\n\r\n // XXX Make sure only trim off leading zeros.\r\n bytes = bytes.slice(-target);\r\n while (bytes.length < target) bytes.unshift(0);\r\n\r\n return bytes;\r\n};\r\n\r\nUInt.prototype.to_hex = function () {\r\n if (!(this._value instanceof BigInteger))\r\n return null;\r\n\r\n var bytes = this.to_bytes();\r\n return sjcl.codec.hex.fromBits(sjcl.codec.bytes.toBits(bytes)).toUpperCase();\r\n};\r\n\r\nUInt.prototype.to_json = UInt.prototype.to_hex;\r\n\r\nUInt.prototype.to_bits = function () {\r\n if (!(this._value instanceof BigInteger))\r\n return null;\r\n\r\n var bytes = this.to_bytes();\r\n\r\n return sjcl.codec.bytes.toBits(bytes);\r\n};\r\n\r\nUInt.prototype.to_bn = function () {\r\n if (!(this._value instanceof BigInteger))\r\n return null;\r\n\r\n var bits = this.to_bits();\r\n\r\n return sjcl.bn.fromBits(bits);\r\n};\r\n\r\nexports.UInt = UInt;\r\n\r\n// vim:sw=2:sts=2:ts=8:et\r\n\n\n// WEBPACK FOOTER\n// module.id = 30\n// module.readableIdentifier = ./src/js/ripple/uint.js\n//@ sourceURL=webpack-module:///./src/js/ripple/uint.js");
/***/ },
/***/ 31:
/***/ function(module, exports, require) {
eval("var util = require(28);\r\nvar EventEmitter = require(27).EventEmitter;\r\nvar RippleError = require(19).RippleError;\r\nvar Queue = require(42).TransactionQueue;\r\nvar Amount = require(2);\r\n\r\n/**\r\n * @constructor TransactionManager\r\n * @param {Object} account\r\n */\r\n\r\nfunction TransactionManager(account) {\r\n EventEmitter.call(this);\r\n\r\n var self = this;\r\n\r\n this.account = account;\r\n this.remote = account._remote;\r\n this._timeout = void(0);\r\n this._pending = new Queue;\r\n this._next_sequence = void(0);\r\n this._cache = { };\r\n\r\n //XX Fee units\r\n this._max_fee = this.remote.max_fee;\r\n\r\n this._submission_timeout = this.remote._submission_timeout;\r\n\r\n function remote_reconnected() {\r\n self.account.get_next_sequence(function(err, sequence) {\r\n sequence_loaded(err, sequence);\r\n self._resubmit(3);\r\n });\r\n }\r\n\r\n function remote_disconnected() {\r\n self.remote.once('connect', remote_reconnected);\r\n }\r\n\r\n this.remote.on('disconnect', remote_disconnected);\r\n\r\n function sequence_loaded(err, sequence, callback) {\r\n self._next_sequence = sequence;\r\n self.emit('sequence_loaded', sequence);\r\n callback && callback();\r\n }\r\n\r\n this.account.get_next_sequence(sequence_loaded);\r\n\r\n function adjust_fees() {\r\n self._pending.forEach(function(pending) {\r\n if (self.remote.local_fee && pending.tx_json.Fee) {\r\n var old_fee = pending.tx_json.Fee;\r\n var new_fee = self.remote.fee_tx(pending.fee_units()).to_json();\r\n pending.tx_json.Fee = new_fee;\r\n pending.emit('fee_adjusted', old_fee, new_fee);\r\n }\r\n });\r\n }\r\n\r\n this.remote.on('load_changed', adjust_fees);\r\n\r\n function cache_transaction(message) {\r\n var hash = message.transaction.hash;\r\n var transaction = {\r\n ledger_hash: message.ledger_hash,\r\n ledger_index: message.ledger_index,\r\n metadata: message.meta,\r\n tx_json: message.transaction\r\n }\r\n\r\n transaction.tx_json.ledger_index = transaction.ledger_index;\r\n transaction.tx_json.inLedger = transaction.ledger_index;\r\n\r\n var pending = self._pending.get('hash', hash);\r\n\r\n if (pending) {\r\n pending.emit('success', transaction);\r\n } else {\r\n self._cache[hash] = transaction;\r\n }\r\n }\r\n\r\n this.account.on('transaction-outbound', cache_transaction);\r\n\r\n function update_pending_status(ledger) {\r\n self._pending.forEach(function(pending) {\r\n pending.last_ledger = ledger;\r\n switch (ledger.ledger_index - pending.submit_index) {\r\n case 8:\r\n pending.emit('lost', ledger);\r\n pending.emit('error', new RippleError('tejLost', 'Transaction lost'));\r\n break;\r\n case 4:\r\n pending.set_state('client_missing');\r\n pending.emit('missing', ledger);\r\n break;\r\n }\r\n });\r\n }\r\n\r\n this.remote.on('ledger_closed', update_pending_status);\r\n};\r\n\r\nutil.inherits(TransactionManager, EventEmitter);\r\n\r\n// request_tx presents transactions in\r\n// a format slightly different from\r\n// request_transaction_entry\r\nfunction rewrite_transaction(tx) {\r\n try {\r\n var result = {\r\n ledger_index: tx.ledger_index,\r\n metadata: tx.meta,\r\n tx_json: {\r\n Account: tx.Account,\r\n Amount: tx.Amount,\r\n Destination: tx.Destination,\r\n Fee: tx.Fee,\r\n Flags: tx.Flags,\r\n Sequence: tx.Sequence,\r\n SigningPubKey: tx.SigningPubKey,\r\n TransactionType: tx.TransactionType,\r\n hash: tx.hash\r\n }\r\n }\r\n } catch(exception) { }\r\n return result || { };\r\n};\r\n\r\nTransactionManager.prototype._resubmit = function(wait_ledgers) {\r\n var self = this;\r\n\r\n if (wait_ledgers) {\r\n var ledgers = Number(wait_ledgers) || 3;\r\n this._wait_ledgers(ledgers, function() {\r\n self._pending.forEach(resubmit_transaction);\r\n });\r\n } else {\r\n self._pending.forEach(resubmit_transaction);\r\n }\r\n\r\n function resubmit_transaction(pending) {\r\n if (!pending || pending.finalized) {\r\n // Transaction has been finalized, nothing to do\r\n return;\r\n }\r\n\r\n pending.emit('resubmit');\r\n\r\n if (!pending.hash) {\r\n self._request(pending);\r\n } else if (self._cache[pending.hash]) {\r\n var cached = self._cache[pending.hash];\r\n pending.emit('success', cached);\r\n delete self._cache[pending.hash];\r\n } else {\r\n // Transaction was successfully submitted, and\r\n // its hash discovered, but not validated\r\n self.remote.request_tx(pending.hash, pending_check);\r\n\r\n function pending_check(err, res) {\r\n if (self._is_not_found(err)) {\r\n //XX\r\n self._request(pending);\r\n } else {\r\n pending.emit('success', rewrite_transaction(res));\r\n }\r\n }\r\n }\r\n }\r\n};\r\n\r\nTransactionManager.prototype._wait_ledgers = function(ledgers, callback) {\r\n var self = this;\r\n var closes = 0;\r\n\r\n function ledger_closed() {\r\n if (++closes === ledgers) {\r\n callback();\r\n self.remote.removeListener('ledger_closed', ledger_closed);\r\n }\r\n }\r\n\r\n this.remote.on('ledger_closed', ledger_closed);\r\n}\r\n\r\nTransactionManager.prototype._request = function(tx) {\r\n var self = this;\r\n var remote = this.remote;\r\n\r\n if (tx.attempts > 5) {\r\n tx.emit('error', new RippleError('tejAttemptsExceeded'));\r\n return;\r\n }\r\n\r\n var submit_request = remote.request_submit();\r\n\r\n if (remote.local_signing) {\r\n tx.sign();\r\n submit_request.tx_blob(tx.serialize().to_hex());\r\n } else {\r\n submit_request.secret(tx._secret);\r\n submit_request.build_path(tx._build_path);\r\n submit_request.tx_json(tx.tx_json);\r\n }\r\n\r\n function transaction_proposed(message) {\r\n tx.hash = message.tx_json.hash;\r\n tx.set_state('client_proposed');\r\n tx.emit('proposed', {\r\n tx_json: message.tx_json,\r\n engine_result: message.engine_result,\r\n engine_result_code: message.engine_result_code,\r\n engine_result_message: message.engine_result_message,\r\n // If server is honest, don't expect a final if rejected.\r\n rejected: tx.isRejected(message.engine_result_code),\r\n });\r\n }\r\n\r\n function transaction_failed(message) {\r\n function transaction_requested(err, res) {\r\n if (self._is_not_found(err)) {\r\n self._resubmit(1);\r\n } else {\r\n //XX\r\n tx.emit('error', new RippleError(message));\r\n }\r\n }\r\n\r\n self.remote.request_tx(tx.hash, transaction_requested);\r\n }\r\n\r\n function transaction_retry(message) {\r\n switch (message.engine_result) {\r\n case 'terPRE_SEQ':\r\n self._resubmit(1);\r\n break;\r\n default:\r\n submission_error(new RippleError(message));\r\n }\r\n }\r\n\r\n function submission_error(error) {\r\n if (self._is_too_busy(error)) {\r\n self._resubmit(1);\r\n } else {\r\n //Decrement sequence\r\n self._next_sequence--;\r\n tx.set_state('remoteError');\r\n tx.emit('submitted', error);\r\n tx.emit('error', new RippleError(error));\r\n }\r\n }\r\n\r\n function submission_success(message) {\r\n if (!tx.hash) {\r\n tx.hash = message.tx_json.hash;\r\n }\r\n\r\n message.result = message.engine_result || '';\r\n\r\n tx.emit('submitted', message);\r\n\r\n switch (message.result.slice(0, 3)) {\r\n case 'tec':\r\n tx.emit('error', message);\r\n break;\r\n case 'tes':\r\n transaction_proposed(message);\r\n break;\r\n case 'tef':\r\n //tefPAST_SEQ\r\n transaction_failed(message);\r\n break;\r\n case 'ter':\r\n transaction_retry(message);\r\n break;\r\n default:\r\n submission_error(message);\r\n }\r\n }\r\n\r\n submit_request.once('success', submission_success);\r\n submit_request.once('error', submission_error);\r\n submit_request.request();\r\n\r\n submit_request.timeout(this._submission_timeout, function() {\r\n tx.emit('timeout');\r\n if (self.remote._connected) {\r\n self._resubmit(1);\r\n }\r\n });\r\n\r\n tx.set_state('client_submitted');\r\n tx.attempts++;\r\n\r\n return submit_request;\r\n};\r\n\r\nTransactionManager.prototype._is_remote_error = function(error) {\r\n return error && typeof error === 'object'\r\n && error.error === 'remoteError'\r\n && typeof error.remote === 'object'\r\n};\r\n\r\nTransactionManager.prototype._is_not_found = function(error) {\r\n return this._is_remote_error(error) && /^(txnNotFound|transactionNotFound)$/.test(error.remote.error);\r\n};\r\n\r\nTransactionManager.prototype._is_too_busy = function(error) {\r\n return this._is_remote_error(error) && error.remote.error === 'tooBusy';\r\n};\r\n\r\n/**\r\n * Entry point for TransactionManager submission\r\n *\r\n * @param {Object} tx\r\n */\r\n\r\nTransactionManager.prototype.submit = function(tx) {\r\n var self = this;\r\n\r\n // If sequence number is not yet known, defer until it is.\r\n if (!this._next_sequence) {\r\n function resubmit_transaction() {\r\n self.submit(tx);\r\n }\r\n this.once('sequence_loaded', resubmit_transaction);\r\n return;\r\n }\r\n\r\n tx.tx_json.Sequence = this._next_sequence++;\r\n tx.submit_index = this.remote._ledger_current_index;\r\n tx.last_ledger = void(0);\r\n tx.attempts = 0;\r\n tx.complete();\r\n\r\n function finalize(message) {\r\n if (!tx.finalized) {\r\n //XX\r\n self._pending.removeSequence(tx.tx_json.Sequence);\r\n tx.finalized = true;\r\n tx.emit('final', message);\r\n }\r\n }\r\n\r\n tx.on('error', finalize);\r\n tx.once('success', finalize);\r\n tx.once('abort', function() {\r\n tx.emit('error', new RippleError('tejAbort', 'Transaction aborted'));\r\n });\r\n\r\n var fee = Number(tx.tx_json.Fee);\r\n var remote = this.remote;\r\n\r\n if (!tx._secret && !tx.tx_json.TxnSignature) {\r\n tx.emit('error', new RippleError('tejSecretUnknown', 'Missing secret'));\r\n } else if (!remote.trusted && !remote.local_signing) {\r\n tx.emit('error', new RippleError('tejServerUntrusted', 'Attempt to give secret to untrusted server'));\r\n } else if (fee && fee > this._max_fee) {\r\n tx.emit('error', new RippleError('tejMaxFeeExceeded', 'Max fee exceeded'));\r\n } else {\r\n this._pending.push(tx);\r\n this._request(tx);\r\n }\r\n};\r\n\r\nexports.TransactionManager = TransactionManager;\r\n\n\n// WEBPACK FOOTER\n// module.id = 31\n// module.readableIdentifier = ./src/js/ripple/transactionmanager.js\n//@ sourceURL=webpack-module:///./src/js/ripple/transactionmanager.js");
/***/ },
/***/ 32:
/***/ function(module, exports, require) {
eval("var sjcl = require(10);\r\n\r\nvar UInt256 = require(23).UInt256;\r\n\r\nvar KeyPair = function ()\r\n{\r\n this._curve = sjcl.ecc.curves['c256'];\r\n this._secret = null;\r\n this._pubkey = null;\r\n};\r\n\r\nKeyPair.from_bn_secret = function (j)\r\n{\r\n if (j instanceof this) {\r\n return j.clone();\r\n } else {\r\n return (new this()).parse_bn_secret(j);\r\n }\r\n};\r\n\r\nKeyPair.prototype.parse_bn_secret = function (j)\r\n{\r\n this._secret = new sjcl.ecc.ecdsa.secretKey(sjcl.ecc.curves['c256'], j);\r\n return this;\r\n};\r\n\r\n/**\r\n * Returns public key as sjcl public key.\r\n *\r\n * @private\r\n */\r\nKeyPair.prototype._pub = function ()\r\n{\r\n var curve = this._curve;\r\n\r\n if (!this._pubkey && this._secret) {\r\n var exponent = this._secret._exponent;\r\n this._pubkey = new sjcl.ecc.ecdsa.publicKey(curve, curve.G.mult(exponent));\r\n }\r\n\r\n return this._pubkey;\r\n};\r\n\r\n/**\r\n * Returns public key as hex.\r\n *\r\n * Key will be returned as a compressed pubkey - 33 bytes converted to hex.\r\n */\r\nKeyPair.prototype.to_hex_pub = function ()\r\n{\r\n var pub = this._pub();\r\n if (!pub) return null;\r\n\r\n var point = pub._point, y_even = point.y.mod(2).equals(0);\r\n return sjcl.codec.hex.fromBits(sjcl.bitArray.concat(\r\n [sjcl.bitArray.partial(8, y_even ? 0x02 : 0x03)],\r\n point.x.toBits(this._curve.r.bitLength())\r\n )).toUpperCase();\r\n};\r\n\r\nKeyPair.prototype.sign = function (hash)\r\n{\r\n hash = UInt256.from_json(hash);\r\n return this._secret.signDER(hash.to_bits(), 0);\r\n};\r\n\r\nexports.KeyPair = KeyPair;\r\n\n\n// WEBPACK FOOTER\n// module.id = 32\n// module.readableIdentifier = ./src/js/ripple/keypair.js\n//@ sourceURL=webpack-module:///./src/js/ripple/keypair.js");
/***/ },
/***/ 33:
/***/ function(module, exports, require) {
eval("\r\nvar sjcl = require(10);\r\nvar utils = require(9);\r\nvar config = require(12);\r\nvar jsbn = require(20);\r\nvar extend = require(29);\r\n\r\nvar BigInteger = jsbn.BigInteger;\r\nvar nbi = jsbn.nbi;\r\n\r\nvar UInt = require(30).UInt,\r\n Base = require(4).Base;\r\n\r\n//\r\n// UInt128 support\r\n//\r\n\r\nvar UInt128 = extend(function () {\r\n // Internal form: NaN or BigInteger\r\n this._value = NaN;\r\n}, UInt);\r\n\r\nUInt128.width = 16;\r\nUInt128.prototype = extend({}, UInt.prototype);\r\nUInt128.prototype.constructor = UInt128;\r\n\r\nvar HEX_ZERO = UInt128.HEX_ZERO = \"00000000000000000000000000000000\";\r\nvar HEX_ONE = UInt128.HEX_ONE = \"00000000000000000000000000000000\";\r\nvar STR_ZERO = UInt128.STR_ZERO = utils.hexToString(HEX_ZERO);\r\nvar STR_ONE = UInt128.STR_ONE = utils.hexToString(HEX_ONE);\r\n\r\nexports.UInt128 = UInt128;\r\n\n\n// WEBPACK FOOTER\n// module.id = 33\n// module.readableIdentifier = ./src/js/ripple/uint128.js\n//@ sourceURL=webpack-module:///./src/js/ripple/uint128.js");
/***/ },
/***/ 34:
/***/ function(module, exports, require) {
eval("exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) {\n var e, m,\n eLen = nBytes * 8 - mLen - 1,\n eMax = (1 << eLen) - 1,\n eBias = eMax >> 1,\n nBits = -7,\n i = isBE ? 0 : (nBytes - 1),\n d = isBE ? 1 : -1,\n s = buffer[offset + i];\n\n i += d;\n\n e = s & ((1 << (-nBits)) - 1);\n s >>= (-nBits);\n nBits += eLen;\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);\n\n m = e & ((1 << (-nBits)) - 1);\n e >>= (-nBits);\n nBits += mLen;\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);\n\n if (e === 0) {\n e = 1 - eBias;\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity);\n } else {\n m = m + Math.pow(2, mLen);\n e = e - eBias;\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen);\n};\n\nexports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) {\n var e, m, c,\n eLen = nBytes * 8 - mLen - 1,\n eMax = (1 << eLen) - 1,\n eBias = eMax >> 1,\n rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),\n i = isBE ? (nBytes - 1) : 0,\n d = isBE ? -1 : 1,\n s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;\n\n value = Math.abs(value);\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0;\n e = eMax;\n } else {\n e = Math.floor(Math.log(value) / Math.LN2);\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--;\n c *= 2;\n }\n if (e + eBias >= 1) {\n value += rt / c;\n } else {\n value += rt * Math.pow(2, 1 - eBias);\n }\n if (value * c >= 2) {\n e++;\n c /= 2;\n }\n\n if (e + eBias >= eMax) {\n m = 0;\n e = eMax;\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen);\n e = e + eBias;\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);\n e = 0;\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);\n\n e = (e << mLen) | m;\n eLen += mLen;\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);\n\n buffer[offset + i - d] |= s * 128;\n};\n\n\n// WEBPACK FOOTER\n// module.id = 34\n// module.readableIdentifier = (webpack)/~/node-libs-browser/~/buffer-browserify/buffer_ieee754.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/~/buffer-browserify/buffer_ieee754.js");
/***/ },
/***/ 35:
/***/ function(module, exports, require) {
eval("module.exports = typeof Array.isArray === 'function'\n ? Array.isArray\n : function (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]'\n }\n;\n\n/*\n\nalternative\n\nfunction isArray(ar) {\n return ar instanceof Array ||\n Array.isArray(ar) ||\n (ar && ar !== Object.prototype && isArray(ar.__proto__));\n}\n\n*/\n\n// WEBPACK FOOTER\n// module.id = 35\n// module.readableIdentifier = (webpack)/~/node-libs-browser/util/isArray.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/util/isArray.js");
/***/ },
/***/ 36:
/***/ function(module, exports, require) {
eval("module.exports = Object.keys || function objectKeys(object) {\n\tif (object !== Object(object)) throw new TypeError('Invalid object');\n\tvar result = [];\n\tfor (var name in object) {\n\t\tif (Object.prototype.hasOwnProperty.call(object, name)) {\n\t\t\tresult.push(name);\n\t\t}\n\t}\n\treturn result;\n};\n\n\n// WEBPACK FOOTER\n// module.id = 36\n// module.readableIdentifier = (webpack)/~/node-libs-browser/util/objectKeys.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/util/objectKeys.js");
/***/ },
/***/ 37:
/***/ function(module, exports, require) {
eval("module.exports = Object.getOwnPropertyNames || function (obj) {\n var res = [];\n for (var key in obj) {\n if (Object.hasOwnProperty.call(obj, key)) res.push(key);\n }\n return res;\n};\n\n// WEBPACK FOOTER\n// module.id = 37\n// module.readableIdentifier = (webpack)/~/node-libs-browser/util/objectGetOwnPropertyNames.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/util/objectGetOwnPropertyNames.js");
/***/ },
/***/ 38:
/***/ function(module, exports, require) {
eval("module.exports = Object.create || function (prototype, properties) {\n // from es5-shim\n var object;\n if (prototype === null) {\n object = { '__proto__' : null };\n }\n else {\n if (typeof prototype !== 'object') {\n throw new TypeError(\n 'typeof prototype[' + (typeof prototype) + '] != \\'object\\''\n );\n }\n var Type = function () {};\n Type.prototype = prototype;\n object = new Type();\n object.__proto__ = prototype;\n }\n if (typeof properties !== 'undefined' && Object.defineProperties) {\n Object.defineProperties(object, properties);\n }\n return object;\n};\n\n// WEBPACK FOOTER\n// module.id = 38\n// module.readableIdentifier = (webpack)/~/node-libs-browser/util/objectCreate.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/util/objectCreate.js");
/***/ },
/***/ 39:
/***/ function(module, exports, require) {
eval("module.exports = function isRegExp(re) {\n return re instanceof RegExp ||\n (typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]');\n}\n\n// WEBPACK FOOTER\n// module.id = 39\n// module.readableIdentifier = (webpack)/~/node-libs-browser/util/isRegExp.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/util/isRegExp.js");
/***/ },
/***/ 40:
/***/ function(module, exports, require) {
eval("module.exports = function indexOf (xs, x) {\n if (xs.indexOf) return xs.indexOf(x);\n for (var i = 0; i < xs.length; i++) {\n if (x === xs[i]) return i;\n }\n return -1;\n}\n\n\n// WEBPACK FOOTER\n// module.id = 40\n// module.readableIdentifier = (webpack)/~/node-libs-browser/util/indexOf.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/util/indexOf.js");
/***/ },
/***/ 41:
/***/ function(module, exports, require) {
eval("// UTILITY\nvar util = require(28);\nvar pSlice = Array.prototype.slice;\n\nvar objectKeys = require(36);\nvar isRegExp = require(39);\n\n// 1. The assert module provides functions that throw\n// AssertionError's when particular conditions are not met. The\n// assert module must conform to the following interface.\n\nvar assert = module.exports = ok;\n\n// 2. The AssertionError is defined in assert.\n// new assert.AssertionError({ message: message,\n// actual: actual,\n// expected: expected })\n\nassert.AssertionError = function AssertionError(options) {\n this.name = 'AssertionError';\n this.message = options.message;\n this.actual = options.actual;\n this.expected = options.expected;\n this.operator = options.operator;\n var stackStartFunction = options.stackStartFunction || fail;\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, stackStartFunction);\n }\n};\nutil.inherits(assert.AssertionError, Error);\n\nfunction replacer(key, value) {\n if (value === undefined) {\n return '' + value;\n }\n if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {\n return value.toString();\n }\n if (typeof value === 'function' || value instanceof RegExp) {\n return value.toString();\n }\n return value;\n}\n\nfunction truncate(s, n) {\n if (typeof s == 'string') {\n return s.length < n ? s : s.slice(0, n);\n } else {\n return s;\n }\n}\n\nassert.AssertionError.prototype.toString = function() {\n if (this.message) {\n return [this.name + ':', this.message].join(' ');\n } else {\n return [\n this.name + ':',\n truncate(JSON.stringify(this.actual, replacer), 128),\n this.operator,\n truncate(JSON.stringify(this.expected, replacer), 128)\n ].join(' ');\n }\n};\n\n// assert.AssertionError instanceof Error\n\nassert.AssertionError.__proto__ = Error.prototype;\n\n// At present only the three keys mentioned above are used and\n// understood by the spec. Implementations or sub modules can pass\n// other keys to the AssertionError's constructor - they will be\n// ignored.\n\n// 3. All of the following functions must throw an AssertionError\n// when a corresponding condition is not met, with a message that\n// may be undefined if not provided. All assertion methods provide\n// both the actual and expected values to the assertion error for\n// display purposes.\n\nfunction fail(actual, expected, message, operator, stackStartFunction) {\n throw new assert.AssertionError({\n message: message,\n actual: actual,\n expected: expected,\n operator: operator,\n stackStartFunction: stackStartFunction\n });\n}\n\n// EXTENSION! allows for well behaved errors defined elsewhere.\nassert.fail = fail;\n\n// 4. Pure assertion tests whether a value is truthy, as determined\n// by !!guard.\n// assert.ok(guard, message_opt);\n// This statement is equivalent to assert.equal(true, !!guard,\n// message_opt);. To test strictly for the value true, use\n// assert.strictEqual(true, guard, message_opt);.\n\nfunction ok(value, message) {\n if (!!!value) fail(value, true, message, '==', assert.ok);\n}\nassert.ok = ok;\n\n// 5. The equality assertion tests shallow, coercive equality with\n// ==.\n// assert.equal(actual, expected, message_opt);\n\nassert.equal = function equal(actual, expected, message) {\n if (actual != expected) fail(actual, expected, message, '==', assert.equal);\n};\n\n// 6. The non-equality assertion tests for whether two objects are not equal\n// with != assert.notEqual(actual, expected, message_opt);\n\nassert.notEqual = function notEqual(actual, expected, message) {\n if (actual == expected) {\n fail(actual, expected, message, '!=', assert.notEqual);\n }\n};\n\n// 7. The equivalence assertion tests a deep equality relation.\n// assert.deepEqual(actual, expected, message_opt);\n\nassert.deepEqual = function deepEqual(actual, expected, message) {\n if (!_deepEqual(actual, expected)) {\n fail(actual, expected, message, 'deepEqual', assert.deepEqual);\n }\n};\n\nfunction _deepEqual(actual, expected) {\n // 7.1. All identical values are equivalent, as determined by ===.\n if (actual === expected) {\n return true;\n\n } else if (require(24).Buffer.isBuffer(actual) && require(24).Buffer.isBuffer(expected)) {\n if (actual.length != expected.length) return false;\n\n for (var i = 0; i < actual.length; i++) {\n if (actual[i] !== expected[i]) return false;\n }\n\n return true;\n\n // 7.2. If the expected value is a Date object, the actual value is\n // equivalent if it is also a Date object that refers to the same time.\n } else if (actual instanceof Date && expected instanceof Date) {\n return actual.getTime() === expected.getTime();\n\n // 7.3 If the expected value is a RegExp object, the actual value is\n // equivalent if it is also a RegExp object with the same source and\n // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).\n } else if (isRegExp(actual) && isRegExp(expected)) {\n return actual.source === expected.source &&\n actual.global === expected.global &&\n actual.multiline === expected.multiline &&\n actual.lastIndex === expected.lastIndex &&\n actual.ignoreCase === expected.ignoreCase;\n\n // 7.4. Other pairs that do not both pass typeof value == 'object',\n // equivalence is determined by ==.\n } else if (typeof actual != 'object' && typeof expected != 'object') {\n return actual == expected;\n\n // 7.5 For all other Object pairs, including Array objects, equivalence is\n // determined by having the same number of owned properties (as verified\n // with Object.prototype.hasOwnProperty.call), the same set of keys\n // (although not necessarily the same order), equivalent values for every\n // corresponding key, and an identical 'prototype' property. Note: this\n // accounts for both named and indexed properties on Arrays.\n } else {\n return objEquiv(actual, expected);\n }\n}\n\nfunction isUndefinedOrNull(value) {\n return value === null || value === undefined;\n}\n\nfunction isArguments(object) {\n return Object.prototype.toString.call(object) == '[object Arguments]';\n}\n\nfunction objEquiv(a, b) {\n if (isUndefinedOrNull(a) || isUndefinedOrNull(b))\n return false;\n // an identical 'prototype' property.\n if (a.prototype !== b.prototype) return false;\n //~~~I've managed to break Object.keys through screwy arguments passing.\n // Converting to array solves the problem.\n if (isArguments(a)) {\n if (!isArguments(b)) {\n return false;\n }\n a = pSlice.call(a);\n b = pSlice.call(b);\n return _deepEqual(a, b);\n }\n try {\n var ka = objectKeys(a),\n kb = objectKeys(b),\n key, i;\n } catch (e) {//happens when one is a string literal and the other isn't\n return false;\n }\n // having the same number of owned properties (keys incorporates\n // hasOwnProperty)\n if (ka.length != kb.length)\n return false;\n //the same set of keys (although not necessarily the same order),\n ka.sort();\n kb.sort();\n //~~~cheap key test\n for (i = ka.length - 1; i >= 0; i--) {\n if (ka[i] != kb[i])\n return false;\n }\n //equivalent values for every corresponding key, and\n //~~~possibly expensive deep test\n for (i = ka.length - 1; i >= 0; i--) {\n key = ka[i];\n if (!_deepEqual(a[key], b[key])) return false;\n }\n return true;\n}\n\n// 8. The non-equivalence assertion tests for any deep inequality.\n// assert.notDeepEqual(actual, expected, message_opt);\n\nassert.notDeepEqual = function notDeepEqual(actual, expected, message) {\n if (_deepEqual(actual, expected)) {\n fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);\n }\n};\n\n// 9. The strict equality assertion tests strict equality, as determined by ===.\n// assert.strictEqual(actual, expected, message_opt);\n\nassert.strictEqual = function strictEqual(actual, expected, message) {\n if (actual !== expected) {\n fail(actual, expected, message, '===', assert.strictEqual);\n }\n};\n\n// 10. The strict non-equality assertion tests for strict inequality, as\n// determined by !==. assert.notStrictEqual(actual, expected, message_opt);\n\nassert.notStrictEqual = function notStrictEqual(actual, expected, message) {\n if (actual === expected) {\n fail(actual, expected, message, '!==', assert.notStrictEqual);\n }\n};\n\nfunction expectedException(actual, expected) {\n if (!actual || !expected) {\n return false;\n }\n\n if (isRegExp(expected)) {\n return expected.test(actual);\n } else if (actual instanceof expected) {\n return true;\n } else if (expected.call({}, actual) === true) {\n return true;\n }\n\n return false;\n}\n\nfunction _throws(shouldThrow, block, expected, message) {\n var actual;\n\n if (typeof expected === 'string') {\n message = expected;\n expected = null;\n }\n\n try {\n block();\n } catch (e) {\n actual = e;\n }\n\n message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +\n (message ? ' ' + message : '.');\n\n if (shouldThrow && !actual) {\n fail(actual, expected, 'Missing expected exception' + message);\n }\n\n if (!shouldThrow && expectedException(actual, expected)) {\n fail(actual, expected, 'Got unwanted exception' + message);\n }\n\n if ((shouldThrow && actual && expected &&\n !expectedException(actual, expected)) || (!shouldThrow && actual)) {\n throw actual;\n }\n}\n\n// 11. Expected to throw an error:\n// assert.throws(block, Error_opt, message_opt);\n\nassert.throws = function(block, /*optional*/error, /*optional*/message) {\n _throws.apply(this, [true].concat(pSlice.call(arguments)));\n};\n\n// EXTENSION! This is annoying to write outside this module.\nassert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {\n _throws.apply(this, [false].concat(pSlice.call(arguments)));\n};\n\nassert.ifError = function(err) { if (err) {throw err;}};\n\n\n// WEBPACK FOOTER\n// module.id = 41\n// module.readableIdentifier = (webpack)/~/node-libs-browser/lib/assert.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/lib/assert.js");
/***/ },
/***/ 42:
/***/ function(module, exports, require) {
eval("\r\nfunction TransactionQueue() {\r\n var self = this;\r\n\r\n this._queue = [ ];\r\n\r\n Object.defineProperty(this, '_length', {\r\n get: function() { return self._queue.length }\r\n });\r\n}\r\n\r\nTransactionQueue.prototype.length = function() {\r\n return this._queue.length;\r\n};\r\n\r\nTransactionQueue.prototype.indexOf = function(prop, val) {\r\n var index = -1;\r\n for (var i=0, tx; tx=this._queue[i]; i++) {\r\n if (tx[prop] === val) {\r\n index = i;\r\n break;\r\n }\r\n }\r\n return index;\r\n};\r\n\r\nTransactionQueue.prototype.hasHash = function(hash) {\r\n return this.indexOf('hash', hash) !== -1;\r\n};\r\n\r\nTransactionQueue.prototype.get = function(prop, val) {\r\n var index = this.indexOf(prop, val);\r\n return index > -1 ? this._queue[index] : false;\r\n};\r\n\r\nTransactionQueue.prototype.removeSequence = function(sequence) {\r\n var result = [ ];\r\n for (var i=0, tx; tx=this._queue[i]; i++) {\r\n if (!tx.tx_json) continue;\r\n if (tx.tx_json.Sequence !== sequence) result.push(tx);\r\n }\r\n this._queue = result;\r\n};\r\n\r\nTransactionQueue.prototype.removeHash = function(hash) {\r\n var result = [ ];\r\n for (var i=0, tx; tx=this._queue[i]; i++) {\r\n if (!tx.tx_json) continue;\r\n if (tx.hash !== hash) result.push(tx);\r\n }\r\n this._queue = result;\r\n};\r\n\r\nTransactionQueue.prototype.forEach = function() {\r\n Array.prototype.forEach.apply(this._queue, arguments);\r\n};\r\n\r\nTransactionQueue.prototype.push = function() {\r\n Array.prototype.push.apply(this._queue, arguments);\r\n};\r\n\r\nexports.TransactionQueue = TransactionQueue;\r\n\n\n// WEBPACK FOOTER\n// module.id = 42\n// module.readableIdentifier = ./src/js/ripple/transactionqueue.js\n//@ sourceURL=webpack-module:///./src/js/ripple/transactionqueue.js");
/***/ },
/***/ 43:
/***/ function(module, exports, require) {
eval("(function (exports) {\n\t'use strict';\n\n\tvar lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n\tfunction b64ToByteArray(b64) {\n\t\tvar i, j, l, tmp, placeHolders, arr;\n\t\n\t\tif (b64.length % 4 > 0) {\n\t\t\tthrow 'Invalid string. Length must be a multiple of 4';\n\t\t}\n\n\t\t// the number of equal signs (place holders)\n\t\t// if there are two placeholders, than the two characters before it\n\t\t// represent one byte\n\t\t// if there is only one, then the three characters before it represent 2 bytes\n\t\t// this is just a cheap hack to not do indexOf twice\n\t\tplaceHolders = b64.indexOf('=');\n\t\tplaceHolders = placeHolders > 0 ? b64.length - placeHolders : 0;\n\n\t\t// base64 is 4/3 + up to two characters of the original data\n\t\tarr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);\n\n\t\t// if there are placeholders, only get up to the last complete 4 chars\n\t\tl = placeHolders > 0 ? b64.length - 4 : b64.length;\n\n\t\tfor (i = 0, j = 0; i < l; i += 4, j += 3) {\n\t\t\ttmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]);\n\t\t\tarr.push((tmp & 0xFF0000) >> 16);\n\t\t\tarr.push((tmp & 0xFF00) >> 8);\n\t\t\tarr.push(tmp & 0xFF);\n\t\t}\n\n\t\tif (placeHolders === 2) {\n\t\t\ttmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4);\n\t\t\tarr.push(tmp & 0xFF);\n\t\t} else if (placeHolders === 1) {\n\t\t\ttmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2);\n\t\t\tarr.push((tmp >> 8) & 0xFF);\n\t\t\tarr.push(tmp & 0xFF);\n\t\t}\n\n\t\treturn arr;\n\t}\n\n\tfunction uint8ToBase64(uint8) {\n\t\tvar i,\n\t\t\textraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes\n\t\t\toutput = \"\",\n\t\t\ttemp, length;\n\n\t\tfunction tripletToBase64 (num) {\n\t\t\treturn lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];\n\t\t};\n\n\t\t// go through the array every three bytes, we'll deal with trailing stuff later\n\t\tfor (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {\n\t\t\ttemp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);\n\t\t\toutput += tripletToBase64(temp);\n\t\t}\n\n\t\t// pad the end with zeros, but make sure to not forget the extra bytes\n\t\tswitch (extraBytes) {\n\t\t\tcase 1:\n\t\t\t\ttemp = uint8[uint8.length - 1];\n\t\t\t\toutput += lookup[temp >> 2];\n\t\t\t\toutput += lookup[(temp << 4) & 0x3F];\n\t\t\t\toutput += '==';\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\ttemp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);\n\t\t\t\toutput += lookup[temp >> 10];\n\t\t\t\toutput += lookup[(temp >> 4) & 0x3F];\n\t\t\t\toutput += lookup[(temp << 2) & 0x3F];\n\t\t\t\toutput += '=';\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn output;\n\t}\n\n\tmodule.exports.toByteArray = b64ToByteArray;\n\tmodule.exports.fromByteArray = uint8ToBase64;\n}());\n\n\n// WEBPACK FOOTER\n// module.id = 43\n// module.readableIdentifier = (webpack)/~/node-libs-browser/~/buffer-browserify/~/base64-js/lib/b64.js\n//@ sourceURL=webpack-module:///(webpack)/~/node-libs-browser/~/buffer-browserify/~/base64-js/lib/b64.js");
/***/ }
/******/ })