forked from RangerMauve/hyper-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnative.js
More file actions
76 lines (66 loc) · 1.83 KB
/
native.js
File metadata and controls
76 lines (66 loc) · 1.83 KB
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
const SwarmNetworker = require('@corestore/networker')
const RAA = require('random-access-application')
const RAM = require('random-access-memory')
const HypercoreProtocol = require('hypercore-protocol')
const Corestore = require('corestore')
const SDK = require('./sdk')
const DEFAULT_SWARM_OPTS = {
extensions: [],
preferredPort: 42666
}
const DEFAULT_CORESTORE_OPTS = {
sparse: true
}
module.exports = async function createSDK (opts) {
return SDK({ ...opts, backend: nativeBackend })
}
module.exports.createBackend = nativeBackend
async function nativeBackend (opts) {
let {
storage,
corestore,
applicationName,
persist,
swarmOpts,
corestoreOpts
} = opts
// Derive storage if it isn't provided
// Don't derive if corestore was provided
if (!storage && !corestore) {
if (persist !== false) {
storage = RAA(applicationName)
} else {
// Nothing should be persisted. 🤷
storage = RAM
}
}
if (!corestore) {
corestore = new Corestore(
storage,
Object.assign({}, DEFAULT_CORESTORE_OPTS, corestoreOpts)
)
}
// The corestore needs to be opened before creating the swarm.
await corestore.ready()
// I think this is used to create a persisted identity?
// Needs to be created before the swarm so that it can be passed in
const noiseSeed = await deriveSecret(applicationName, 'replication-keypair')
const keyPair = HypercoreProtocol.keyPair(noiseSeed)
const swarm = new SwarmNetworker(corestore, Object.assign({ keyPair }, DEFAULT_SWARM_OPTS, swarmOpts))
return {
storage,
corestore,
swarm,
deriveSecret,
keyPair,
close
}
async function deriveSecret (namespace, name) {
return corestore.inner._deriveSecret(namespace, name)
}
function close (cb) {
corestore.close(() => {
swarm.close().then(cb, cb)
})
}
}