This repository has been archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathinit.js
315 lines (262 loc) · 8.54 KB
/
init.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
'use strict'
const log = require('debug')('ipfs:components:init')
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const mergeOptions = require('merge-options')
const promisify = require('promisify-es6')
const getDefaultConfig = require('../runtime/config-nodejs.js')
const createRepo = require('../runtime/repo-nodejs')
const Keychain = require('libp2p-keychain')
const NoKeychain = require('./no-keychain')
const GCLock = require('./pin/gc-lock')
const { DAGNode } = require('ipld-dag-pb')
const UnixFs = require('ipfs-unixfs')
const multicodec = require('multicodec')
const multiaddr = require('multiaddr')
const {
AlreadyInitializingError,
AlreadyInitializedError,
NotStartedError
} = require('../errors')
const BlockService = require('ipfs-block-service')
const Ipld = require('ipld')
const getDefaultIpldOptions = require('../runtime/ipld-nodejs')
const createPreloader = require('../preload')
const { ERR_REPO_NOT_INITIALIZED } = require('ipfs-repo').errors
const IPNS = require('../ipns')
const OfflineDatastore = require('../ipns/routing/offline-datastore')
const initAssets = require('../runtime/init-assets-nodejs')
const PinManager = require('./pin/pin-manager')
const Components = require('./')
module.exports = ({
apiManager,
print,
options: constructorOptions
}) => async function init (options) {
const { cancel } = apiManager.update({ init: () => { throw new AlreadyInitializingError() } })
try {
options = options || {}
if (typeof constructorOptions.init === 'object') {
options = mergeOptions(options, constructorOptions.init)
}
if (constructorOptions.pass) {
options.pass = constructorOptions.pass
}
if (constructorOptions.config) {
options.config = constructorOptions.config
}
const repo = typeof options.repo === 'string' || options.repo == null
? createRepo({ path: options.repo, autoMigrate: options.repoAutoMigrate })
: options.repo
let isInitialized = true
if (repo.closed) {
try {
await repo.open()
} catch (err) {
if (err.code === ERR_REPO_NOT_INITIALIZED) {
isInitialized = false
} else {
throw err
}
}
}
const { peerId, config, keychain } = isInitialized
? await initExistingRepo(repo, options)
: await initNewRepo(repo, options)
log('peer created')
const peerInfo = new PeerInfo(peerId)
if (config.Addresses && config.Addresses.Swarm) {
config.Addresses.Swarm.forEach(addr => {
let ma = multiaddr(addr)
if (ma.getPeerId()) {
ma = ma.encapsulate(`/p2p/${peerInfo.id.toB58String()}`)
}
peerInfo.multiaddrs.add(ma)
})
}
const blockService = new BlockService(repo)
const ipld = new Ipld(getDefaultIpldOptions(blockService, constructorOptions.ipld, log))
const preload = createPreloader(constructorOptions.preload)
await preload.start()
const gcLock = new GCLock(constructorOptions.repoOwner, {
// Make sure GCLock is specific to repo, for tests where there are
// multiple instances of IPFS
morticeId: repo.path
})
const dag = Components.legacy.dag({ _ipld: ipld, _preload: preload })
const object = Components.legacy.object({ _ipld: ipld, _preload: preload, dag, _gcLock: gcLock })
const pinManager = new PinManager(repo, dag)
await pinManager.load()
const pin = Components.legacy.pin({ _ipld: ipld, _preload: preload, object, _repo: repo, _pinManager: pinManager })
const add = Components.add({ ipld, dag, preload, pin, gcLock, options: constructorOptions })
if (!isInitialized && !options.emptyRepo) {
// add empty unixfs dir object (go-ipfs assumes this exists)
const emptyDirCid = await addEmptyDir({ dag })
log('adding default assets')
await initAssets({ add, print })
log('initializing IPNS keyspace')
// Setup the offline routing for IPNS.
// This is primarily used for offline ipns modifications, such as the initializeKeyspace feature.
const offlineDatastore = new OfflineDatastore(repo)
const ipns = new IPNS(offlineDatastore, repo.datastore, peerInfo, keychain, { pass: options.pass })
await ipns.initializeKeyspace(peerId.privKey.bytes, emptyDirCid.toString())
}
const api = createApi({
add,
apiManager,
constructorOptions,
blockService,
gcLock,
initOptions: options,
ipld,
keychain,
peerInfo,
pinManager,
preload,
print,
repo
})
apiManager.update(api, () => { throw new NotStartedError() })
} catch (err) {
cancel()
throw err
}
return apiManager.api
}
async function initNewRepo (repo, { privateKey, emptyRepo, bits, profiles, config, pass, print }) {
emptyRepo = emptyRepo || false
bits = bits == null ? 2048 : Number(bits)
config = mergeOptions(getDefaultConfig(), config)
config = applyProfiles(profiles, config)
// Verify repo does not exist yet
const exists = await repo.exists()
log('repo exists?', exists)
if (exists === true) {
throw new Error('repo already exists')
}
const peerId = await createPeerId({ privateKey, bits, print })
let keychain = new NoKeychain()
log('identity generated')
config.Identity = {
PeerID: peerId.toB58String(),
PrivKey: peerId.privKey.bytes.toString('base64')
}
privateKey = peerId.privKey
config.Keychain = Keychain.generateOptions()
log('peer identity: %s', config.Identity.PeerID)
await repo.init(config)
await repo.open()
log('repo opened')
if (pass) {
log('creating keychain')
const keychainOptions = { passPhrase: pass, ...config.Keychain }
keychain = new Keychain(repo.keys, keychainOptions)
await keychain.importPeer('self', { privKey: privateKey })
}
return { peerId, keychain, config }
}
async function initExistingRepo (repo, { config: newConfig, profiles, pass }) {
let config = await repo.config.get()
if (newConfig || profiles) {
if (newConfig) {
config = mergeOptions(config, newConfig)
}
if (profiles) {
config = applyProfiles(profiles, config)
}
await repo.config.set(config)
}
let keychain = new NoKeychain()
if (pass) {
const keychainOptions = { passPhrase: pass, ...config.Keychain }
keychain = new Keychain(repo.keys, keychainOptions)
log('keychain constructed')
}
const peerId = await promisify(PeerId.createFromPrivKey)(config.Identity.PrivKey)
// Import the private key as 'self', if needed.
if (pass) {
try {
await keychain.findKeyByName('self')
} catch (err) {
log('Creating "self" key')
await keychain.importPeer('self', peerId)
}
}
return { peerId, keychain, config }
}
function createPeerId ({ privateKey, bits, print }) {
if (privateKey) {
log('using user-supplied private-key')
return typeof privateKey === 'object'
? privateKey
: promisify(PeerId.createFromPrivKey)(Buffer.from(privateKey, 'base64'))
} else {
// Generate peer identity keypair + transform to desired format + add to config.
print('generating %s-bit RSA keypair...', bits)
return promisify(PeerId.create)({ bits })
}
}
async function addEmptyDir ({ dag }) {
const node = new DAGNode(new UnixFs('directory').marshal())
return dag.put(node, {
version: 0,
format: multicodec.DAG_PB,
hashAlg: multicodec.SHA2_256,
preload: false
})
}
// Apply profiles (e.g. ['server', 'lowpower']) to config
function applyProfiles (profiles, config) {
return (profiles || []).reduce((name, config) => {
const profile = require('./config').profiles[name]
if (!profile) {
throw new Error(`No profile with name '${name}'`)
}
log('applying profile %s', name)
return profile.transform(config)
})
}
function createApi ({
add,
apiManager,
constructorOptions,
blockService,
gcLock,
initOptions,
ipld,
keychain,
peerInfo,
pinManager,
preload,
print,
repo
}) {
const refs = () => { throw new NotStartedError() }
refs.local = Components.refs.local({ repo })
const api = {
add,
cat: Components.cat({ ipld, preload }),
config: Components.config({ repo }),
dns: Components.dns(),
get: Components.get({ ipld, preload }),
init: () => { throw new AlreadyInitializedError() },
isOnline: Components.isOnline({}),
ls: Components.ls({ ipld, preload }),
refs,
start: Components.start({
apiManager,
options: constructorOptions,
blockService,
gcLock,
initOptions,
ipld,
keychain,
peerInfo,
pinManager,
preload,
print,
repo
})
}
return api
}