hypercore 11.39.6 → 11.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -551,16 +551,17 @@ class Hypercore extends EventEmitter {
551
551
  this.state.removeSession(this)
552
552
  this._removeSession()
553
553
 
554
- this.readable = false
555
- this.writable = false
556
- this.opened = false
557
-
558
554
  const gc = []
559
555
  for (const ext of this.extensions.values()) {
560
556
  if (ext.session === this) gc.push(ext)
561
557
  }
562
558
  for (const ext of gc) ext.destroy()
563
559
 
560
+ this.readable = false
561
+ this.writable = false
562
+ // needs to be below extension gc as `.peers` gates on `.opened`
563
+ this.opened = false
564
+
564
565
  this.core.replicator.findingPeers -= this._findingPeers
565
566
  this.core.replicator.clearRequests(this.activeRequests, error)
566
567
  this.core.replicator.updateActivity(this._active ? -1 : 0)
package/lib/core.js CHANGED
@@ -795,6 +795,18 @@ module.exports = class Core {
795
795
  // but this is easy atm (and the above layer will just retry)
796
796
  if (proof.fork !== this.state.fork) return false
797
797
 
798
+ if (proof.upgrade && proof.upgrade.start !== this.state.length) {
799
+ const length = this.state.length
800
+ proof = await MerkleTree.refit(this.state, proof)
801
+
802
+ // the nodes it carries cannot bridge our current length. the proof is not invalid, just not applicable to us
803
+ if (proof === null) return false
804
+
805
+ // refitting yields, so the tree may have moved under us.
806
+ // note that commitable() cannot catch this as it samples the fork after the fact
807
+ if (this.state.fork !== proof.fork || this.state.length !== length) return false
808
+ }
809
+
798
810
  const batch = await MerkleTree.verify(this.state, proof)
799
811
 
800
812
  if (batch.upgraded && batch.length <= this.state.length) {
@@ -3,6 +3,7 @@ const crypto = require('hypercore-crypto')
3
3
  const b4a = require('b4a')
4
4
  const unslab = require('unslab')
5
5
  const caps = require('./caps')
6
+ const safetyCatch = require('safety-catch')
6
7
  const {
7
8
  INVALID_PROOF,
8
9
  INVALID_CHECKSUM,
@@ -11,21 +12,35 @@ const {
11
12
  ASSERTION
12
13
  } = require('hypercore-errors')
13
14
 
15
+ // the length can be 2 ** 64 in practice, but js numbers limit it to 2 ** 52
16
+ const MAX_LENGTH = 2 ** 52
17
+ // a proof needs at most two nodes per level, for the 64 levels a tree can have
18
+ const MAX_NODES = 2 * 64
19
+
14
20
  class NodeQueue {
15
- constructor(nodes, extra = null) {
21
+ constructor(nodes, root = null) {
16
22
  this.i = 0
17
23
  this.nodes = nodes
18
- this.extra = extra
19
- this.length = nodes.length + (this.extra === null ? 0 : 1)
24
+ this.root = root
25
+ this.length = nodes.length + (this.root === null ? 0 : 1)
26
+ }
27
+
28
+ peek(index) {
29
+ if (this.root !== null && this.root.index === index) return this.root
30
+ if (this.i < this.nodes.length && this.nodes[this.i].index === index) return this.nodes[this.i]
31
+ return null
32
+ }
33
+
34
+ shiftRoot() {
35
+ if (this.root === null) return null
36
+ const node = this.root
37
+ this.root = null
38
+ this.length--
39
+ return node
20
40
  }
21
41
 
22
42
  shift(index) {
23
- if (this.extra !== null && this.extra.index === index) {
24
- const node = this.extra
25
- this.extra = null
26
- this.length--
27
- return node
28
- }
43
+ if (this.root !== null && this.root.index === index) return this.shiftRoot()
29
44
 
30
45
  if (this.i >= this.nodes.length) {
31
46
  throw INVALID_OPERATION('Expected node ' + index + ', got (nil)')
@@ -167,8 +182,8 @@ class MerkleTreeBatch {
167
182
  }
168
183
 
169
184
  // deprecated, use sssion proof instead
170
- proof(batch, { block, hash, seek, upgrade }) {
171
- return generateProof(this.session, batch, block, hash, seek, upgrade)
185
+ proof(batch, req) {
186
+ return MerkleTree.proof(this.session, batch, req)
172
187
  }
173
188
 
174
189
  verifyUpgrade(proof) {
@@ -490,9 +505,14 @@ class ByteSeeker {
490
505
  }
491
506
 
492
507
  class TreeProof {
493
- constructor(session, block, hash, seek, upgrade) {
508
+ constructor(session, rx, { block = null, hash = null, seek = null, upgrade = null } = {}) {
509
+ this.session = session
510
+ this.rx = rx
511
+
494
512
  this.fork = session.fork
495
513
  this.signature = session.signature
514
+ this.length = session.length
515
+ this.prologue = session.prologue
496
516
 
497
517
  this.block = block
498
518
  this.hash = hash
@@ -507,9 +527,72 @@ class TreeProof {
507
527
  }
508
528
  }
509
529
 
530
+ getTreeNode(index) {
531
+ return this.rx.getTreeNode(index)
532
+ }
533
+
534
+ async generate() {
535
+ // Important that this does not throw inbetween making the promise arrays
536
+ // and settle being called, otherwise there will be lingering promises in the background
537
+
538
+ const { block, hash, seek, upgrade } = this
539
+
540
+ if (this.prologue && upgrade) {
541
+ upgrade.start = upgrade.start < this.prologue.length ? 0 : upgrade.start
542
+ upgrade.length = upgrade.start < this.prologue.length ? this.prologue.length : upgrade.length
543
+ }
544
+
545
+ const head = 2 * this.length
546
+ const from = upgrade ? upgrade.start * 2 : 0
547
+ const to = upgrade ? from + upgrade.length * 2 : head
548
+ const node = normalizeIndexed(block, hash)
549
+
550
+ // can't do anything as we have no data...
551
+ if (head === 0) {
552
+ this.block = this.hash = this.seek = this.upgrade = null
553
+ return this
554
+ }
555
+
556
+ if (from >= to || to > head) {
557
+ throw INVALID_OPERATION('Invalid upgrade')
558
+ }
559
+ if (seek && upgrade && node !== null && node.index >= from) {
560
+ throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
561
+ }
562
+
563
+ let subTree = head
564
+
565
+ if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
566
+ subTree = nodesToRoot(node.index, node.nodes, to)
567
+ const seekRoot = seek
568
+ ? await seekUntrustedTree(this.session, subTree, seek.bytes, seek.padding)
569
+ : head
570
+ blockAndSeekProof(this, node, seek, seekRoot, subTree)
571
+ } else if ((node || seek) && upgrade) {
572
+ subTree = seek ? await seekFromHead(this.session, to, seek.bytes, seek.padding) : node.index
573
+ }
574
+
575
+ if (upgrade) {
576
+ const pending = this.pending
577
+
578
+ pending.upgrade = []
579
+ upgradeProof(this, node, seek, from, to, subTree, pending.upgrade)
580
+
581
+ if (head > to) {
582
+ pending.additionalUpgrade = []
583
+ upgradeProof(this, node, seek, to, head, seek ? head : subTree, pending.additionalUpgrade)
584
+ }
585
+ }
586
+
587
+ return this
588
+ }
589
+
510
590
  async settle() {
511
591
  const result = {
512
592
  fork: this.fork,
593
+ // the tree length proof was generated at, aak the length it upgrades the receiver to
594
+ // local only, never sent on the wire
595
+ coreLength: this.length,
513
596
  block: null,
514
597
  hash: null,
515
598
  seek: null,
@@ -555,6 +638,61 @@ class TreeProof {
555
638
  }
556
639
  }
557
640
 
641
+ // generates a proof from our current length using only the nodes carried by an existing proof
642
+ class RefitTreeProof extends TreeProof {
643
+ constructor(session, proof) {
644
+ super(session, null, {
645
+ block: proof.block ? { index: proof.block.index, nodes: 0 } : null,
646
+ hash: proof.hash ? { index: proof.hash.index, nodes: 0 } : null
647
+ })
648
+
649
+ this.insufficient = false
650
+
651
+ if (hasTooManyNodes(proof)) throw INVALID_OPERATION('Too many nodes')
652
+
653
+ const nodes = []
654
+ verifyTree(proof, nodes)
655
+ nodes.push(...proof.upgrade.nodes, ...proof.upgrade.additionalNodes)
656
+
657
+ this.nodes = new Map()
658
+
659
+ let length = 0
660
+
661
+ for (const node of nodes) {
662
+ this.nodes.set(node.index, node)
663
+ length = Math.max(length, flat.rightSpan(node.index) / 2 + 1)
664
+ }
665
+
666
+ if (length > MAX_LENGTH) throw INVALID_OPERATION('Upgrade is out of bounds')
667
+
668
+ if (length > this.length) {
669
+ this.upgrade = { start: this.length, length: length - this.length }
670
+ this.length = length
671
+ this.signature = proof.upgrade.signature
672
+ }
673
+ }
674
+
675
+ getTreeNode(index) {
676
+ if (!this.nodes.has(index)) {
677
+ this.insufficient = true
678
+ return Promise.resolve(null)
679
+ }
680
+
681
+ return Promise.resolve(this.nodes.get(index))
682
+ }
683
+
684
+ async generate() {
685
+ const indexed = this.block || this.hash
686
+
687
+ if (indexed) {
688
+ const index = this.block ? 2 * this.block.index : this.hash.index
689
+ indexed.nodes = await MerkleTree.missingNodes(this.session, index, this.session.length)
690
+ }
691
+
692
+ return super.generate()
693
+ }
694
+ }
695
+
558
696
  class MerkleTree {
559
697
  static hash(s) {
560
698
  return unslab(crypto.tree(s.roots))
@@ -711,8 +849,31 @@ class MerkleTree {
711
849
  return batch
712
850
  }
713
851
 
714
- static proof(session, rx, { block, hash, seek, upgrade }) {
715
- return generateProof(session, rx, block, hash, seek, upgrade)
852
+ static proof(session, rx, req) {
853
+ return new TreeProof(session, rx, req).generate()
854
+ }
855
+
856
+ // rewrite a proof as if it was requested from our current length, using only the nodes it
857
+ // carries. returns the original proof if no rewrite is needed, or null if the nodes it
858
+ // carries are not sufficient, ie the proof cannot be applied at our current length
859
+ static async refit(session, proof) {
860
+ if (!proof.upgrade || proof.seek || proof.upgrade.start === session.length) return proof
861
+
862
+ let refitted = null
863
+
864
+ const p = new RefitTreeProof(session, proof)
865
+ try {
866
+ refitted = await (await p.generate()).settle()
867
+ } catch (err) {
868
+ if (!p.insufficient) throw err
869
+ safetyCatch(err)
870
+ return null
871
+ }
872
+
873
+ if (refitted.block) refitted.block.value = proof.block.value
874
+ refitted.manifest = proof.manifest
875
+
876
+ return refitted
716
877
  }
717
878
 
718
879
  static maxMissingNodes(index, length) {
@@ -773,18 +934,6 @@ class MerkleTree {
773
934
  rx.tryFlush()
774
935
  return Promise.all([offset, size])
775
936
  }
776
-
777
- static upgradeLength(proof) {
778
- const extra = proof.additionalNodes
779
-
780
- if (extra.length) {
781
- const last = extra[extra.length - 1]
782
- const index = flat.rightSpan(last.index)
783
- return index / 2 + 1
784
- }
785
-
786
- return proof.start + proof.length
787
- }
788
937
  }
789
938
 
790
939
  module.exports = {
@@ -971,31 +1120,31 @@ function verifyUpgrade({ fork, upgrade }, blockRoot, batch) {
971
1120
  }
972
1121
  }
973
1122
 
974
- const extra = upgrade.additionalNodes
1123
+ // move the root to the additionalNodes queue if the block is past the upgrade,
1124
+ // since its relevant for the additionalNodes queue if so
1125
+ const root = q.root !== null && q.root.index >= to ? q.shiftRoot() : null
1126
+ const additional = new NodeQueue(upgrade.additionalNodes, root)
975
1127
 
976
1128
  ite.seek(batch.roots[batch.roots.length - 1].index)
977
- i = 0
978
1129
 
979
- while (i < extra.length && extra[i].index === ite.sibling()) {
980
- batch.appendRoot(extra[i++], ite)
1130
+ while (additional.length > 0 && additional.peek(ite.sibling()) !== null) {
1131
+ batch.appendRoot(additional.shift(ite.index), ite)
981
1132
  }
982
1133
 
983
- while (i < extra.length) {
984
- const node = extra[i++]
985
-
986
- while (node.index !== ite.index) {
987
- if (ite.factor === 2) throw INVALID_OPERATION('Unexpected node: ' + node.index)
1134
+ while (additional.length > 0) {
1135
+ while (additional.peek(ite.index) === null) {
1136
+ if (ite.factor === 2) throw INVALID_OPERATION('Unexpected additional node')
988
1137
  ite.leftChild()
989
1138
  }
990
1139
 
991
- batch.appendRoot(node, ite)
1140
+ batch.appendRoot(additional.shift(ite.index), ite)
992
1141
  ite.sibling()
993
1142
  }
994
1143
 
995
1144
  batch.signature = unslab(upgrade.signature)
996
1145
  batch.fork = fork
997
1146
 
998
- return q.extra === null
1147
+ return q.root === null
999
1148
  }
1000
1149
 
1001
1150
  async function seekFromHead(session, head, bytes, padding) {
@@ -1068,29 +1217,31 @@ async function seekUntrustedTree(session, root, bytes, padding) {
1068
1217
  // Note, that all these methods are sync as we can statically infer which nodes
1069
1218
  // are needed for the remote to verify given they arguments they passed us
1070
1219
 
1071
- function seekProof(session, rx, seekRoot, root, p) {
1220
+ function seekProof(proof, seekRoot, root) {
1221
+ const p = proof.pending
1072
1222
  const ite = flat.iterator(seekRoot)
1073
1223
  let cnt = 0
1074
1224
 
1075
1225
  p.seek = []
1076
- p.seek.push(getTreeNodeOrError(rx, ite.index))
1226
+ p.seek.push(getTreeNodeOrError(proof, ite.index))
1077
1227
 
1078
1228
  while (ite.index !== root) {
1079
1229
  if (++cnt >= 1024) throw ASSERTION('Bad seekProof seekRoot=' + seekRoot + ', root=' + root)
1080
1230
  ite.sibling()
1081
- p.seek.push(getTreeNodeOrError(rx, ite.index))
1231
+ p.seek.push(getTreeNodeOrError(proof, ite.index))
1082
1232
  ite.parent()
1083
1233
  }
1084
1234
  }
1085
1235
 
1086
- function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
1087
- if (!node) return seekProof(session, rx, seekRoot, root, p)
1236
+ function blockAndSeekProof(proof, node, seek, seekRoot, root) {
1237
+ if (!node) return seekProof(proof, seekRoot, root)
1088
1238
 
1239
+ const p = proof.pending
1089
1240
  const ite = flat.iterator(node.index)
1090
1241
  let cnt = 0
1091
1242
 
1092
1243
  p.node = []
1093
- if (!node.value) p.node.push(getTreeNodeOrError(rx, ite.index))
1244
+ if (!node.value) p.node.push(getTreeNodeOrError(proof, ite.index))
1094
1245
 
1095
1246
  while (ite.index !== root) {
1096
1247
  if (++cnt >= 1024) {
@@ -1099,25 +1250,26 @@ function blockAndSeekProof(session, rx, node, seek, seekRoot, root, p) {
1099
1250
  ite.sibling()
1100
1251
 
1101
1252
  if (seek && ite.contains(seekRoot) && ite.index !== seekRoot) {
1102
- seekProof(session, rx, seekRoot, ite.index, p)
1253
+ seekProof(proof, seekRoot, ite.index)
1103
1254
  } else {
1104
- p.node.push(getTreeNodeOrError(rx, ite.index))
1255
+ p.node.push(getTreeNodeOrError(proof, ite.index))
1105
1256
  }
1106
1257
 
1107
1258
  ite.parent()
1108
1259
  }
1109
1260
  }
1110
1261
 
1111
- function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
1112
- if (from === 0) p.upgrade = []
1262
+ function upgradeProof(proof, node, seek, from, to, subTree, nodes) {
1263
+ const p = proof.pending
1264
+ let connected = from === 0
1113
1265
 
1114
1266
  for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
1115
1267
  // check if they already have the node
1116
1268
  if (ite.index + ite.factor / 2 < from) continue
1117
1269
 
1118
1270
  // connect existing tree
1119
- if (p.upgrade === null && ite.contains(from - 2)) {
1120
- p.upgrade = []
1271
+ if (!connected && ite.contains(from - 2)) {
1272
+ connected = true
1121
1273
 
1122
1274
  const root = ite.index
1123
1275
  const target = from - 2
@@ -1131,9 +1283,9 @@ function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
1131
1283
  ite.sibling()
1132
1284
  if (ite.index > target) {
1133
1285
  if (p.node === null && p.seek === null && ite.contains(subTree)) {
1134
- blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
1286
+ blockAndSeekProof(proof, node, seek, subTree, ite.index)
1135
1287
  } else {
1136
- p.upgrade.push(getTreeNodeOrError(rx, ite.index))
1288
+ nodes.push(getTreeNodeOrError(proof, ite.index))
1137
1289
  }
1138
1290
  }
1139
1291
  ite.parent()
@@ -1142,62 +1294,25 @@ function upgradeProof(session, rx, node, seek, from, to, subTree, p) {
1142
1294
  continue
1143
1295
  }
1144
1296
 
1145
- if (p.upgrade === null) {
1146
- p.upgrade = []
1147
- }
1297
+ connected = true
1148
1298
 
1149
1299
  // if the subtree included is a child of this tree, include that one
1150
1300
  // instead of a dup node
1151
1301
  if (p.node === null && p.seek === null && ite.contains(subTree)) {
1152
- blockAndSeekProof(session, rx, node, seek, subTree, ite.index, p)
1302
+ blockAndSeekProof(proof, node, seek, subTree, ite.index)
1153
1303
  continue
1154
1304
  }
1155
1305
 
1156
1306
  // add root (can be optimised since the root might be in tree.roots)
1157
- p.upgrade.push(getTreeNodeOrError(rx, ite.index))
1307
+ nodes.push(getTreeNodeOrError(proof, ite.index))
1158
1308
  }
1159
1309
  }
1160
1310
 
1161
- function additionalUpgradeProof(session, rx, from, to, p) {
1162
- if (from === 0) p.additionalUpgrade = []
1163
-
1164
- for (const ite = flat.iterator(0); ite.fullRoot(to); ite.nextTree()) {
1165
- // check if they already have the node
1166
- if (ite.index + ite.factor / 2 < from) continue
1167
-
1168
- // connect existing tree
1169
- if (p.additionalUpgrade === null && ite.contains(from - 2)) {
1170
- p.additionalUpgrade = []
1171
-
1172
- const root = ite.index
1173
- const target = from - 2
1174
- let cnt = 0
1175
-
1176
- ite.seek(target)
1177
-
1178
- while (ite.index !== root) {
1179
- if (++cnt >= 1024) {
1180
- throw ASSERTION(
1181
- 'Bad arguments to additionalUpgradeProof root=' + root + ' target=' + target
1182
- )
1183
- }
1184
- ite.sibling()
1185
- if (ite.index > target) {
1186
- p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
1187
- }
1188
- ite.parent()
1189
- }
1190
-
1191
- continue
1192
- }
1193
-
1194
- if (p.additionalUpgrade === null) {
1195
- p.additionalUpgrade = []
1196
- }
1197
-
1198
- // add root (can be optimised since the root is in tree.roots)
1199
- p.additionalUpgrade.push(getTreeNodeOrError(rx, ite.index))
1200
- }
1311
+ function hasTooManyNodes(proof) {
1312
+ if (proof.block && proof.block.nodes.length > MAX_NODES) return true
1313
+ if (proof.hash && proof.hash.nodes.length > MAX_NODES) return true
1314
+ if (!proof.upgrade) return false
1315
+ return proof.upgrade.nodes.length > MAX_NODES || proof.upgrade.additionalNodes.length > MAX_NODES
1201
1316
  }
1202
1317
 
1203
1318
  function nodesToRoot(index, nodes, head) {
@@ -1310,54 +1425,6 @@ async function settleProof(p) {
1310
1425
  }
1311
1426
  }
1312
1427
 
1313
- // tree can be either the merkle tree or a merkle tree batch
1314
- async function generateProof(session, rx, block, hash, seek, upgrade) {
1315
- // Important that this does not throw inbetween making the promise arrays
1316
- // and finalise being called, otherwise there will be lingering promises in the background
1317
-
1318
- if (session.prologue && upgrade) {
1319
- upgrade.start = upgrade.start < session.prologue.length ? 0 : upgrade.start
1320
- upgrade.length =
1321
- upgrade.start < session.prologue.length ? session.prologue.length : upgrade.length
1322
- }
1323
-
1324
- const head = 2 * session.length
1325
- const from = upgrade ? upgrade.start * 2 : 0
1326
- const to = upgrade ? from + upgrade.length * 2 : head
1327
- const node = normalizeIndexed(block, hash)
1328
-
1329
- // can't do anything as we have no data...
1330
- if (head === 0) return new TreeProof(session, null, null, null, null)
1331
-
1332
- if (from >= to || to > head) {
1333
- throw INVALID_OPERATION('Invalid upgrade')
1334
- }
1335
- if (seek && upgrade && node !== null && node.index >= from) {
1336
- throw INVALID_OPERATION('Cannot both do a seek and block/hash request when upgrading')
1337
- }
1338
-
1339
- let subTree = head
1340
-
1341
- const p = new TreeProof(session, block, hash, seek, upgrade)
1342
-
1343
- if (node !== null && (!upgrade || node.lastIndex < upgrade.start)) {
1344
- subTree = nodesToRoot(node.index, node.nodes, to)
1345
- const seekRoot = seek
1346
- ? await seekUntrustedTree(session, subTree, seek.bytes, seek.padding)
1347
- : head
1348
- blockAndSeekProof(session, rx, node, seek, seekRoot, subTree, p.pending)
1349
- } else if ((node || seek) && upgrade) {
1350
- subTree = seek ? await seekFromHead(session, to, seek.bytes, seek.padding) : node.index
1351
- }
1352
-
1353
- if (upgrade) {
1354
- upgradeProof(session, rx, node, seek, from, to, subTree, p.pending)
1355
- if (head > to) additionalUpgradeProof(session, rx, to, head, p.pending)
1356
- }
1357
-
1358
- return p
1359
- }
1360
-
1361
1428
  function getUnpaddedSize(node, padding, ite) {
1362
1429
  return padding === 0
1363
1430
  ? node.size
package/lib/replicator.js CHANGED
@@ -1110,7 +1110,7 @@ class Peer {
1110
1110
  return
1111
1111
  }
1112
1112
 
1113
- if (!this.isActive() && proof.block !== null) {
1113
+ if (!this.isActive() && proof !== null && proof.block !== null) {
1114
1114
  return
1115
1115
  }
1116
1116
 
@@ -1138,9 +1138,8 @@ class Peer {
1138
1138
  this.replicator._onupload(proof.block.index, proof.block.value.byteLength, this)
1139
1139
  }
1140
1140
 
1141
- if (proof.upgrade) {
1142
- const remoteLength = MerkleTree.upgradeLength(proof.upgrade)
1143
- if (remoteLength > this.pushedLength) this.pushedLength = remoteLength
1141
+ if (proof.upgrade && proof.coreLength > this.pushedLength) {
1142
+ this.pushedLength = proof.coreLength
1144
1143
  }
1145
1144
 
1146
1145
  this.wireData.send({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hypercore",
3
- "version": "11.39.6",
3
+ "version": "11.40.1",
4
4
  "description": "Hypercore is a secure, distributed append-only log",
5
5
  "main": "index.js",
6
6
  "scripts": {