-
Notifications
You must be signed in to change notification settings - Fork 183
/
index.js
1645 lines (1325 loc) · 44.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 low = require('last-one-wins')
var remove = require('unordered-array-remove')
var set = require('unordered-set')
var merkle = require('merkle-tree-stream/generator')
var flat = require('flat-tree')
var bulk = require('bulk-write-stream')
var from = require('from2')
var codecs = require('codecs')
var batcher = require('atomic-batcher')
var inherits = require('inherits')
var raf = require('random-access-file')
var bitfield = require('./lib/bitfield')
var sparseBitfield = require('sparse-bitfield')
var treeIndex = require('./lib/tree-index')
var storage = require('./lib/storage')
var crypto = require('hypercore-crypto')
var inspect = require('inspect-custom-symbol')
var pretty = require('pretty-hash')
var Nanoguard = require('nanoguard')
var safeBufferEquals = require('./lib/safe-buffer-equals')
var replicate = require('./lib/replicate')
var Protocol = require('hypercore-protocol')
var Message = require('abstract-extension')
var Nanoresource = require('nanoresource/emitter')
class Extension extends Message {
broadcast (message) {
const feed = this.local.handlers
const buf = this.encoding.encode(message)
for (const peer of feed.peers) {
peer.extension(this.id, buf)
}
}
send (message, peer) {
peer.extension(this.id, this.encode(message))
}
}
var defaultCrypto = {
sign (data, sk, cb) {
return cb(null, crypto.sign(data, sk))
},
verify (sig, data, pk, cb) {
return cb(null, crypto.verify(sig, data, pk))
}
}
module.exports = Feed
function Feed (createStorage, key, opts) {
if (!(this instanceof Feed)) return new Feed(createStorage, key, opts)
Nanoresource.call(this)
if (typeof createStorage === 'string') createStorage = defaultStorage(createStorage)
if (typeof createStorage !== 'function') throw new Error('Storage should be a function or string')
if (typeof key === 'string') key = Buffer.from(key, 'hex')
if (!Buffer.isBuffer(key) && !opts) {
opts = key
key = null
}
if (!opts) opts = {}
var self = this
var secretKey = opts.secretKey || null
if (typeof secretKey === 'string') secretKey = Buffer.from(secretKey, 'hex')
this.noiseKeyPair = opts.noiseKeyPair || Protocol.keyPair()
this.live = opts.live !== false
this.sparse = !!opts.sparse
this.length = 0
this.byteLength = 0
this.maxRequests = opts.maxRequests || 16
this.key = key || opts.key || null
this.discoveryKey = this.key && crypto.discoveryKey(this.key)
this.secretKey = secretKey
this.bitfield = null
this.tree = null
this.writable = !!opts.writable
this.readable = true
this.downloading = opts.downloading !== false
this.uploading = opts.uploading !== false
this.allowPush = !!opts.allowPush
this.peers = []
this.ifAvailable = new Nanoguard()
this.extensions = Extension.createLocal(this) // set Feed as the handlers
this.crypto = opts.crypto || defaultCrypto
// hooks
this._onwrite = opts.onwrite || null
this._indexing = !!opts.indexing
this._createIfMissing = opts.createIfMissing !== false
this._overwrite = !!opts.overwrite
this._storeSecretKey = opts.storeSecretKey !== false
this._alwaysIfAvailable = !!opts.ifAvailable
this._merkle = null
this._storage = storage(createStorage, opts)
this._batch = batcher(this._onwrite ? workHook : work)
this._seq = 0
this._waiting = []
this._selections = []
this._reserved = sparseBitfield()
this._synced = null
this._downloadingSet = typeof opts.downloading === 'boolean'
this._stats = (typeof opts.stats !== 'undefined' && !opts.stats) ? null : {
downloadedBlocks: 0,
downloadedBytes: 0,
uploadedBlocks: 0,
uploadedBytes: 0
}
this._codec = toCodec(opts.valueEncoding)
this._sync = low(sync)
if (!this.sparse) this.download({start: 0, end: -1})
if (this.sparse && opts.eagerUpdate) {
this.update(function loop (err) {
if (err) this.emit('update-error', err)
self.update(loop)
})
}
// open it right away
this.open(onerror)
function onerror (err) {
if (err) self.emit('error', err)
}
function workHook (values, cb) {
if (!self._merkle) return self._reloadMerkleStateBeforeAppend(workHook, values, cb)
self._appendHook(values, cb)
}
function work (values, cb) {
if (!self._merkle) return self._reloadMerkleStateBeforeAppend(work, values, cb)
self._append(values, cb)
}
function sync (_, cb) {
self._syncBitfield(cb)
}
}
inherits(Feed, Nanoresource)
Feed.discoveryKey = crypto.discoveryKey
Feed.prototype[inspect] = function (depth, opts) {
var indent = ''
if (typeof opts.indentationLvl === 'number') {
while (indent.length < opts.indentationLvl) indent += ' '
}
return 'Hypercore(\n' +
indent + ' key: ' + opts.stylize((this.key && pretty(this.key)), 'string') + '\n' +
indent + ' discoveryKey: ' + opts.stylize((this.discoveryKey && pretty(this.discoveryKey)), 'string') + '\n' +
indent + ' opened: ' + opts.stylize(this.opened, 'boolean') + '\n' +
indent + ' sparse: ' + opts.stylize(this.sparse, 'boolean') + '\n' +
indent + ' writable: ' + opts.stylize(this.writable, 'boolean') + '\n' +
indent + ' length: ' + opts.stylize(this.length, 'number') + '\n' +
indent + ' byteLength: ' + opts.stylize(this.byteLength, 'number') + '\n' +
indent + ' peers: ' + opts.stylize(this.peers.length, 'number') + '\n' +
indent + ')'
}
// TODO: instead of using a getter, update on remote-update/add/remove
Object.defineProperty(Feed.prototype, 'remoteLength', {
enumerable: true,
get: function () {
var len = 0
for (var i = 0; i < this.peers.length; i++) {
var remoteLength = this.peers[i].remoteLength
if (remoteLength > len) len = remoteLength
}
return len
}
})
Object.defineProperty(Feed.prototype, 'stats', {
enumerable: true,
get: function () {
if (!this._stats) return null
var peerStats = []
for (var i = 0; i < this.peers.length; i++) {
var peer = this.peers[i]
peerStats[i] = peer.stats
}
return {
peers: peerStats,
totals: this._stats
}
}
})
Feed.prototype.replicate = function (initiator, opts) {
if ((!this._selections.length || this._selections[0].end !== -1) && !this.sparse && !(opts && opts.live)) {
// hack!! proper fix is to refactor ./replicate to *not* clear our non-sparse selection
this.download({start: 0, end: -1})
}
if (isOptions(initiator) && !opts) {
opts = initiator
initiator = opts.initiator
}
opts = opts || {}
opts.stats = !!this._stats
opts.noise = !(opts.noise === false && opts.encrypted === false)
var stream = replicate(this, initiator, opts)
this.emit('replicating', stream)
return stream
}
Feed.prototype.registerExtension = function (name, handlers) {
return this.extensions.add(name, handlers)
}
Feed.prototype.onextensionupdate = function () {
for (const peer of this.peers) peer._updateOptions()
}
Feed.prototype.setDownloading = function (downloading) {
if (this.downloading === downloading && this._downloadingSet) return
this.downloading = downloading
this._downloadingSet = true
this.ready((err) => {
if (err) return
for (const peer of this.peers) peer.setDownloading(this.downloading)
})
}
Feed.prototype.setUploading = function (uploading) {
if (uploading === this.uploading) return
this.uploading = uploading
this.ready((err) => {
if (err) return
for (const peer of this.peers) peer.setUploading(this.uploading)
})
}
// Alias the nanoresource open method
Feed.prototype.ready = Feed.prototype.open
Feed.prototype.update = function (opts, cb) {
if (typeof opts === 'function') return this.update(-1, opts)
if (typeof opts === 'number') opts = { minLength: opts }
if (!opts) opts = {}
if (!cb) cb = noop
var self = this
var len = typeof opts.minLength === 'number' ? opts.minLength : -1
this.ready(function (err) {
if (err) return cb(err)
if (len === -1) len = self.length + 1
if (self.length >= len) return cb(null)
if (self.writable) cb = self._writeStateReloader(cb)
var w = {
hash: opts.hash !== false,
bytes: 0,
index: len - 1,
options: opts,
update: true,
callback: cb
}
self._waiting.push(w)
if (typeof opts.ifAvailable === 'boolean' ? opts.ifAvailable : self._alwaysIfAvailable) self._ifAvailable(w, len)
self._updatePeers()
})
}
Feed.prototype._ifAvailable = function (w, minLength) {
var cb = w.callback
var called = false
var self = this
w.callback = done
process.nextTick(readyNT, this.ifAvailable, function () {
if (self.closed) return done(new Error('Closed'))
if (self.length >= minLength || self.remoteLength >= minLength) return
done(new Error('No update available from peers'))
})
function done (err) {
if (called) return
called = true
var i = self._waiting.indexOf(w)
if (i > -1) remove(self._waiting, i)
cb(err)
}
}
Feed.prototype._ifAvailableGet = function (w) {
var cb = w.callback
var called = false
var self = this
w.callback = done
process.nextTick(readyNT, this.ifAvailable, function () {
if (self.closed) return done(new Error('Closed'))
for (var i = 0; i < self.peers.length; i++) {
var peer = self.peers[i]
if (peer.remoteBitfield.get(w.index)) return
}
done(new Error('Block not available from peers'))
})
function done (err, data) {
if (called) return
called = true
var i = self._waiting.indexOf(w)
if (i > -1) remove(self._waiting, i)
cb(err, data)
}
}
// will reload the writable state. used by .update on a writable peer
Feed.prototype._writeStateReloader = function (cb) {
var self = this
return function (err) {
if (err) return cb(err)
self._reloadMerkleState(cb)
}
}
Feed.prototype._reloadMerkleState = function (cb) {
var self = this
this._roots(self.length, function (err, roots) {
if (err) return cb(err)
self._merkle = merkle(crypto, roots)
cb(null)
})
}
Feed.prototype._reloadMerkleStateBeforeAppend = function (work, values, cb) {
this._reloadMerkleState(function (err) {
if (err) return cb(err)
work(values, cb)
})
}
Feed.prototype._open = function (cb) {
var self = this
var generatedKey = false
var retryOpen = true
// TODO: clean up the duplicate code below ...
this._storage.openKey(function (_, key) {
if (key && !self._overwrite && !self.key) self.key = key
if (!self.key && self.live) {
var keyPair = crypto.keyPair()
self.secretKey = keyPair.secretKey
self.key = keyPair.publicKey
generatedKey = true
}
self.discoveryKey = self.key && crypto.discoveryKey(self.key)
self._storage.open({key: self.key, discoveryKey: self.discoveryKey}, onopen)
})
function onopen (err, state) {
if (err) return cb(err)
// if no key but we have data do a bitfield reset since we cannot verify the data.
if (!state.key && state.bitfield.length) {
self._overwrite = true
}
if (self._overwrite) {
state.bitfield = []
state.key = state.secretKey = null
}
self.bitfield = bitfield(state.bitfieldPageSize, state.bitfield)
self.tree = treeIndex(self.bitfield.tree)
self.length = self.tree.blocks()
self._seq = self.length
if (state.key && self.key && Buffer.compare(state.key, self.key) !== 0) {
return self._forceClose(cb, new Error('Another hypercore is stored here'))
}
if (state.key) self.key = state.key
if (state.secretKey) self.secretKey = state.secretKey
if (!self.length) return onsignature(null, null)
self._storage.getSignature(self.length - 1, onsignature)
function onsignature (_, sig) {
if (self.length) self.live = !!sig
if ((generatedKey || !self.key) && !self._createIfMissing) {
return self._forceClose(cb, new Error('No hypercore is stored here'))
}
if (!self.key && self.live) {
var keyPair = crypto.keyPair()
self.secretKey = keyPair.secretKey
self.key = keyPair.publicKey
}
var writable = !!self.secretKey || self.key === null
if (!writable && self.writable) return self._forceClose(cb, new Error('Feed is not writable'))
self.writable = writable
if (!self._downloadingSet) self.downloading = !writable
self.discoveryKey = self.key && crypto.discoveryKey(self.key)
if (self._storeSecretKey && !self.secretKey) {
self._storeSecretKey = false
}
var shouldWriteKey = generatedKey || !safeBufferEquals(self.key, state.key)
var shouldWriteSecretKey = self._storeSecretKey && (generatedKey || !safeBufferEquals(self.secretKey, state.secretKey))
var missing = 1 +
(shouldWriteKey ? 1 : 0) +
(shouldWriteSecretKey ? 1 : 0) +
(self._overwrite ? 1 : 0)
var error = null
if (shouldWriteKey) self._storage.key.write(0, self.key, done)
if (shouldWriteSecretKey) self._storage.secretKey.write(0, self.secretKey, done)
if (self._overwrite) {
self._storage.bitfield.del(32, Infinity, done)
}
done(null)
function done (err) {
if (err) error = err
if (--missing) return
if (error) return self._forceClose(cb, error)
self._roots(self.length, onroots)
}
function onroots (err, roots) {
if (err && retryOpen) {
retryOpen = false
self.length--
self._storage.getSignature(self.length - 1, onsignature)
return
}
if (err) return self._forceClose(cb, err)
self._merkle = merkle(crypto, roots)
self.byteLength = roots.reduce(addSize, 0)
self.emit('ready')
cb(null)
}
}
}
}
Feed.prototype.download = function (range, cb) {
if (typeof range === 'function') return this.download(null, range)
if (typeof range === 'number') range = {start: range, end: range + 1}
if (!range) range = {}
if (!cb) cb = noop
if (!this.readable) return cb(new Error('Feed is closed'))
// TODO: if no peers, check if range is already satisfied and nextTick(cb) if so
// this._updatePeers does this for us when there is a peer though, so not critical
var sel = {
_index: this._selections.length,
hash: !!range.hash,
iterator: null,
start: range.start || 0,
end: range.end || -1,
want: 0,
linear: !!range.linear,
requested: 0,
callback: cb
}
sel.want = toWantRange(sel.start)
this._selections.push(sel)
this._updatePeers()
return sel
}
Feed.prototype.undownload = function (range) {
if (typeof range === 'number') range = {start: range, end: range + 1}
if (!range) range = {}
if (range.callback && range._index > -1) {
set.remove(this._selections, range)
process.nextTick(range.callback, createError('ECANCELED', -11, 'Download was cancelled'))
return
}
var start = range.start || 0
var end = range.end || -1
var hash = !!range.hash
var linear = !!range.linear
for (var i = 0; i < this._selections.length; i++) {
var s = this._selections[i]
if (s.start === start && s.end === end && s.hash === hash && s.linear === linear) {
set.remove(this._selections, s)
process.nextTick(range.callback, createError('ECANCELED', -11, 'Download was cancelled'))
return
}
}
}
Feed.prototype.digest = function (index) {
return this.tree.digest(2 * index)
}
Feed.prototype.proof = function (index, opts, cb) {
if (typeof opts === 'function') return this.proof(index, null, opts)
if (!this.opened) return this._readyAndProof(index, opts, cb)
if (!opts) opts = {}
var proof = this.tree.proof(2 * index, opts)
if (!proof) return cb(new Error('No proof available for this index'))
var needsSig = this.live && !!proof.verifiedBy
var pending = proof.nodes.length + (needsSig ? 1 : 0)
var error = null
var signature = null
var nodes = new Array(proof.nodes.length)
if (!pending) return cb(null, {nodes: nodes, signature: null})
for (var i = 0; i < proof.nodes.length; i++) {
this._storage.getNode(proof.nodes[i], onnode)
}
if (needsSig) {
this._storage.getSignature(proof.verifiedBy / 2 - 1, onsignature)
}
function onsignature (err, sig) {
if (sig) signature = sig
onnode(err, null)
}
function onnode (err, node) {
if (err) error = err
if (node) {
nodes[proof.nodes.indexOf(node.index)] = node
}
if (--pending) return
if (error) return cb(error)
cb(null, {nodes: nodes, signature: signature})
}
}
Feed.prototype._readyAndProof = function (index, opts, cb) {
var self = this
this.ready(function (err) {
if (err) return cb(err)
self.proof(index, opts, cb)
})
}
Feed.prototype.put = function (index, data, proof, cb) {
if (!this.opened) return this._readyAndPut(index, data, proof, cb)
this._putBuffer(index, this._codec.encode(data), proof, null, cb)
}
Feed.prototype.cancel = function (start, end) { // TODO: use same argument scheme as download
if (!end) end = start + 1
// cancel these right away as .download does not wait for ready
for (var i = this._selections.length - 1; i >= 0; i--) {
var sel = this._selections[i]
if (start <= sel.start && sel.end <= end) {
this.undownload(sel)
}
}
// defer the last part until after ready as .get does that as well
if (this.opened) this._cancel(start, end)
else this._readyAndCancel(start, end)
}
Feed.prototype._cancel = function (start, end) {
var i = 0
for (i = start; i < end; i++) {
this._reserved.set(i, false) // TODO: send cancel message if set returns true
}
for (i = this._waiting.length - 1; i >= 0; i--) {
var w = this._waiting[i]
if ((start <= w.start && w.end <= end) || (start <= w.index && w.index < end)) {
remove(this._waiting, i)
if (w.callback) process.nextTick(w.callback, new Error('Request cancelled'))
}
}
}
Feed.prototype.clear = function (start, end, opts, cb) { // TODO: use same argument scheme as download
if (typeof end === 'function') return this.clear(start, start + 1, null, end)
if (typeof opts === 'function') return this.clear(start, end, null, opts)
if (!opts) opts = {}
if (!end) end = start + 1
if (!cb) cb = noop
// TODO: this needs some work. fx we can only calc byte offset for blocks we know about
// so internally we should make sure to only do that. We should use the merkle tree for this
var self = this
var byteOffset = start === 0 ? 0 : (typeof opts.byteOffset === 'number' ? opts.byteOffset : -1)
var byteLength = typeof opts.byteLength === 'number' ? opts.byteLength : -1
this.ready(function (err) {
if (err) return cb(err)
var modified = false
// TODO: use a buffer.fill thing here to speed this up!
for (var i = start; i < end; i++) {
if (self.bitfield.set(i, false)) modified = true
}
if (!modified) return process.nextTick(cb)
// TODO: write to a tmp/update file that we want to del this incase it crashes will del'ing
self._unannounce({start: start, length: end - start})
if (opts.delete === false || self._indexing) return sync()
if (byteOffset > -1) return onstartbytes(null, byteOffset)
self._storage.dataOffset(start, [], onstartbytes)
function sync () {
self.emit('clear', start, end)
self._sync(null, cb)
}
function onstartbytes (err, offset) {
if (err) return cb(err)
byteOffset = offset
if (byteLength > -1) return onendbytes(null, byteLength + byteOffset)
if (end === self.length) return onendbytes(null, self.byteLength)
self._storage.dataOffset(end, [], onendbytes)
}
function onendbytes (err, end) {
if (err) return cb(err)
if (!self._storage.data.del) return sync() // Not all data storage impls del
self._storage.data.del(byteOffset, end - byteOffset, sync)
}
})
}
Feed.prototype.signature = function (index, cb) {
if (typeof index === 'function') return this.signature(this.length - 1, index)
if (index < 0 || index >= this.length) return cb(new Error('No signature available for this index'))
this._storage.nextSignature(index, cb)
}
Feed.prototype.verify = function (index, signature, cb) {
var self = this
this.rootHashes(index, function (err, roots) {
if (err) return cb(err)
var checksum = crypto.tree(roots)
self.crypto.verify(checksum, signature, self.key, function (err, valid) {
if (err) return cb(err)
if (!valid) return cb(new Error('Signature verification failed'))
return cb(null, true)
})
})
}
Feed.prototype.rootHashes = function (index, cb) {
this._getRootsToVerify(index * 2 + 2, {}, [], cb)
}
Feed.prototype.seek = function (bytes, opts, cb) {
if (typeof opts === 'function') return this.seek(bytes, null, opts)
if (!opts) opts = {}
if (!this.opened) return this._readyAndSeek(bytes, opts, cb)
var self = this
if (bytes === this.byteLength) return process.nextTick(cb, null, this.length, 0)
this._seek(bytes, function (err, index, offset) {
if (!err && isBlock(index)) return done(index / 2, offset)
if (opts.wait === false) return cb(err || new Error('Unable to seek to this offset'))
var start = opts.start || 0
var end = opts.end || -1
if (!err) {
var left = flat.leftSpan(index) / 2
var right = flat.rightSpan(index) / 2 + 1
if (left > start) start = left
if (right < end || end === -1) end = right
}
if (end > -1 && end <= start) return cb(new Error('Unable to seek to this offset'))
var w = {
hash: opts.hash !== false,
bytes: bytes,
index: -1,
ifAvailable: opts && typeof opts.ifAvailable === 'boolean' ? opts.ifAvailable : self._alwaysIfAvailable,
start: start,
end: end,
want: toWantRange(start),
requested: 0,
callback: cb || noop
}
self._waiting.push(w)
self._updatePeers()
if (w.ifAvailable) self._ifAvailableSeek(w)
})
function done (index, offset) {
for (var i = 0; i < self.peers.length; i++) {
self.peers[i].haveBytes(bytes)
}
cb(null, index, offset)
}
}
Feed.prototype._ifAvailableSeek = function (w) {
var self = this
var cb = w.callback
process.nextTick(readyNT, this.ifAvailable, function () {
if (self.closed) return done(new Error('Closed'))
if (w.requested !== 0) return // inflight
done('Seek not available from peers')
})
function done (err) {
var i = self._waiting.indexOf(w)
if (i > -1) {
remove(self._waiting, i)
w.callback = noop
cb(err)
}
}
}
Feed.prototype._seek = function (offset, cb) {
if (offset === 0) return cb(null, 0, 0)
var self = this
var roots = flat.fullRoots(this.length * 2)
var nearestRoot = 0
loop(null, null)
function onroot (top) {
if (isBlock(top)) return cb(null, nearestRoot, offset)
var left = flat.leftChild(top)
while (!self.tree.get(left)) {
if (isBlock(left)) return cb(null, nearestRoot, offset)
left = flat.leftChild(left)
}
self._storage.getNode(left, onleftchild)
}
function onleftchild (err, node) {
if (err) return cb(err)
if (node.size > offset) {
nearestRoot = node.index
onroot(node.index)
} else {
offset -= node.size
if (flat.parent(node.index) === nearestRoot) {
nearestRoot = flat.sibling(node.index)
onroot(nearestRoot)
} else {
onroot(flat.sibling(node.index))
}
}
}
function loop (err, node) {
if (err) return cb(err)
if (node) {
if (node.size > offset) {
nearestRoot = node.index
return onroot(node.index)
}
offset -= node.size
}
if (!roots.length) return cb(new Error('Out of bounds'))
self._storage.getNode(roots.shift(), loop)
}
}
Feed.prototype._readyAndSeek = function (bytes, opts, cb) {
var self = this
this.ready(function (err) {
if (err) return cb(err)
self.seek(bytes, opts, cb)
})
}
Feed.prototype._getBuffer = function (index, cb) {
this._storage.getData(index, cb)
}
Feed.prototype._putBuffer = function (index, data, proof, from, cb) {
// TODO: this nodes in proof are not instances of our Node prototype
// but just similar. Check if this has any v8 perf implications.
// TODO: if the proof contains a valid signature BUT fails, emit a critical error
// --> feed should be considered dead
var self = this
var trusted = -1
var missing = []
var next = 2 * index
var i = data ? 0 : 1
while (true) {
if (this.tree.get(next)) {
trusted = next
break
}
var sib = flat.sibling(next)
next = flat.parent(next)
if (i < proof.nodes.length && proof.nodes[i].index === sib) {
i++
continue
}
if (!this.tree.get(sib)) break
missing.push(sib)
}
if (trusted === -1 && this.tree.get(next)) trusted = next
var error = null
var trustedNode = null
var missingNodes = new Array(missing.length)
var pending = missing.length + (trusted > -1 ? 1 : 0)
for (i = 0; i < missing.length; i++) this._storage.getNode(missing[i], onmissing)
if (trusted > -1) this._storage.getNode(trusted, ontrusted)
if (!missing.length && trusted === -1) onmissingloaded(null)
function ontrusted (err, node) {
if (err) error = err
if (node) trustedNode = node
if (!--pending) onmissingloaded(error)
}
function onmissing (err, node) {
if (err) error = err
if (node) missingNodes[missing.indexOf(node.index)] = node
if (!--pending) onmissingloaded(error)
}
function onmissingloaded (err) {
if (err) return cb(err)
self._verifyAndWrite(index, data, proof, missingNodes, trustedNode, from, cb)
}
}
Feed.prototype._readyAndPut = function (index, data, proof, cb) {
var self = this
this.ready(function (err) {
if (err) return cb(err)
self.put(index, data, proof, cb)
})
}
Feed.prototype._write = function (index, data, nodes, sig, from, cb) {
if (!this._onwrite) return this._writeAfterHook(index, data, nodes, sig, from, cb)
this._onwrite(index, data, from, writeHookDone(this, index, data, nodes, sig, from, cb))
}
function writeHookDone (self, index, data, nodes, sig, from, cb) {
return function (err) {
if (err) return cb(err)
self._writeAfterHook(index, data, nodes, sig, from, cb)
}
}
Feed.prototype._writeAfterHook = function (index, data, nodes, sig, from, cb) {
var self = this
var pending = nodes.length + 1 + (sig ? 1 : 0)
var error = null
for (var i = 0; i < nodes.length; i++) this._storage.putNode(nodes[i].index, nodes[i], ondone)
if (data) this._storage.putData(index, data, nodes, ondone)
else ondone()
if (sig) this._storage.putSignature(sig.index, sig.signature, ondone)
function ondone (err) {
if (err) error = err
if (--pending) return
if (error) return cb(error)
self._writeDone(index, data, nodes, from, cb)
}
}
Feed.prototype._writeDone = function (index, data, nodes, from, cb) {
for (var i = 0; i < nodes.length; i++) this.tree.set(nodes[i].index)
this.tree.set(2 * index)
if (data) {
if (this.bitfield.set(index, true)) {
if (this._stats) {
this._stats.downloadedBlocks += 1
this._stats.downloadedBytes += data.length
}
this.emit('download', index, data, from)
}
if (this.peers.length) this._announce({start: index}, from)
if (!this.writable) {
if (!this._synced) this._synced = this.bitfield.iterator(0, this.length)
if (this._synced.next() === -1) {
this._synced.range(0, this.length)
this._synced.seek(0)
if (this._synced.next() === -1) {
this.emit('sync')
}
}
}
}
this._sync(null, cb)
}
Feed.prototype._verifyAndWrite = function (index, data, proof, localNodes, trustedNode, from, cb) {
var visited = []
var remoteNodes = proof.nodes
var top = data ? new storage.Node(2 * index, crypto.data(data), data.length) : remoteNodes.shift()
// check if we already have the hash for this node
if (verifyNode(trustedNode, top)) {
this._write(index, data, visited, null, from, cb)
return
}
// keep hashing with siblings until we reach or trusted node
while (true) {
var node = null
var next = flat.sibling(top.index)
if (remoteNodes.length && remoteNodes[0].index === next) {
node = remoteNodes.shift()
visited.push(node)
} else if (localNodes.length && localNodes[0].index === next) {
node = localNodes.shift()
} else {
// we cannot create another parent, i.e. these nodes must be roots in the tree
this._verifyRootsAndWrite(index, data, top, proof, visited, from, cb)
return
}
visited.push(top)
top = new storage.Node(flat.parent(top.index), crypto.parent(top, node), top.size + node.size)