This repository has been archived by the owner on Sep 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
ethereum-identity-provider.js
57 lines (49 loc) · 1.79 KB
/
ethereum-identity-provider.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
'use strict'
const IdentityProvider = require('./identity-provider-interface')
const { Wallet, utils } = require('ethers')
const type = 'ethereum'
class EthIdentityProvider extends IdentityProvider {
constructor (options = {}) {
super()
this.wallet = options.wallet
}
// Returns the type of the identity provider
static get type () { return type }
// Returns the signer's id
async getId (options = {}) {
if (!this.wallet) {
this.wallet = await this._createWallet(options)
}
return this.wallet.address
}
// Returns a signature of pubkeysignature
async signIdentity (data, options = {}) {
const wallet = this.wallet
if (!wallet) { throw new Error(`wallet is required`) }
return wallet.signMessage(data)
}
static async verifyIdentity (identity) {
// Verify that identity was signed by the id
const signerAddress = utils.verifyMessage(identity.publicKey + identity.signatures.id, identity.signatures.publicKey)
return (signerAddress === identity.id)
}
async _createWallet (options = {}) {
if (options.mnemonicOpts) {
if (!options.mnemonicOpts.mnemonic) {
throw new Error(`mnemonic is required`)
}
return Wallet.fromMnemonic(options.mnemonicOpts.mnemonic, options.mnemonicOpts.path, options.mnemonicOpts.wordlist)
}
if (options.encryptedJsonOpts) {
if (!options.encryptedJsonOpts.json) {
throw new Error(`encrypted json is required`)
}
if (!options.encryptedJsonOpts.password) {
throw new Error(`password for encrypted json is required`)
}
return Wallet.fromEncryptedJson(options.encryptedJsonOpts.json, options.encryptedJsonOpts.password, options.encryptedJsonOpts.progressCallback)
}
return Wallet.createRandom()
}
}
module.exports = EthIdentityProvider