-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
2743 lines (2325 loc) · 68.6 KB
/
index.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
var EventEmitter = require('events').EventEmitter
var assert = require('assert')
var util = require('util')
var omit = require('object.omit')
var Q = require('q')
var typeforce = require('typeforce')
var debug = require('debug')('tim')
var PassThrough = require('readable-stream').PassThrough
var reemit = require('re-emitter')
var bitcoin = require('@tradle/bitcoinjs-lib')
var extend = require('xtend/mutable')
var clone = require('xtend/immutable')
var collect = require('stream-collector')
var tradleUtils = require('@tradle/utils')
var map = require('map-stream')
var pump = require('pump')
var find = require('array-find')
var deepEqual = require('deep-equal')
var Cache = require('lru-cache')
var ChainedObj = require('@tradle/chained-obj')
var TxData = require('@tradle/tx-data').TxData
var TxInfo = require('@tradle/tx-data').TxInfo
var ChainWriter = require('@tradle/bitjoe-js')
var ChainLoader = require('@tradle/chainloader')
var Permission = require('@tradle/permission')
var Wallet = require('@tradle/simple-wallet')
var hrtime = require('monotonic-timestamp')
var mi = require('@tradle/identity')
var Identity = mi.Identity
var kiki = require('@tradle/kiki')
var toKey = kiki.toKey
var Builder = ChainedObj.Builder
var Parser = ChainedObj.Parser
var lb = require('logbase')
var Entry = lb.Entry
var unchainer = require('./lib/unchainer')
var constants = require('@tradle/constants')
var EventType = require('./lib/eventType')
var Dir = require('./lib/dir')
var createIdentityDB = require('./lib/identityDB')
var createMsgDB = require('./lib/msgDB')
var createTypeDB = require('./lib/typeDB')
var createTxDB = require('./lib/txDB')
var createMiscDB = require('./lib/miscDB')
var Errors = require('./lib/errors')
var utils = require('./lib/utils')
var getViaCache = require('./lib/getViaCache')
var RETRY_UNCHAIN_ERRORS = [
ChainLoader.Errors.ParticipantsNotFound,
ChainLoader.Errors.FileNotFound
].map(function (ErrType) {
return ErrType.type
})
var DEV = process.env.NODE_ENV !== 'production'
var TYPE = constants.TYPE
var TYPES = constants.TYPES
var SIGNEE = constants.SIGNEE
var ROOT_HASH = constants.ROOT_HASH
var PREV_HASH = constants.PREV_HASH
var CUR_HASH = constants.CUR_HASH
var NONCE = constants.NONCE
var CONFIRMATIONS_BEFORE_CONFIRMED = 10
Driver.BLOCKCHAIN_KEY_PURPOSE = 'messaging'
Driver.MIN_BALANCE = 10000
Driver.CHAIN_WRITE_THROTTLE = 60000
Driver.CHAIN_READ_THROTTLE = 300000
Driver.SEND_THROTTLE = 10000
Driver.CATCH_UP_INTERVAL = 2000
Driver.UNCHAIN_THROTTLE = 20000
// Driver.Zlorp = Zlorp
Driver.Kiki = kiki
Driver.Identity = Identity
Driver.Wallet = Wallet
Driver.EventType = EventType
Driver.PROTOCOL_VERSION = '1.0.0'
// TODO: export other deps
var DEFAULT_OPTIONS = {
opReturnPrefix: '',
chainThrottle: Driver.CHAIN_WRITE_THROTTLE,
syncInterval: Driver.CHAIN_READ_THROTTLE,
unchainThrottle: Driver.UNCHAIN_THROTTLE,
sendThrottle: Driver.SEND_THROTTLE,
afterBlockTimestamp: 0
}
var optionsTypes = {
// maybe allow read-only mode if this is missing
// TODO: replace with kiki (will need to adjust otr, zlorp for async APIs)
keys: 'Array',
identity: 'Identity',
blockchain: 'Object',
networkName: 'String',
keeper: 'Object',
leveldown: 'Function',
pathPrefix: 'String',
opReturnPrefix: '?String',
syncInterval: '?Number',
chainThrottle: '?Number',
unchainThrottle: '?Number',
sendThrottle: '?Number',
readOnly: '?Boolean',
afterBlockTimestamp: '?Number',
name: '?String'
}
var noop = function () {}
module.exports = Driver
util.inherits(Driver, EventEmitter)
Driver.enableOptimizations = require('./lib/optimizations')
function Driver (options) {
var self = this
typeforce(optionsTypes, options)
EventEmitter.call(this)
this.setMaxListeners(0)
tradleUtils.bindPrototypeFunctions(this)
// this._fetchAndReschedule = promiseDebounce(this._fetchAndReschedule, this)
options = clone(DEFAULT_OPTIONS, options)
extend(this, omit(options, ['name']))
this._options = utils.pick(this, Object.keys(optionsTypes))
this._name = options.name
this._signingKey = toKey(
this.getPrivateKey({
type: 'ec',
purpose: 'sign'
})
)
// copy
this.identityMeta = {}
this.setIdentity(options.identity.toJSON())
if (this.afterBlockTimestamp) {
this._debug('ignoring txs before', new Date(this.afterBlockTimestamp * 1000).toString())
}
var networkName = this.networkName
var keeper = this.keeper
var blockchain = this.blockchain
var leveldown = this.leveldown
var wallet = this.wallet = this.wallet || new Wallet({
networkName: networkName,
blockchain: blockchain,
priv: this.getBlockchainKey().priv()
})
// init balance while we rely on blockr for this info
this._balance = 0
this._paused = false
this.chainwriter = new ChainWriter({
wallet: wallet,
keeper: keeper,
networkName: networkName,
minConf: 0,
prefix: this.opReturnPrefix
})
this.chainloader = new ChainLoader({
keeper: keeper,
networkName: networkName,
prefix: this.opReturnPrefix,
lookup: this.getKeyAndIdentity2
})
this.unchainer = unchainer({
chainloader: this.chainloader,
lookup: this.lookupByDHTKey
})
this._streams = {}
this._ignoreTxs = []
this._watchedAddresses = [
this.wallet.addressString
]
this._watchedTxs = []
// in-memory cache of recent conversants
this._catchUpWithBlockchain()
this._fingerprintToIdentity = {}
this._pendingTxs = []
this._setupDBs()
this._setupTxFetching()
var keeperReadyDfd = Q.defer()
var keeperReady = keeperReadyDfd.promise
if (!keeper.isReady || keeper.isReady()) keeperReadyDfd.resolve()
else keeper.once('ready', keeperReadyDfd.resolve)
this._readyPromise = Q.all([
self._prepIdentity(),
self._setupTxStream(),
keeperReady,
this._loadWatches(),
this._updateBalance()
.catch(function (e) {
self._debug('unable to get balance')
})
])
.then(function () {
if (self._destroyed) {
return Q.reject(new Error('destroyed'))
}
self.msgDB.start()
self.txDB.start()
self.addressBook.start()
self.typeDB.start()
self.miscDB.start()
self._ready = true
self._debug('ready')
self.emit('ready')
// self.publishMyIdentity()
self._writeToChain()
self._readFromChain()
self._sendTheUnsent()
// self._watchMsgStatuses()
})
}
/**
* specify txIds for which to load txs
* @param {Array} txIds - transaction ids
*/
Driver.prototype.loadTxs = function (txIds) {
var self = this
Q.ninvoke(this.blockchain.transactions, 'get', txIds)
.then(function (txInfos) {
// TODO: get rid of this parse everywhere
txInfos = utils.parseCommonBlockchainTxs(txInfos)
return self._processTxs(txInfos)
})
}
Driver.prototype.ready = function () {
return this._readyPromise
}
Driver.prototype.isReady = function () {
return this._ready
}
Driver.prototype.isPaused = function () {
return this._paused
}
Driver.prototype.pause = function (resumeTimeout) {
if (this._paused) return
this._debug('pausing...')
this._paused = true
for (var name in this._streams) {
this._streams[name].pause()
}
if (typeof resumeTimeout === 'number') {
setTimeout(this.resume, resumeTimeout)
}
this.emit('pause')
}
Driver.prototype.resume = function () {
if (!this._paused) return
this._debug('resuming...')
this._paused = false
for (var name in this._streams) {
this._streams[name].resume()
}
this.emit('resume')
}
Driver.prototype._prepIdentity = function () {
var self = this
return utils.getDHTKey(this.identityJSON)
.then(function (key) {
copyDHTKeys(self.identityMeta, key)
})
}
Driver.prototype._updateBalance = function () {
var self = this
return Q.ninvoke(this.wallet, 'balance')
.then(function (balance) {
self._balance = balance
if (balance < Driver.MIN_BALANCE) {
self.emit('lowbalance')
}
})
}
/**
* read from chain
*/
Driver.prototype._readFromChain = function () {
var self = this
if (this._destroyed) return
if (!this.txDB.isLive()) {
return this.txDB.once('live', this._readFromChain)
}
if (this._queuedUnchains) return
this._queuedUnchains = {}
var stream = this.txDB.liveStream({
old: true,
tail: true
})
this._streams.txDB = stream
pump(
stream,
map(function (data, cb) {
if (self._destroyed || typeof data.value !== 'object') {
return cb()
}
cb(null, data.value)
}),
map(function (entry, cb) {
// was read from chain and hasn't been processed yet
var txId = entry.txId
if (!entry.dateDetected || entry.dateUnchained || entry.ignore) {
return finish()
}
// no body yet
if (!entry.tx) {
return finish()
}
// clear old errors
var errs = utils.getErrors(entry, 'unchain')
delete entry.errors
if (!errs || !errs.length) return finish(null, entry)
var shouldTryAgain = errs.every(function (err) {
return RETRY_UNCHAIN_ERRORS.indexOf(err.type) !== -1
})
if (!shouldTryAgain) return finish()
if (errs.length >= Errors.MAX_UNCHAIN) {
// console.log(entry.errors, entry.id)
self._debug('skipping unchain after', errs.length, 'errors for tx:', txId)
// TODO: remove
// self._remove(entry)
return finish()
}
if (self._queuedUnchains[txId]) {
finish()
return self._debug('already schedulded unchaining!')
}
self._queuedUnchains[txId] = true
var throttled = throttleIfRetrying(errs, self.unchainThrottle, function () {
finish(null, entry)
})
if (throttled) {
self._debug('throttling unchain retry of tx', txId, throttled, 'millis')
}
function finish (err, ret) {
if (err || !ret) self._rmPending(txId)
delete self._queuedUnchains[txId]
if (!ret) {
self._debug('skipping unchain of tx', txId)
}
cb(err, ret)
}
}),
map(function (txEntry, cb) {
if (self._destroyed) return cb()
var chainedObj
self.lookupObject(txEntry, true) // verify=true
.then(function (result) {
chainedObj = result
if (chainedObj.txType === TxData.types.public) {
self._debug('saving to keeper')
self.keeper.put(chainedObj.key, chainedObj.data)
}
return chainedObj
})
.catch(function (err) {
chainedObj = err.progress
})
// record failed unchains as well
.then(function () {
return self.unchainResultToEntry(chainedObj)
})
.done(function (entry) {
self._rmPending(utils.getEntryProp(entry, 'txId'))
cb(null, entry)
})
}),
utils.jsonify(),
this._log,
this._rethrow
)
this._pauseStreamIfPaused(stream)
}
Driver.prototype._pauseStreamIfPaused = function (stream) {
if (this._paused) {
stream.pause()
}
}
// Driver.prototype._remove = function (info, lookup) {
// var self = this
// this.lookupObject(info)
// .catch(function (err) {
// return err.progress
// })
// .then(function (chainedObj) {
// var tasks = ['key', 'permissionKey']
// .map(function (p) {
// return chainedObj[p]
// })
// .filter(function (key) {
// return !!key
// })
// return Q.all(tasks)
// })
// }
Driver.prototype._rmPending = function (txId) {
typeforce('String', txId)
var idx = this._pendingTxs.indexOf(txId)
if (idx !== -1) {
this._pendingTxs.splice(idx, 1)
}
}
Driver.prototype._rethrow = function (err) {
if (err) {
this._debug('experienced an error', err)
if (!this._destroyed && err) throw err
}
}
Driver.prototype._setupTxFetching = function () {
var self = this
var txDB = this.txDB
var txSubmodule = this.blockchain.transactions
txSubmodule.get = getViaCache(
txSubmodule.get.bind(txSubmodule),
getFromCache
)
function getFromCache (ids, cb) {
// ids = ids.filter(function (id) {
// return self._ignoreTxs.indexOf(id) === -1
// })
// var togo = ids.length
// if (togo === 0) return cb(null, [])
self._multiGetFromDB({
db: self.txDB,
keys: ids
})
.then(function (results) {
results = utils.pluck(results, 'value')
results.forEach(function (r, i) {
if (r && r.ignore) {
var id = ids[i]
if (self._ignoreTxs.indexOf(id) === -1) {
self._ignoreTxs.push(id)
}
}
})
results = results.map(function (v) {
return v && v.tx && v.confirmations >= CONFIRMATIONS_BEFORE_CONFIRMED ? v : undefined
})
cb(null, results)
})
}
}
Driver.prototype._catchUpWithBlockchain = function () {
var self = this
if (this._caughtUpPromise) return this._caughtUpPromise
var done
var txIds
var catchUp = Q.defer()
this._caughtUpPromise = catchUp.promise
.then(function () {
self._debug('caught up with blockchain')
})
.finally(function () {
done = true
})
this.once('txs', function (txInfos) {
txIds = txInfos
.filter(function (txInfo) {
return txInfo.blockTimestamp > self.afterBlockTimestamp
})
.map(function (txInfo) {
return txInfo.txId
})
checkDBs()
})
return this._caughtUpPromise
function checkDBs () {
if (self._destroyed) return
self._multiGetFromDB({
db: self.txDB,
keys: txIds,
strict: true,
then: function (entry) {
var hasErrors = !!utils.countErrors(entry)
var processed = entry.dateUnchained || entry.dateChained || entry.ignore || hasErrors
if (!processed) {
self._debug('still waiting for tx', entry.txId)
throw new Error('not ready')
}
}
})
.then(catchUp.resolve)
.catch(scheduleRetry)
}
function scheduleRetry () {
self._debug('not caught up yet with blockchain...')
setTimeout(checkDBs, Driver.CATCH_UP_INTERVAL)
}
}
// Driver.prototype.unignoreTxs = function (txIds) {
// this.log(new Entry({
// type: EventType.tx.load,
// ignore: false,
// txIds: txIds
// }))
// }
Driver.prototype._sortParsedTxs = function (txInfos) {
return txInfos
}
Driver.prototype._shouldLoadTx = function (txInfo) {
// override this if you want to be more choosy
return true
}
Driver.prototype._willLoadTx = function (txInfo) {
var txId = txInfo.txId
if (this._ignoreTxs.indexOf(txId) !== -1) return false
if (this._watchedTxs.indexOf(txId) !== -1) return true
return this._shouldLoadTx(txInfo)
}
// Driver.prototype.shouldLoadTxData = function (txData) {
// // override this if you want to be more choosy
// return true
// }
Driver.prototype._multiGetFromDB = function (opts) {
// override this if you have a better way
// e.g. in react-native, with AsyncStorage.multiGet
typeforce({
db: 'Object',
keys: 'Array',
then: '?Function',
strict: '?Boolean'
}, opts)
return Q[opts.strict ? 'all' : 'allSettled'](opts.keys.map(function (key) {
var promise = Q.ninvoke(opts.db, 'get', key)
return opts.then ? promise.then(opts.then) : promise
}))
}
Driver.prototype.identityPublishStatus = function () {
var self = this
// check if we've already chained it
if (!this._ready) {
return this._readyPromise.then(this.identityPublishStatus)
}
var rh = this.myRootHash()
var me = this.identityJSON
var status = {
ever: false,
current: false,
queued: false
}
return this._catchUpWithBlockchain()
.then(function () {
return Q.all([
Q.ninvoke(self.msgDB, 'byRootHash', rh),
Q.ninvoke(tradleUtils, 'getStorageKeyFor', utils.toBuffer(me))
])
})
.spread(function (entries, curHash) {
curHash = curHash.toString('hex')
var unchained = entries.filter(function (e) {
return e.dateUnchained
})
status.ever = !!unchained.length
unchained.some(function (e) {
if (e[CUR_HASH] === curHash) {
status.txId = e.txId
status.current = true
return true
}
})
status.queued = !status.current && entries.some(function (e) {
return e[CUR_HASH] === curHash
})
return status
})
.catch(function (err) {
if (!err.notFound) throw err
return status
})
}
Driver.prototype.publishIdentity = function (identity, toAddress) {
identity = identity || this.identityJSON
return this.publish({
msg: identity,
to: [{ fingerprint: toAddress || constants.IDENTITY_PUBLISH_ADDRESS }]
})
}
Driver.prototype.setIdentity = function (identityJSON) {
if (deepEqual(this.identityJSON, identityJSON)) return
this.identity = Identity.fromJSON(identityJSON)
this.identityJSON = this.identity.toJSON()
}
Driver.prototype.publishMyIdentity = function (toAddr) {
var self = this
if (this._publishingIdentity) {
throw new Error('wait till current publishing process ends')
}
if (!this._ready) {
return this._readyPromise.then(this.publishMyIdentity)
}
if (toAddr) {
this.watchAddresses(toAddr)
}
this._publishingIdentity = true
return this.identityPublishStatus()
.then(function (status) {
if (!status.ever) return self.publishIdentity()
if (status.queued) {
return Q.reject(new Error('already publishing this version'))
}
if (status.current) {
return Q.reject(new Error('already published this version'))
}
return publish()
})
.finally(function () {
delete self._publishingIdentity
})
function publish () {
var priv = self.getPrivateKey({ purpose: 'update' })
var update = extend({}, self.identityJSON)
var prevHash = self.myCurrentHash() || self.myRootHash()
utils.updateChainedObj(update, prevHash)
return Builder.addNonce(update)
.then(function () {
return Builder()
.data(update)
.signWith(toKey(priv))
.build()
})
.then(function (buf) {
self.setIdentity(update)
extend(self.identityMeta, utils.pick(update, PREV_HASH, ROOT_HASH))
return Q.all([
self._prepIdentity(),
self.publishIdentity(buf, toAddr)
])
})
}
}
Driver.prototype.identities = function () {
return this.addressBook
}
Driver.prototype.messages = function () {
return this.msgDB
}
Driver.prototype.decryptedMessagesStream = function () {
var self = this
return this.msgDB.createValueStream()
.pipe(map(function (info, cb) {
self.lookupObject(info)
.then(function (obj) {
cb(null, obj)
}, function (err) {
self._debug('failed to lookup object: ' + info[CUR_HASH])
cb()
})
}))
}
Driver.prototype.transactions = function () {
return this.txDB
}
Driver.prototype.unchainResultToEntry = function (chainedObj) {
var self = this
var success = !utils.countErrors(chainedObj)
var type = success ?
EventType.chain.readSuccess :
EventType.chain.readError
// no decrypted data should be stored in the log
var safeProps = omit(chainedObj, [
'type',
'parsed',
'key',
'data',
'encryptedData', // stored in keeper
'permission',
'encryptedPermission' // stored in keeper
])
var entry = new Entry(safeProps)
.set('type', type)
// if ('key' in chainedObj) {
// entry.set(CUR_HASH, chainedObj.key)
// }
if ('parsed' in chainedObj) {
entry.set('public', chainedObj.txType === TxData.types.public)
}
if ('tx' in chainedObj) {
entry.set('tx', utils.toBuffer(chainedObj.tx))
}
var tasks = ['from', 'to'].map(function (party) {
return chainedObj[party]
})
.map(function (party) {
if (!party) return
if (party[ROOT_HASH]) return party[ROOT_HASH]
// a bit scary
var fingerprint = party.identity.keys()[0].toJSON().fingerprint
return self.lookupRootHash(fingerprint)
})
return Q.allSettled(tasks)
.spread(function (from, to) {
if (from.value) {
entry.set('from', utils.toObj(ROOT_HASH, from.value))
}
if (to.value) {
entry.set('to', utils.toObj(ROOT_HASH, to.value))
}
if (success) utils.setUID(entry)
return entry
})
}
Driver.prototype._writeToChain = function () {
var self = this
var getStream = this.msgDB.getToChainStream.bind(this.msgDB, {
old: true,
tail: true
})
var throttle = this.chainThrottle
this._processQueue({
name: 'writeToChain',
getStream: getStream,
maxErrors: Errors.MAX_CHAIN,
errorsGroup: Errors.group.chain,
processItem: this.putOnChain,
throttle: throttle,
retryDelay: throttle,
successType: EventType.chain.writeSuccess,
// shouldSkipQueue: function (state) {
// return state.public
// },
shouldTryLater: function (state) {
if (self._balance < Driver.MIN_BALANCE) {
self._updateBalance()
return true
}
}
})
}
Driver.prototype.getSendQueue = function () {
var msgDB = this.msgDB
var stream = pump(
msgDB.getToSendStream({
old: true,
tail: false
}),
map(function (data, cb) {
msgDB.get(data.value, cb)
})
// ,
// utils.filterStream(function (data) {
// var errs = utils.getErrors(data, 'send')
// return !(errs && errs.length >= Errors.MAX_SEND)
// })
)
return Q.nfcall(collect, stream)
}
Driver.prototype.getChainQueue = function () {
var msgDB = this.msgDB
var stream = pump(
msgDB.getToChainStream({
old: true,
tail: false
}),
map(function (data, cb) {
msgDB.get(data.value, cb)
})
// ,
// utils.filterStream(function (data) {
// var errs = utils.getErrors(data, 'chain')
// return !(errs && errs.length >= Errors.MAX_CHAIN)
// })
)
return Q.nfcall(collect, stream)
}
Driver.prototype._sendTheUnsent = function () {
var getStream = this.msgDB.getToSendStream.bind(this.msgDB, {
old: true,
tail: true
})
this._processQueue({
name: 'sendTheUnsent',
getStream: getStream,
maxErrors: Errors.MAX_RESEND,
errorsGroup: Errors.group.send,
processItem: this._processSendQueueItem,
retryDelay: this.sendThrottle,
successType: EventType.msg.sendSuccess,
giveUpType: EventType.msg.giveUpSend
})
}
Driver.prototype._processQueue = function (opts) {
var self = this
typeforce({
name: 'String',
successType: 'Number',
getStream: 'Function',
processItem: 'Function',
maxErrors: '?Number',
shouldSkipQueue: '?Function',
shouldTryLater: '?Function',
retryDelay: '?Number',
retryOnFail: '?Boolean' // default: true
}, opts)
var name = opts.name
this._processingQueue = this._processingQueue || {}
if (this._processingQueue[name]) return
this._processingQueue[name] = true
// queues by recipient root hash
var queues = {}
var lastProcessTime = 0
var shouldSkipQueue = opts.shouldSkipQueue || alwaysFalse
var shouldTryLater = opts.shouldTryLater || alwaysFalse
var maxErrors = typeof opts.maxErrors === 'number' ? opts.maxErrors : Infinity
var errorsGroup = opts.errorsGroup
var processItem = opts.processItem
if (opts.throttle) {
processItem = utils.rateLimitPromiseFn(processItem, opts.throttle)
}
var retryDelay = opts.retryDelay
var retryOnFail = opts.retryOnFail !== false
var successType = opts.successType
var giveUpType = opts.giveUpType
var stream = opts.getStream()
var sync
stream.once('sync', function () {
sync = true
})
this._streams[name] = stream
pump(
stream,
map(function (data, cb) {
if (data.type === 'del') {
remove(data)
return cb()
}
self.msgDB.get(data.value, function (err, state) {
if (err) {
self._debug('error on "get" from msgDB', err)
remove(data)
return throwIfDev(err)
}
// HACK for bug fixed in 3.5.1
// to kill orphaned timestamps that were already introduced
if (state.timestamp !== Number(data.key.split('!')[1])) {
self._debug('ignoring orphaned timestamp', state.uuid)
return cb()
}
if (shouldSkipQueue(state)) {
runASAP(state)
} else {
insert(state)
processQueue(getQueueID(state))
}
cb()
})
})
)
this._pauseStreamIfPaused(stream)
function getQueueID (data) {
// should public go in one queue?
// return data.public ? data[ROOT_HASH] : data.to[ROOT_HASH]
return data.to[ROOT_HASH] || data.to.fingerprint
}
function runASAP (state) {
if (self._destroyed) return
if (shouldTryLater(state)) {
setTimeout(runASAP.bind(null, state), retryDelay)
} else {
processItem(state)
}
}