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 14
/
keystore.js
210 lines (182 loc) · 5.35 KB
/
keystore.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
'use strict'
const fs = (typeof window === 'object' || typeof self === 'object') ? null : eval('require("fs")') // eslint-disable-line
const level = require('level')
const crypto = require('libp2p-crypto')
const secp256k1 = require('secp256k1')
const LRU = require('lru')
const Buffer = require('safe-buffer/').Buffer
const { verifier } = require('./verifiers')
function createStore (path = './keystore') {
if (fs && fs.mkdirSync) {
fs.mkdirSync(path, { recursive: true })
}
return level(path)
}
const verifiedCache = new LRU(1000)
class Keystore {
constructor (input = {}) {
if (typeof input === 'string') {
this._store = createStore(input)
} else if (typeof input.open === 'function') {
this._store = input
} else if (typeof input.store === 'string') {
this._store = createStore(input.store)
} else {
this._store = input.store || createStore()
}
this._cache = input.cache || new LRU(100)
}
async open () {
if (this._store) {
await this._store.open()
return Promise.resolve()
}
return Promise.reject(new Error('Keystore: No store found to open'))
}
async close () {
if (!this._store) return
await this._store.close()
}
async hasKey (id) {
if (!id) {
throw new Error('id needed to check a key')
}
if (this._store.status && this._store.status !== 'open') {
return Promise.resolve(null)
}
let hasKey = false
try {
let storedKey = this._cache.get(id) || await this._store.get(id)
hasKey = storedKey !== undefined && storedKey !== null
} catch (e) {
// Catches 'Error: ENOENT: no such file or directory, open <path>'
console.error('Error: ENOENT: no such file or directory')
}
return hasKey
}
async createKey (id) {
if (!id) {
throw new Error('id needed to create a key')
}
if (this._store.status && this._store.status !== 'open') {
return Promise.resolve(null)
}
const genKeyPair = () => new Promise((resolve, reject) => {
crypto.keys.generateKeyPair('secp256k1', 256, (err, key) => {
if (!err) {
resolve(key)
}
reject(err)
})
})
const keys = await genKeyPair()
const decompressedKey = secp256k1.publicKeyConvert(keys.public.marshal(), false)
const key = {
publicKey: decompressedKey.toString('hex'),
privateKey: keys.marshal().toString('hex')
}
try {
await this._store.put(id, JSON.stringify(key))
} catch (e) {
console.log(e)
}
this._cache.set(id, key)
return keys
}
async getKey (id) {
if (!id) {
throw new Error('id needed to get a key')
}
if (!this._store) {
await this.open()
}
if (this._store.status && this._store.status !== 'open') {
return Promise.resolve(null)
}
const cachedKey = this._cache.get(id)
let storedKey
try {
storedKey = cachedKey || await this._store.get(id)
} catch (e) {
// ignore ENOENT error
}
if (!storedKey) {
return
}
const deserializedKey = cachedKey || JSON.parse(storedKey)
if (!deserializedKey) {
return
}
if (!cachedKey) {
this._cache.set(id, deserializedKey)
}
const genPrivKey = (pk) => new Promise((resolve, reject) => {
crypto.keys.supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(pk, (err, key) => {
if (!err) {
resolve(key)
}
reject(err)
})
})
return genPrivKey(Buffer.from(deserializedKey.privateKey, 'hex'))
}
async sign (key, data) {
if (!key) {
throw new Error('No signing key given')
}
if (!data) {
throw new Error('Given input data was undefined')
}
if (!Buffer.isBuffer(data)) {
data = Buffer.from(data)
}
return new Promise((resolve, reject) => {
key.sign(data, (err, signature) => {
if (!err) {
resolve(signature.toString('hex'))
}
reject(err)
})
})
}
getPublic (keys, options = {}) {
const formats = ['hex', 'buffer']
const decompress = typeof options.decompress === 'undefined' ? true : options.decompress
const format = options.format || 'hex'
if (formats.indexOf(format) === -1) {
throw new Error('Supported formats are `hex` and `buffer`')
}
let pubKey = keys.public.marshal()
if (decompress) {
pubKey = secp256k1.publicKeyConvert(pubKey, false)
}
return format === 'buffer' ? pubKey : pubKey.toString('hex')
}
async verify (signature, publicKey, data, v = 'v1') {
return Keystore.verify(signature, publicKey, data, v)
}
static async verify (signature, publicKey, data, v = 'v1') {
const cached = verifiedCache.get(signature)
let res = false
if (!cached) {
const verified = await verifier(v).verify(signature, publicKey, data)
res = verified
if (verified) {
verifiedCache.set(signature, { publicKey, data })
}
} else {
const compare = (cached, data, v) => {
let match
if (v === 'v0') {
match = Buffer.compare(Buffer.alloc(30, cached), Buffer.alloc(30, data)) === 0
} else {
match = Buffer.isBuffer(data) ? Buffer.compare(cached, data) === 0 : cached === data
}
return match
}
res = cached.publicKey === publicKey && compare(cached.data, data, v)
}
return res
}
}
module.exports = Keystore