-
Notifications
You must be signed in to change notification settings - Fork 500
/
remote.js
1585 lines (1246 loc) · 43.8 KB
/
remote.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Remote access to a server.
// - We never send binary data.
// - We use the W3C interface for node and browser compatibility:
// http://www.w3.org/TR/websockets/#the-websocket-interface
//
// This class is intended for both browser and node.js use.
//
// This class is designed to work via peer protocol via either the public or
// private websocket interfaces. The JavaScript class for the peer protocol
// has not yet been implemented. However, this class has been designed for it
// to be a very simple drop option.
//
// YYY Will later provide js/network.js which will transparently use multiple
// instances of this class for network access.
// npm
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Request = require('./request').Request;
var Server = require('./server').Server;
var Amount = require('./amount').Amount;
var Currency = require('./currency').Currency;
var UInt160 = require('./uint160').UInt160;
var Transaction = require('./transaction').Transaction;
var Account = require('./account').Account;
var Meta = require('./meta').Meta;
var OrderBook = require('./orderbook').OrderBook;
var PathFind = require('./pathfind').PathFind;
var RippleError = require('./rippleerror').RippleError;
var utils = require('./utils');
var sjcl = require('./utils').sjcl;
var config = require('./config');
/**
Interface to manage the connection to a Ripple server.
This implementation uses WebSockets.
Keys for opts:
trace
max_listeners : Set maxListeners for remote; prevents EventEmitter warnings
connection_offset : Connect to remote servers on supplied interval (in seconds)
trusted : truthy, if remote is trusted
max_fee : Maximum acceptable transaction fee
fee_cushion : Extra fee multiplier to account for async fee changes.
servers : Array of server objects with the following form
{
host: <string>
, port: <number>
, secure: <boolean>
}
Events:
'connect'
'connected' (DEPRECATED)
'disconnect'
'disconnected' (DEPRECATED)
'state':
- 'online' : Connected and subscribed.
- 'offline' : Not subscribed or not connected.
'subscribed' : This indicates stand-alone is available.
Server events:
'ledger_closed' : A good indicate of ready to serve.
'transaction' : Transactions we receive based on current subscriptions.
'transaction_all' : Listening triggers a subscribe to all transactions
globally in the network.
@param opts Connection options.
@param trace
*/
function Remote(opts, trace) {
EventEmitter.call(this);
var self = this;
this.trusted = Boolean(opts.trusted);
this.local_sequence = Boolean(opts.local_sequence); // Locally track sequence numbers
this.local_fee = (typeof opts.local_fee === 'undefined') ? true : Boolean(opts.local_fee); // Locally set fees
this.local_signing = (typeof opts.local_signing === 'undefined') ? true : Boolean(opts.local_signing);
this.fee_cushion = (typeof opts.fee_cushion === 'undefined') ? 1.2 : Number(opts.fee_cushion);
this.max_fee = (typeof opts.max_fee === 'undefined') ? Infinity : Number(opts.max_fee);
this.id = 0;
this.trace = Boolean(opts.trace);
this._server_fatal = false; // True, if we know server exited.
this._ledger_current_index = void(0);
this._ledger_hash = void(0);
this._ledger_time = void(0);
this._stand_alone = void(0);
this._testnet = void(0);
this._transaction_subs = 0;
this.online_target = false;
this._online_state = 'closed'; // 'open', 'closed', 'connecting', 'closing'
this.state = 'offline'; // 'online', 'offline'
this.retry_timer = void(0);
this.retry = void(0);
this._connection_count = 0;
this._connected = false;
this._connection_offset = 1000 * (typeof opts.connection_offset === 'number' ? opts.connection_offset : 5)
this._submission_timeout = 1000 * (typeof opts.submission_timeout === 'number' ? opts.submission_timeout : 10)
this._received_tx = { };
this._cur_path_find = null;
// Local signing implies local fees and sequences
if (this.local_signing) {
this.local_sequence = true;
this.local_fee = true;
}
this._servers = [ ];
this._primary_server = void(0);
// Cache information for accounts.
// DEPRECATED, will be removed
this.accounts = {
// Consider sequence numbers stable if you know you're not generating bad transactions.
// Otherwise, clear it to have it automatically refreshed from the network.
// account : { seq : __ }
};
// Account objects by AccountId.
this._accounts = { };
// OrderBook objects
this._books = { };
// Secrets that we know about.
this.secrets = {
// Secrets can be set by calling set_secret(account, secret).
// account : secret
};
// Cache for various ledgers.
// XXX Clear when ledger advances.
this.ledgers = {
current : {
account_root : { }
}
};
// Fallback for previous API
if (!opts.hasOwnProperty('servers')) {
opts.servers = [
{
host: opts.websocket_ip,
port: opts.websocket_port,
secure: opts.websocket_ssl,
trusted: opts.trusted
}
];
}
opts.servers.forEach(function(server) {
var pool = Number(server.pool) || 1;
while (pool--) { self.addServer(server); };
});
// This is used to remove Node EventEmitter warnings
var maxListeners = opts.maxListeners || opts.max_listeners || 0;
this._servers.concat(this).forEach(function(emitter) {
emitter.setMaxListeners(maxListeners);
});
function listenerAdded(type, listener) {
if (type === 'transaction_all') {
if (!self._transaction_subs && self._connected) {
self.request_subscribe('transactions').request();
}
self._transaction_subs += 1;
}
};
this.on('newListener', listenerAdded);
function listenerRemoved(type, listener) {
if (type === 'transaction_all') {
self._transaction_subs -= 1;
if (!self._transaction_subs && self._connected) {
self.request_unsubscribe('transactions').request();
}
}
};
this.on('removeListener', listenerRemoved);
function addPendingAccounts() {
opts.storage.loadAccounts(function(err, accounts) {
if (!err && Array.isArray(accounts)) {
accounts.forEach(self.account.bind(self));
}
});
};
if (opts.storage) {
this.storage = opts.storage;
this.once('connect', addPendingAccounts);
}
};
util.inherits(Remote, EventEmitter);
// Flags for ledger entries. In support of account_root().
Remote.flags = {
// Account Root
account_root : {
PasswordSpent: 0x00010000, // True, if password set fee is spent.
RequireDestTag: 0x00020000, // True, to require a DestinationTag for payments.
RequireAuth: 0x00040000, // True, to require a authorization to hold IOUs.
DisallowXRP: 0x00080000, // True, to disallow sending XRP.
DisableMaster: 0x00100000 // True, force regular key.
},
// Offer
offer: {
Passive: 0x00010000,
Sell: 0x00020000 // True, offer was placed as a sell.
},
// Ripple State
state: {
LowReserve: 0x00010000, // True, if entry counts toward reserve.
HighReserve: 0x00020000,
LowAuth: 0x00040000,
HighAuth: 0x00080000,
LowNoRipple: 0x00100000,
HighNoRipple: 0x00200000
}
};
Remote.from_config = function(obj, trace) {
var serverConfig = typeof obj === 'string' ? config.servers[obj] : obj;
var remote = new Remote(serverConfig, trace);
function initializeAccount(account) {
var accountInfo = this.accounts[account];
if (typeof accountInfo === 'object') {
if (accountInfo.secret) {
// Index by nickname
remote.setSecret(account, accountInfo.secret);
// Index by account ID
remote.setSecret(accountInfo.account, accountInfo.secret);
}
}
};
Object.keys(config.accounts || {}).forEach(initializeAccount, config);
return remote;
};
Remote.prototype.addServer = function(opts) {
var self = this;
var server = new Server(this, {
host: opts.host || opts.websocket_ip,
port: opts.port || opts.websocket_port,
secure: opts.secure || opts.websocket_ssl
});
function serverMessage(data) {
self._handleMessage(data, server);
};
server.on('message', serverMessage);
function serverConnect() {
if (opts.primary || !self._primary_server) {
self._setPrimaryServer(server);
}
switch (++self._connection_count) {
case 1:
self._setState('online');
break;
case self._servers.length:
self.emit('ready');
break;
}
};
server.on('connect', serverConnect);
function serverDisconnect() {
self._connection_count--;
if (self._connection_count === 0) {
self._setState('offline');
}
};
server.on('disconnect', serverDisconnect);
this._servers.push(server);
return this;
};
// Inform remote that the remote server is not comming back.
Remote.prototype.serverFatal = function() {
this._server_fatal = true;
};
// Set the emitted state: 'online' or 'offline'
Remote.prototype._setState = function(state) {
if (this.state !== state) {
this._trace('remote: set_state:', state);
this.state = state;
this.emit('state', state);
switch (state) {
case 'online':
this._online_state = 'open';
this._connected = true;
this.emit('connect');
this.emit('connected');
break;
case 'offline':
this._online_state = 'closed';
this._connected = false;
this.emit('disconnect');
this.emit('disconnected');
break;
}
}
};
Remote.prototype.setTrace = function(trace) {
this.trace = trace === void(0) || trace;
return this;
};
// Store a secret - allows the Remote to automatically fill out auth information.
Remote.prototype.setSecret = function(account, secret) {
this.secrets[account] = secret;
};
Remote.prototype._trace = function() {
if (this.trace) {
utils.logObject.apply(utils, arguments);
}
};
/**
* Connect to the Ripple network.
*
* param {Function} callback
*/
Remote.prototype.connect = function(online) {
if (!this._servers.length) {
throw new Error('No servers available.');
}
switch (typeof online) {
case 'undefined':
break;
case 'function':
this.once('connect', online);
break;
default:
// Downwards compatibility
if (!Boolean(online)) {
return this.disconnect();
}
}
var self = this;
;(function nextServer(i) {
var server = self._servers[i];
server.connect();
server._sid = ++i;
if (i < self._servers.length) {
setTimeout(function() {
nextServer(i);
}, self._connection_offset);
}
})(0);
return this;
};
/**
* Disconnect from the Ripple network.
*/
Remote.prototype.disconnect = function(callback) {
if (!this._servers.length) {
throw new Error('No servers available, not disconnecting');
}
if (typeof callback === 'function') {
this.once('disconnect', callback);
}
this._servers.forEach(function(server) {
server.disconnect();
});
this._set_state('offline');
return this;
};
// It is possible for messages to be dispatched after the connection is closed.
Remote.prototype._handleMessage = function(message, server) {
var self = this;
try { message = JSON.parse(message); } catch(e) { }
if (!Remote.isValidMessage(message)) {
// Unexpected response from remote.
this.emit('error', new RippleError('remoteUnexpected', 'Unexpected response from remote'));
return;
}
switch (message.type) {
case 'response':
// Handled by the server that sent the request
break;
case 'ledgerClosed':
// XXX If not trusted, need to verify we consider ledger closed.
// XXX Also need to consider a slow server or out of order response.
// XXX Be more defensive fields could be missing or of wrong type.
// YYY Might want to do some cache management.
if (!Remote.isValidLedgerData(message)) return;
if (message.ledger_index >= this._ledger_current_index) {
this._ledger_time = message.ledger_time;
this._ledger_hash = message.ledger_hash;
this._ledger_current_index = message.ledger_index + 1;
this.emit('ledger_closed', message, server);
}
break;
case 'serverStatus':
self.emit('server_status', message);
break;
case 'transaction':
// To get these events, just subscribe to them. A subscribes and
// unsubscribes will be added as needed.
// XXX If not trusted, need proof.
// De-duplicate transactions that are immediately following each other
var hash = message.transaction.hash;
if (this._received_tx.hasOwnProperty(hash)) {
break;
} else if (message.validated) {
this._received_tx[hash] = true;
}
this._trace('remote: tx:', message);
if (message.meta) {
// Process metadata
message.mmeta = new Meta(message.meta);
// Pass the event on to any related Account objects
message.mmeta.getAffectedAccounts().forEach(function(account) {
account = self._accounts[account];
if (account) account.notify(message);
});
// Pass the event on to any related OrderBooks
message.mmeta.getAffectedBooks().forEach(function(book) {
book = self._books[book];
if (book) book.notify(message);
});
} else {
[ 'Account', 'Destination' ].forEach(function(prop) {
var account = message.transaction[prop];
if (account && (account = self.account(account))) {
account.notify(message);
}
});
}
this.emit('transaction', message);
this.emit('transaction_all', message);
break;
case 'path_find':
// Pass the event to the currently open PathFind object
if (this._cur_path_find) {
this._cur_path_find.notify_update(message);
}
this.emit('path_find_all', message);
break;
// All other messages
default:
this._trace('remote: ' + message.type + ': ', message);
this.emit('net_' + message.type, message);
break;
}
};
Remote.isValidMessage = function(message) {
return (typeof message === 'object')
&& (typeof message.type === 'string');
};
Remote.isValidLedgerData = function(ledger) {
return (typeof ledger === 'object')
&& (typeof ledger.fee_base === 'number')
&& (typeof ledger.fee_ref === 'number')
&& (typeof ledger.fee_base === 'number')
&& (typeof ledger.ledger_hash === 'string')
&& (typeof ledger.ledger_index === 'number')
&& (typeof ledger.ledger_time === 'number')
&& (typeof ledger.reserve_base === 'number')
&& (typeof ledger.reserve_inc === 'number')
&& (typeof ledger.txn_count === 'number');
};
Remote.isLoadStatus = function(message) {
return (typeof message.load_base === 'number')
&& (typeof message.load_factor === 'number');
};
Remote.prototype.ledgerHash = function() {
return this._ledger_hash;
};
Remote.prototype._setPrimaryServer = function(server) {
if (this._primary_server) {
this._primary_server._primary = false;
}
this._primary_server = server;
this._primary_server._primary = true;
};
Remote.prototype._serverIsAvailable = function(server) {
return server && server._connected;
};
Remote.prototype._nextServer = function() {
var result = null;
for (var i=0, l=this._servers.length; i<l; i++) {
var server = this._servers[i];
if (this._serverIsAvailable(server)) {
result = server;
break;
}
}
return result;
};
Remote.prototype._getServer = function() {
var server;
if (this._serverIsAvailable(this._primary_server)) {
server = this._primary_server;
} else {
server = this._nextServer();
if (server) {
this._setPrimaryServer(server);
}
}
return server;
};
// Send a request.
// <-> request: what to send, consumed.
Remote.prototype.request = function(request) {
if (typeof request === 'string') {
if (!/^request_/.test(request)) request = 'request_' + request;
if (typeof this[request] === 'function') {
var args = Array.prototype.slice.call(arguments, 1);
return this[request].apply(this, args);
} else {
throw new Error('Command does not exist: ' + request);
}
} else if (!(request instanceof Request)) {
throw new Error('Argument is not a Request');
}
if (!this._servers.length) {
request.emit('error', new Error('No servers available'));
} else if (!this._connected) {
this.once('connect', this.request.bind(this, request));
} else if (request.server === null) {
request.emit('error', new Error('Server does not exist'));
} else {
var server = request.server || this._getServer();
if (server) {
server.request(request);
} else {
request.emit('error', new Error('No servers available'));
}
}
};
Remote.prototype.requestServerInfo = function(callback) {
return new Request(this, 'server_info').callback(callback);
};
// XXX This is a bad command. Some variants don't scale.
// XXX Require the server to be trusted.
Remote.prototype.requestLedger = function(ledger, options, callback) {
//utils.assert(this.trusted);
var request = new Request(this, 'ledger');
if (ledger) {
// DEPRECATED: use .ledger_hash() or .ledger_index()
//console.log('request_ledger: ledger parameter is deprecated');
request.message.ledger = ledger;
}
var requestFields = [
'full',
'expand',
'transactions',
'accounts'
];
switch (typeof options) {
case 'object':
for (var key in options) {
if (~requestFields.indexOf(key)) {
request.message[key] = true;
}
}
break;
case 'function':
callback = options;
options = void(0);
break;
default:
//DEPRECATED
this._trace('request_ledger: full parameter is deprecated');
request.message.full = true;
break;
}
request.callback(callback);
return request;
};
// Only for unit testing.
Remote.prototype.requestLedgerHash = function(callback) {
//utils.assert(this.trusted); // If not trusted, need to check proof.
return new Request(this, 'ledger_closed').callback(callback);
};
// .ledger()
// .ledger_index()
Remote.prototype.requestLedgerHeader = function(callback) {
return new Request(this, 'ledger_header').callback(callback);
};
// Get the current proposed ledger entry. May be closed (and revised) at any time (even before returning).
// Only for unit testing.
Remote.prototype.requestLedgerCurrent = function(callback) {
return new Request(this, 'ledger_current').callback(callback);
};
// --> type : the type of ledger entry.
// .ledger()
// .ledger_index()
// .offer_id()
Remote.prototype.requestLedgerEntry = function(type, callback) {
//utils.assert(this.trusted); // If not trusted, need to check proof, maybe talk packet protocol.
var self = this;
var request = new Request(this, 'ledger_entry');
// Transparent caching. When .request() is invoked, look in the Remote object for the result.
// If not found, listen, cache result, and emit it.
//
// Transparent caching:
if (type === 'account_root') {
request.request_default = request.request;
request.request = function() { // Intercept default request.
var bDefault = true;
// .self = Remote
// this = Request
// console.log('request_ledger_entry: caught');
//if (self._ledger_hash) {
// A specific ledger is requested.
// XXX Add caching.
// else if (req.ledger_index)
// else if ('ripple_state' === request.type) // YYY Could be cached per ledger.
//}
if (!self._ledger_hash && type === 'account_root') {
var cache = self.ledgers.current.account_root;
if (!cache) {
cache = self.ledgers.current.account_root = {};
}
var node = self.ledgers.current.account_root[request.message.account_root];
if (node) {
// Emulate fetch of ledger entry.
// console.log('request_ledger_entry: emulating');
// YYY Missing lots of fields.
request.emit('success', { node: node });
bDefault = false;
} else { // Was not cached.
// XXX Only allow with trusted mode. Must sync response with advance.
switch (type) {
case 'account_root':
request.once('success', function(message) {
// Cache node.
// console.log('request_ledger_entry: caching');
self.ledgers.current.account_root[message.node.Account] = message.node;
});
break;
default:
// This type not cached.
// console.log('request_ledger_entry: non-cached type');
}
}
}
if (bDefault) {
// console.log('request_ledger_entry: invoking');
request.request_default();
}
};
}
request.callback(callback);
return request;
};
// .accounts(accounts, realtime)
Remote.prototype.requestSubscribe = function(streams, callback) {
var request = new Request(this, 'subscribe');
if (streams) {
request.message.streams = Array.isArray(streams) ? streams : [ streams ];
}
request.callback(callback);
return request;
};
// .accounts(accounts, realtime)
Remote.prototype.requestUnsubscribe = function(streams, callback) {
var request = new Request(this, 'unsubscribe');
if (streams) {
request.message.streams = Array.isArray(streams) ? streams : [ streams ];
}
request.callback(callback);
return request;
};
// .ledger_choose()
// .ledger_hash()
// .ledger_index()
Remote.prototype.requestTransaction =
Remote.prototype.requestTransactionEntry = function(hash, ledger_hash, callback) {
//utils.assert(this.trusted); // If not trusted, need to check proof, maybe talk packet protocol.
var request = new Request(this, 'transaction_entry');
request.txHash(hash);
switch (typeof ledger_hash) {
case 'string':
request.ledgerHash(ledger_hash);
break;
case 'number':
request.ledgerIndex(ledger_hash);
break;
case 'undefined':
case 'function':
request.ledgerIndex('validated');
callback = ledger_hash;
break;
default:
throw new Error('Invalid ledger_hash type');
}
request.callback(callback);
return request;
};
// DEPRECATED: use request_transaction_entry
Remote.prototype.requestTx = function(hash, callback) {
var request = new Request(this, 'tx');
request.message.transaction = hash;
request.callback(callback);
return request;
};
Remote.accountRequest = function(type, account, accountIndex, ledger, callback) {
if (typeof account === 'object') {
var options = account;
callback = account_index;
ledger = options.ledger;
accountIndex = options.account_index;
account = options.accountID || options.account;
}
var lastArg = arguments[arguments.length - 1];
if (typeof lastArg === 'function') {
callback = lastArg;
}
var request = new Request(this, type);
var account = UInt160.json_rewrite(account);
request.message.ident = account; //DEPRECATED;
request.message.account = account;
if (typeof accountIndex === 'number') {
request.message.index = accountIndex;
}
if (typeof ledger !== 'undefined') {
request.ledgerChoose(ledger);
}
request.callback(callback);
return request;
};
Remote.prototype.requestAccountInfo = function(accountID, callback) {
var args = Array.prototype.concat.apply(['account_info'], arguments);
return Remote.accountRequest.apply(this, args);
};
Remote.prototype.requestAccountCurrencies = function(accountID, callback) {
var args = Array.prototype.concat.apply(['account_currencies'], arguments);
return Remote.accountRequest.apply(this, args);
};
// --> account_index: sub_account index (optional)
// --> current: true, for the current ledger.
Remote.prototype.requestAccountLines = function(accountID, account_index, ledger, callback) {
// XXX Does this require the server to be trusted?
//utils.assert(this.trusted);
var args = Array.prototype.concat.apply(['account_lines'], arguments);
return Remote.accountRequest.apply(this, args);
};
// --> account_index: sub_account index (optional)
// --> current: true, for the current ledger.
Remote.prototype.requestAccountOffers = function(accountID, account_index, ledger, callback) {
var args = Array.prototype.concat.apply(['account_offers'], arguments);
return Remote.accountRequest.apply(this, args);
};
/*
account: account,
ledger_index_min: ledger_index, // optional, defaults to -1 if ledger_index_max is specified.
ledger_index_max: ledger_index, // optional, defaults to -1 if ledger_index_min is specified.
binary: boolean, // optional, defaults to false
count: boolean, // optional, defaults to false
descending: boolean, // optional, defaults to false
offset: integer, // optional, defaults to 0
limit: integer // optional
*/
Remote.prototype.requestAccountTx = function(options, callback) {
// XXX Does this require the server to be trusted?
//utils.assert(this.trusted);
var request = new Request(this, 'account_tx');
var requestFields = [
'account',
'ledger_index_min', //earliest
'ledger_index_max', //latest
'binary', //false
'count', //false
'descending', //false
'offset', //0
'limit',
//extended account_tx
'forward', //false
'marker'
];
for (var key in options) {
if (~requestFields.indexOf(key)) {
request.message[key] = options[key];
}
}
request.callback(callback);
return request;
};
/**
* Request the overall transaction history.
*
* Returns a list of transactions that happened recently on the network. The
* default number of transactions to be returned is 20.
*/
Remote.prototype.requestTxHistory = function(start, callback) {
// XXX Does this require the server to be trusted?
//utils.assert(this.trusted);
var request = new Request(this, 'tx_history');
request.message.start = start;
request.callback(callback);
return request;
};
Remote.prototype.requestBookOffers = function(gets, pays, taker, callback) {
if (gets.hasOwnProperty('pays')) {
var options = gets;
callback = pays;
taker = options.taker;
pays = options.pays;
gets = options.gets;
}
var lastArg = arguments[arguments.length - 1];
if (typeof lastArg === 'function') {
callback = lastArg;
}
var request = new Request(this, 'book_offers');
request.message.taker_gets = {
currency: Currency.json_rewrite(gets.currency)
};
if (request.message.taker_gets.currency !== 'XRP') {
request.message.taker_gets.issuer = UInt160.json_rewrite(gets.issuer);
}
request.message.taker_pays = {
currency: Currency.json_rewrite(pays.currency)
}
if (request.message.taker_pays.currency !== 'XRP') {
request.message.taker_pays.issuer = UInt160.json_rewrite(pays.issuer);
}
request.message.taker = taker ? taker : UInt160.ACCOUNT_ONE;
request.callback(callback);
return request;
};
Remote.prototype.requestWalletAccounts = function(seed, callback) {
utils.assert(this.trusted); // Don't send secrets.
var request = new Request(this, 'wallet_accounts');
request.message.seed = seed;
request.callback(callback);
return request;
};
Remote.prototype.requestSign = function(secret, tx_json, callback) {
utils.assert(this.trusted); // Don't send secrets.
var request = new Request(this, 'sign');