forked from CNXTEoEorg/uport-js-client
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
488 lines (432 loc) · 18.3 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
// Normalize library use, which dependencies/utils do we prefer
const { decodeToken, createUnsignedToken, SECP256K1Client, TokenSigner } = require('jsontokens')
const Transaction = require('ethereumjs-tx')
const util = require('ethereumjs-util')
const BN = util.BN
const txutils = require('eth-signer/dist/eth-signer-simple.js').txutils
const EthJS = require('ethjs-query');
const HttpProvider = require('ethjs-provider-http');
const UportLite = require('uport-lite')
const verifyJWT = require('uport').JWT.verifyJWT
const nets = require('nets')
const Contract = require('uport').Contract
const ethutil = require('ethereumjs-util')
const base58 = require('bs58')
const decodeEvent = require('ethjs-abi').decodeEvent
const SecureRandom = require('secure-random')
// TODO return to smaller lib
// const IPFS = require('ipfs-mini');
const IPFS = require('ipfs-api')
const isIPFS = require('is-ipfs')
const EthSigner = require('eth-signer')
const SimpleSigner = EthSigner.signers.SimpleSigner
const MIMProxySigner = EthSigner.signers.MIMProxySigner
const urlDecode = require('urldecode')
const fs = require('fs')
const deploy = require('./deploy.js')
const mnid = require('mnid')
const tryRequire = (path) => {
try {
return require(path)
} catch(err) {
return null
}
}
const uportIdentity = require('uport-identity')
const RegistryArtifact = require('uport-registry')
const MetaIdentityManagerArtifact = uportIdentity.MetaIdentityManager.v2
// TODO need to import identity manager Adresses
const networks = {
'mainnet': { id: '0x1',
registry: '0xab5c8051b9a1df1aab0149f8b0630848b7ecabf6',
rpcUrl: 'https://mainnet.infura.io' },
'ropsten': { id: '0x3',
registry: '0x41566e3a081f5032bdcad470adb797635ddfe1f0',
rpcUrl: 'https://ropsten.infura.io' },
'kovan': { id: '0x2a',
registry: '0x5f8e9351dc2d238fb878b6ae43aa740d62fc9758',
rpcUrl: 'https://kovan.infura.io' },
'rinkeby': { id: '0x4',
registry: '0x2cc31912b2b0f3075a87b3640923d45a26cef3ee',
rpcUrl: 'https://rinkeby.infura.io' }
}
const DEFAULTNETWORK = 'rinkeby'
const configNetwork = (net = DEFAULTNETWORK) => {
if (typeof net === 'object') {
['id', 'registry', 'rpcUrl'].forEach((key) => {
if (!net.hasOwnProperty(key)) throw new Error(`Malformed network config object, object must have '${key}' key specified.`)
})
return net
} else if (typeof net === 'string') {
if (!networks[net]) throw new Error(`Network configuration not available for '${net}'`)
return networks[net]
}
throw new Error(`Network configuration object or network string required`)
}
const genKeyPair = () => {
const privateKey = SecureRandom.randomBuffer(32)
const publicKey = ethutil.privateToPublic(privateKey)
return {
privateKey: `0x${privateKey.toString('hex')}`,
publicKey: `0x04${publicKey.toString('hex')}`,
address: `0x${ethutil.pubToAddress(publicKey).toString('hex')}`
}
}
const getUrlParams = (url) => (
url.match(/[^&?]*?=[^&?]*/g)
.map((param) => param.split('='))
.reduce((params, param) => {
params[param[0]] = param[1]
return params
}, {}))
const funcToData = (funcStr) => {
const name = funcStr.match(/.*\(/g)[0].slice(0, -1)
const [type, args] = funcStr.match(/\(.*\)/g)[0].slice(1, -1).split(',')
.map((str) => str.trim().split(' '))
.reduce((arrs, param) => {
arrs[0].push(param[0])
arrs[1].push(param[1])
return arrs
}, [[],[]])
return `0x${txutils._encodeFunctionTxData(name, type, args)}`
}
const intersection = (obj, arr) => Object.keys(obj).filter(key => arr.includes(key))
const filterCredentials = (credentials, keys) => [].concat.apply([], keys.map((key) => credentials[key].map((cred) => cred.jwt)))
const SimpleResponseHandler = (res, url) => new Promise((resolve, reject) => resolve(res))
const serialize = (uportClient) => {
// TODO covers most cases, but also deal with passed in config functions
const jsonClientState = {
id: uportClient.id,
network: uportClient.network,
info: uportClient.info,
credentials: uportClient.credentials,
ipfsConfig: uportClient.ipfsUrl,
deviceKeys: uportClient.deviceKeys,
recoveryKeys: uportClient.recoveryKeys,
mnid: uportClient.mnid,
initialized: uportClient.initialized
}
return JSON.stringify(jsonClientState)
}
const deserialize = (str) => {
const jsonClientState = JSON.parse(str)
const uportClient = new UPortClient(jsonClientState, { credentials: jsonClientState.credentials })
// Some of uport client could be refactored to handle this through configs, but won't change this interface once changed
uportClient.id = jsonClientState.id
uportClient.mnid = jsonClientState.mnid
uportClient.initTokenSigner()
uportClient.initSimpleSigner()
uportClient.initTransactionSigner(uportClient.metaIdentityManagerAddress)
return uportClient
}
const HTTPResponseHandler = (res, url) => {
// Chasqui specific
if(!url) return new Promise((resolve, reject) => resolve(res))
if (!!url.match(/chasqui.uport.me/g)) {
return new Promise((resolve, reject) => {
nets({
uri: urlDecode(url),
json: true,
method: 'GET',
withCredentials: false,
rejectUnauthorized: false
}, (err, resp, body) => {
if (err) reject(err)
post(res, url).then(resolve, reject)
})
})
}
return post(res, url)
}
const post = (res, url) => new Promise((resolve, reject) => {
nets({
body: JSON.stringify({access_token: res}),
url: urlDecode(url),
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
}, (err, resp, body) => {
if (err) reject(err)
resolve(resp)
})
})
const responseHandlers = {
'simple' : SimpleResponseHandler,
'http' : HTTPResponseHandler
}
const prommiseTimeOut = (msec) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, msec)
})
}
const configResponseHandler = (responseHandler = 'simple') => {
if ( typeof(responseHandler) === 'function') return responseHandler
if ( typeof(responseHandler) === 'string') {
if (!responseHandlers[responseHandler]) throw new Error(`Response handler configuration not available for '${net}'`)
return responseHandlers[responseHandler]
}
throw new Error(`Not a valid responseHandler`)
}
const isShareRequest = (uri) => !!uri.match(/:me\?.*requestToken/g)
const isSimpleRequest = (uri) => !!uri.match(/:me\?/g)
const isTransactionRequest = (uri) => !!uri.match(/:0[xX][0-9a-fA-F]+\?/g)
const isAddAttestationRequest = (uri) => !!uri.match(/add\?/g)
class UPortClient {
constructor(config = {}, initState = {}) {
// Handle this differently once there is a test and full client
this.responseHandler = configResponseHandler(config.responseHandler)
// {key: value, ...}
this.info = initState.info || { }
// this.credentials = {address: [{jwt: ..., json: ....}, ...], ...}
this.credentials = initState.credentials || { }
this.deviceKeys = config.deviceKeys
this.recoveryKeys = config.recoveryKeys
this.network = config.network ? configNetwork(config.network) : null // have some default connect/setup testrpc
if (this.network) {
// Eventually consume an ipfs api client or at least some wrapper that allows a mock to be passed in
this.ipfsUrl = config.ipfsConfig || 'https://ipfs.infura.io/ipfs/'
// ^ TODO better ipfs config, pass in opts after or url above
this.ipfs = new IPFS({ host: 'ipfs.infura.io', port: 5001, protocol: 'https' })
this.registryNetwork = {[this.network.id]: {registry: this.network.registry, rpcUrl: this.network.rpcUrl}}
const registry = config.registry || new UportLite({networks: this.registryNetwork, ipfsGw: this.ipfsUrl})
// TODO change this in uport-js or in uport-lite, should not be necessary
this.registry = (address) => new Promise((resolve, reject) => {
registry(address, (error, profile) => {
if (error) return reject(error)
resolve(profile)
})
})
this.verifyJWT = (jwt) => verifyJWT({registry: this.registry}, jwt)
this.provider = config.provider || new HttpProvider(this.network.rpcUrl);
this.ethjs = this.provider ? new EthJS(this.provider) : null;
// TODO how to config this
this.registryAddress = this.network.registry
this.metaIdentityManagerAddress = MetaIdentityManagerArtifact.networks[this.network.id[2]].address
this.initialized = config.initialized || false
this.consume = this.consume.bind(this); // Bind consume method to make it compatible with other uport libraries.
}
}
initKeys() {
if (!this.deviceKeys) this.deviceKeys = genKeyPair()
if (!this.recoveryKeys) this.recoveryKeys = genKeyPair()
this.initTokenSigner()
this.initSimpleSigner()
}
initTokenSigner() {
const tokenSigner = new TokenSigner('ES256k', this.deviceKeys.privateKey.slice(2)) // Remove 0x prefix from private key
this.signer = tokenSigner.sign.bind(tokenSigner)
}
initSimpleSigner() {
this.simpleSigner = new SimpleSigner({privateKey: this.deviceKeys.privateKey, publicKey: this.deviceKeys.publicKey, address: this.deviceKeys.address })
this.transactionSigner = this.simpleSigner //TODO Make less confusing, uses simpler signer until identity created then uses identity specific signer
}
initTransactionSigner(MetaIdentityManagerAdress) {
this.transactionSigner = new MIMProxySigner(this.id, this.simpleSigner, MetaIdentityManagerAdress)
}
appDDO(name, description, url, img) {
return new Promise((resolve, reject) => {
const DDO = { '@type': 'App' }
if (name) DDO.name = name
if (description) DDO.description = description
if (url) DDO.url = url
if (img) {
if (isIPFS.cid(img)) {
DDO.image = { contentUrl: `/ipfs/${img}` }
resolve(DDO)
} else if (isIPFS.path(img)) {
DDO.image = { contentUrl: img }
resolve(DDO)
} else {
fs.readFile(img, (err, data) => {
if (err) {
reject(new Error(err))
} else {
this.ipfs.files.add(data, (err, result) => {
if (err) {
reject(new Error(err))
} else {
const imgHash = result[0].hash
DDO.image = { contentUrl: `/ipfs/${imgHash}` }
resolve(DDO)
}
})
}
})
}
} else {
resolve(DDO)
}
})
}
getReceipt(txHash) {
let receipt
return this.ethjs.getTransactionReceipt(txHash).then(res => {
if (res !== null) {
receipt = res
return
}
return prommiseTimeOut(1000)
}).then(() => {
if (receipt) return receipt
return this.getReceipt(txHash)
})
}
initializeIdentity(initDdo){
if (!this.network) return Promise.reject(new Error('No network configured'))
const MetaIdentityManagerAdress = this.metaIdentityManagerAddress
const MetaIdentityManager = Contract(MetaIdentityManagerArtifact.abi).at(MetaIdentityManagerAdress) // add config for this
this.initKeys()
const uri = MetaIdentityManager.createIdentity(this.deviceKeys.address, this.recoveryKeys.address)
return this.consume(uri)
.then(this.getReceipt.bind(this))
.then(receipt => {
const log = receipt.logs[0]
const createEventAbi = MetaIdentityManager.abi.filter(obj => obj.type === 'event' && obj.name ==='LogIdentityCreated')[0]
this.id = decodeEvent(createEventAbi, log.data, log.topics).identity
this.mnid = mnid.encode({ network: this.network.id, address: this.id })
this.initTransactionSigner(MetaIdentityManagerAdress)
// TODO add address?
const baseDdo = {
'@context': 'http://schema.org',
'@type': 'Person',
"publicKey": this.deviceKeys.publicKey
}
const ddo = Object.assign(baseDdo, initDdo)
return this.writeDDO(ddo)
}).then(this.ethjs.getTransactionReceipt.bind(this.ethjs))
.then(receipt => {
// .. receipt
this.initialized = true
return
})
}
sign(payload) {
const hash = SECP256K1Client.createHash(payload)
return SECP256K1Client.signHash(hash, this.privateKey)
}
addProfileKey(key, value ) {
this.info[key] = value
}
getDDO() {
return this.registry(this.mnid)
}
writeDDO(newDdo) {
const Registry = Contract(RegistryArtifact.abi).at(this.network.registry)
return this.getDDO().then(ddo => {
ddo = Object.assign(ddo || {}, newDdo)
return new Promise((resolve, reject) => {
this.ipfs.add(Buffer.from(JSON.stringify(ddo)), (err, result) => {
if (err) reject(new Error(err))
resolve(result)
})
})
}).then(res => {
const hash = res[0].hash
const hexhash = new Buffer(base58.decode(hash)).toString('hex')
// removes Qm from ipfs hash, which specifies length and hash
const hashArg = `0x${hexhash.slice(4)}`
const key = 'uPortProfileIPFS1220'
return Registry.set(key, this.id, hashArg)
})
.then(this.consume.bind(this))
}
signRawTx(unsignedRawTx) {
return new Promise((resolve, reject) => {
this.transactionSigner.signRawTx(unsignedRawTx, (err, rawTx) => {
if (err) reject(err)
resolve(rawTx)
})
})
}
shareRequestHandler(uri) {
const params = getUrlParams(uri)
// A shareReq in a token
const token = decodeToken(params.requestToken).payload
const verified = filterCredentials(this.credentials, intersection(this.credentials, token.requested) )
const req = params.requestToken
const info = intersection(this.info, token.requested)
.reduce((infoReq, key) => {
infoReq[key] = this.info[key]
return infoReq
}, {})
const payload = {...info, iss: this.address, iat: new Date().getTime(), verified, type: 'shareReq', req}
const response = this.signer(payload)
if (this.network) {
return this.verifyJWT(params.requestToken).then(() => this.responseHandler(response, token.callbackUrl))
}
return this.responseHandler(response, token.callbackUrl)
}
simpleRequestHandler(uri) {
// A simple request
const params = getUrlParams(uri)
const response = this.signer({iss: this.address, iat: new Date().getTime(), address: this.address})
return this.responseHandler(response, params.callback_url)
}
transactionRequestHandler(uri) {
const params = getUrlParams(uri)
const to = uri.match(/0[xX][0-9a-fA-F]+/g)[0]
const from = this.deviceKeys.address
const data = params.bytecode || params.function ? funcToData(params.function) : '0x' //TODO whats the proper null value?
const value = params.value || 0
let nonce, gasPrice, gas, txObj
return this.ethjs.getTransactionCount(this.deviceKeys.address, 'pending')
.then(res => {
nonce = res
return params.gasPrice ? params.gasPrice : this.ethjs.gasPrice()
}).then(res => {
gasPrice = res
txObj = {to, value: new BN(value), data, gasPrice, nonce, from, gasLimit: 300000 } // temp gas val
const tx = new Transaction(txObj)
const unsignedRawTx = util.bufferToHex(tx.serialize())
tx.sign(new Buffer(this.deviceKeys.privateKey.slice(2), 'hex')) // TODO remove redundant, get hash from above, and not actual hash when mocked since not IM
if (this.ethjs) {
return this.signRawTx(unsignedRawTx)
.then(rawTx => {
// TODO remove redudant signing to get actuall tx data for gas estimate, doing this for now since tx data changed in eth-signer
const txEstimate = new Transaction(new Buffer(rawTx, 'hex'));
const estimateTxObj = { data: txEstimate.data.toString('hex'), to: txEstimate.to.toString('hex'), from: txEstimate.from.toString('hex') }
return this.ethjs.estimateGas(estimateTxObj)
}).then(res => {
txObj.gasLimit = params.gas ? params.gas : res.mul(new BN(20, 10)).div(new BN(19, 10)) // gas buffer
const txWithGas = new Transaction(txObj)
const unsignedRawTxWithGas = util.bufferToHex(txWithGas.serialize())
return this.signRawTx(unsignedRawTxWithGas)
}).then(rawTx => {
return this.ethjs.sendRawTransaction(rawTx)
}).then(txHash => {
return this.responseHandler(txHash, params.callback_url)
})
} else {
const txHash = util.bufferToHex(tx.hash(true))
return this.responseHandler(txHash, params.callback_url)
}
})
}
addAttestationRequestHandler(uri) {
const params = getUrlParams(uri)
const attestations = Array.isArray(params.attestations) ? params.attestations : [params.attestations]
for (let jwt in attestations) {
jwt = attestations[jwt]
const json = decodeToken(jwt).payload
const key = Object.keys(json.claim)[0]
if (this.network) {
this.verifyJWT(jwt).then(() => {
this.credentials[key] ? this.credentials[key].append({jwt, json}) : this.credentials[key] = [{jwt, json}]
}).catch(console.log)
}
// redundant
this.credentials[key] ? this.credentials[key].append({jwt, json}) : this.credentials[key] = [{jwt, json}]
}
// TODO standard response?
}
consume(uri) {
if (isShareRequest(uri)) return this.shareRequestHandler(uri)
if (isSimpleRequest(uri)) return this.simpleRequestHandler(uri)
if (isTransactionRequest(uri)) return this.transactionRequestHandler(uri)
if (isAddAttestationRequest(uri)) return this.addAttestationRequestHandler(uri)
return Promise.reject(new Error('Invalid URI Passed'))
}
}
module.exports = { UPortClient, serialize, deserialize, networks, genKeyPair, deploy }