-
Notifications
You must be signed in to change notification settings - Fork 0
/
commit.js
368 lines (324 loc) · 8.55 KB
/
commit.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
/* eslint-disable no-await-in-loop */
const debug = require('debug')('ara-filesystem:commit')
const { createAFSKeyPath } = require('./key-path')
const storage = require('ara-contracts/storage')
const pify = require('pify')
const fs = require('fs')
const {
proxyExists,
getProxyAddress
} = require('ara-contracts/registry')
const {
AID_PREFIX,
STAGED_FILE,
METADATA_TREE_NAME,
METADATA_TREE_INDEX,
METADATA_SIGNATURES_NAME,
METADATA_SIGNATURES_INDEX
} = require('./constants')
const {
getDocumentOwner,
validate,
web3: {
account
},
transform: {
toHexString
}
} = require('ara-util')
const { setPrice } = require('./price')
const {
resolve,
dirname
} = require('path')
/**
* Commits the AFS with the given Ara identity
* @param {Object} opts
* @param {String} opts.did
* @param {String} opts.password
* @param {String} opts.afsPassword
* @param {Boolean} opts.estimate
* @param {String} opts.estimateDid
* @param {Number} opts.price
* @param {Object} [opts.keyringOpts]
* @param {Number} [opts.gasPrice]
* @param {Function} [opts.writeCallbacks.onhash]
* @param {Function} [opts.writeCallbacks.onreceipt]
* @param {Function} [opts.writeCallbacks.onconfirmation]
* @param {Function} [opts.writeCallbacks.onerror]
* @param {Function} [opts.writeCallbacks.onmined]
* @param {Function} [opts.priceCallbacks.onhash]
* @param {Function} [opts.priceCallbacks.onreceipt]
* @param {Function} [opts.priceCallbacks.onconfirmation]
* @param {Function} [opts.priceCallbacks.onerror]
* @param {Function} [opts.priceCallbacks.onmined]
* @return {Object}
*/
async function commit(opts) {
if (!opts || 'object' !== typeof opts) {
throw new TypeError('Expecting opts object.')
} else if ('string' !== typeof opts.did || !opts.did) {
throw new TypeError('Expecting non-empty string.')
} else if ('string' !== typeof opts.password || !opts.password) {
throw new TypeError('Expecting non-empty password.')
} else if (opts.afsPassword && 'string' !== typeof opts.afsPassword) {
throw new TypeError('Expecting non-empty password.')
} else if (opts.estimate && 'boolean' !== typeof opts.estimate) {
throw new TypeError('Expecting boolean.')
} else if (opts.estimateDid && 'string' !== typeof opts.estimateDid) {
throw new TypeError('Expecting non-empty string.')
} else if (opts.price && ('number' !== typeof opts.price || opts.price < 0)) {
throw new TypeError('Expecting whole number price.')
} else if (opts.gasPrice && ('number' !== typeof opts.gasPrice || opts.gasPrice < 0)) {
throw new TypeError(`Expected 'opts.gasPrice' to be a positive number. Got ${opts.gasPrice}.`)
}
let {
did,
estimate,
afsPassword,
estimateDid
} = opts
const {
password,
price,
keyringOpts,
gasPrice = 0,
writeCallbacks: {
onhash: writeonhash,
onreceipt: writeonreceipt,
onconfirmation: writeonconfirmation,
onerror: writeonerror,
onmined: writeonmined
} = {},
priceCallbacks: {
onhash: priceonhash,
onreceipt: priceonreceipt,
onconfirmation: priceonconfirmation,
onerror: priceonerror,
onmined: priceonmined
} = {},
} = opts
afsPassword = afsPassword || password
estimate = estimate || false
if (estimateDid && !estimate) {
estimateDid = null
}
let ddo
try {
({ did, ddo } = await validate({
did, password: afsPassword, label: 'commit', keyringOpts
}))
} catch (err) {
throw err
}
if (!(await proxyExists(estimateDid || did))) {
throw new Error('Proxy doesn\'t exist, please deploy a proxy for this AFS first.')
}
const proxy = await getProxyAddress(estimateDid || did)
debug('proxy address', proxy)
const path = generateStagedPath(did)
try {
await pify(fs.access)(path)
} catch (err) {
throw new Error('No staged commits ready to be pushed')
}
const contents = _readStagedFile(path)
const exists = await _hasBeenCommitted(contents, proxy)
const mtData = _getWriteData(0, contents, exists)
const msData = _getWriteData(1, contents, exists)
let owner = getDocumentOwner(ddo, true)
owner = `${AID_PREFIX}${owner}`
const acct = await account.load({ did: owner, password })
let result = await storage.write({
mtData,
msData,
account: acct,
to: proxy,
gasPrice,
onhash: writeonhash,
onreceipt: writeonreceipt,
onconfirmation: writeonconfirmation,
onerror: writeonerror,
onmined: writeonmined
}, estimate, exists)
if (estimate) {
if (0 < price) {
const setPriceGasCost = await setPrice({
did,
password,
afsPassword,
price,
gasPrice,
keyringOpts,
estimate: true,
estimateDid
})
result = Number(result) + Number(setPriceGasCost)
}
return result.toString()
}
await _deleteStagedFile(path)
if (0 < price) {
await setPrice({
did,
password,
price,
keyringOpts,
afsPassword,
gasPrice,
onhash: priceonhash,
onreceipt: priceonreceipt,
onconfirmation: priceonconfirmation,
onerror: priceonerror,
onmined: priceonmined
})
}
return result
}
function hasStaged(did) {
const path = resolve(createAFSKeyPath(did), STAGED_FILE)
try {
fs.accessSync(path)
return true
} catch (err) {
return false
}
}
function writeToStaged({
did,
fileIndex,
offset,
data
} = {}) {
const path = generateStagedPath(did)
_writeStagedFile({
fileIndex,
offset,
data,
path
})
}
function readFromStaged({
did,
fileIndex,
offset = 0
} = {}) {
const path = generateStagedPath(did)
const contents = _readStagedFile(path)
fileIndex = _getFilenameByIndex(fileIndex)
let result
if (contents[fileIndex] && contents[fileIndex][offset]) {
result = contents[fileIndex][offset]
}
return result
}
function generateStagedPath(did) {
const path = resolve(createAFSKeyPath(did), STAGED_FILE)
try {
fs.accessSync(path)
} catch (err) {
_makeStagedFile(path)
}
return path
}
function _getWriteData(index, contents, append) {
const map = contents[_getFilenameByIndex(index)]
let buffer = ''
const offsets = Object.keys(map).map(v => parseInt(v, 10))
const buffers = Object.values(map)
let result
if (!append) {
buffers.map((v, i) => {
buffer += v
const length = _hexToBytes(v.length)
// inserts 0s to fill buffer based on offsets
if (offsets[i + 1] && offsets[i + 1] !== _hexToBytes(buffer.length)) {
const diff = offsets[i + 1] - _hexToBytes(buffer.length)
buffer += toHexString(Buffer.alloc(diff))
}
return length
})
buffer = `0x${buffer}`
result = { buffer, offsets }
} else {
offsets.shift()
buffers.shift()
buffer = `0x${buffers.join('')}`
result = { offsets, buffer }
}
return result
}
function _hexToBytes(hex) {
return hex / 2
}
function _readStagedFile(path) {
const contents = fs.readFileSync(path, 'utf8')
return JSON.parse(contents)
}
function _writeStagedFile({
fileIndex,
offset,
data,
path
} = {}) {
let json = {}
try {
fs.accessSync(path)
json = _readStagedFile(path)
} catch (err) {
fs.writeFileSync(path, '')
}
const hex = data.toString('hex')
const filename = _getFilenameByIndex(fileIndex)
if (filename) {
if (!json[filename]) json[filename] = {}
json[filename][offset] = hex
const jsonString = JSON.stringify(json)
fs.writeFileSync(path, jsonString)
}
}
function _makeStagedFile(path) {
try {
fs.mkdirSync(dirname(path))
} catch (err) {
debug('could not make dir at', path, 'err', err)
}
}
async function _deleteStagedFile(path) {
try {
await pify(fs.unlink)(path)
} catch (err) {
debug('could not unlink', path)
}
}
// checks to see if header written to staged has been pushed to blockchain
// if it has, we know that AFS has been committed already
async function _hasBeenCommitted(contents, proxy) {
const buffer = `0x${_getBufferFromStaged(contents, 0, 0)}`
return storage.hasBuffer({
address: proxy,
fileIndex: 0,
offset: 0,
buffer
})
}
function _getBufferFromStaged(contents, index, offset) {
const map = contents[_getFilenameByIndex(index)]
return map[offset]
}
function _getFilenameByIndex(index) {
if (index === METADATA_TREE_INDEX) {
return METADATA_TREE_NAME
} else if (index === METADATA_SIGNATURES_INDEX) {
return METADATA_SIGNATURES_NAME
}
debug('index not recognized', index)
return null
}
module.exports = {
commit,
hasStaged,
writeToStaged,
readFromStaged,
generateStagedPath
}