This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.ts
272 lines (220 loc) · 7.69 KB
/
index.ts
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
import { type Ed25519PeerId, type PeerIdType, type RSAPeerId, type Secp256k1PeerId, symbol, type PeerId } from '@libp2p/interface-peer-id'
import { CodeError } from '@libp2p/interfaces/errors'
import { base58btc } from 'multiformats/bases/base58'
import { bases } from 'multiformats/basics'
import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { identity } from 'multiformats/hashes/identity'
import { sha256 } from 'multiformats/hashes/sha2'
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
import type { MultibaseDecoder } from 'multiformats/bases/interface'
import type { MultihashDigest } from 'multiformats/hashes/interface'
const inspect = Symbol.for('nodejs.util.inspect.custom')
const baseDecoder = Object
.values(bases)
.map(codec => codec.decoder)
// @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141
.reduce((acc, curr) => acc.or(curr), bases.identity.decoder)
// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv
const LIBP2P_KEY_CODE = 0x72
const MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36
const MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37
interface PeerIdInit {
type: PeerIdType
multihash: MultihashDigest
privateKey?: Uint8Array
}
interface RSAPeerIdInit {
multihash: MultihashDigest
privateKey?: Uint8Array
publicKey?: Uint8Array
}
interface Ed25519PeerIdInit {
multihash: MultihashDigest
privateKey?: Uint8Array
}
interface Secp256k1PeerIdInit {
multihash: MultihashDigest
privateKey?: Uint8Array
}
class PeerIdImpl {
public type: PeerIdType
public readonly multihash: MultihashDigest
public readonly privateKey?: Uint8Array
public readonly publicKey?: Uint8Array
private string?: string
constructor (init: PeerIdInit) {
this.type = init.type
this.multihash = init.multihash
this.privateKey = init.privateKey
// mark string cache as non-enumerable
Object.defineProperty(this, 'string', {
enumerable: false,
writable: true
})
}
get [Symbol.toStringTag] (): string {
return `PeerId(${this.toString()})`
}
readonly [symbol] = true
toString (): string {
if (this.string == null) {
this.string = base58btc.encode(this.multihash.bytes).slice(1)
}
return this.string
}
// return self-describing String representation
// in default format from RFC 0001: https://github.com/libp2p/specs/pull/209
toCID (): CID {
return CID.createV1(LIBP2P_KEY_CODE, this.multihash)
}
toBytes (): Uint8Array {
return this.multihash.bytes
}
/**
* Returns Multiaddr as a JSON string
*/
toJSON (): string {
return this.toString()
}
/**
* Checks the equality of `this` peer against a given PeerId
*/
equals (id: PeerId | Uint8Array | string): boolean {
if (id instanceof Uint8Array) {
return uint8ArrayEquals(this.multihash.bytes, id)
} else if (typeof id === 'string') {
return peerIdFromString(id).equals(this as PeerId)
} else if (id?.multihash?.bytes != null) {
return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes)
} else {
throw new Error('not valid Id')
}
}
/**
* Returns PeerId as a human-readable string
* https://nodejs.org/api/util.html#utilinspectcustom
*
* @example
* ```js
* import { peerIdFromString } from '@libp2p/peer-id'
*
* console.info(peerIdFromString('QmFoo'))
* // 'PeerId(QmFoo)'
* ```
*/
[inspect] (): string {
return `PeerId(${this.toString()})`
}
}
class RSAPeerIdImpl extends PeerIdImpl implements RSAPeerId {
public readonly type = 'RSA'
public readonly publicKey?: Uint8Array
constructor (init: RSAPeerIdInit) {
super({ ...init, type: 'RSA' })
this.publicKey = init.publicKey
}
}
class Ed25519PeerIdImpl extends PeerIdImpl implements Ed25519PeerId {
public readonly type = 'Ed25519'
public readonly publicKey: Uint8Array
constructor (init: Ed25519PeerIdInit) {
super({ ...init, type: 'Ed25519' })
this.publicKey = init.multihash.digest
}
}
class Secp256k1PeerIdImpl extends PeerIdImpl implements Secp256k1PeerId {
public readonly type = 'secp256k1'
public readonly publicKey: Uint8Array
constructor (init: Secp256k1PeerIdInit) {
super({ ...init, type: 'secp256k1' })
this.publicKey = init.multihash.digest
}
}
export function createPeerId (init: PeerIdInit): PeerId {
if (init.type === 'RSA') {
return new RSAPeerIdImpl(init)
}
if (init.type === 'Ed25519') {
return new Ed25519PeerIdImpl(init)
}
if (init.type === 'secp256k1') {
return new Secp256k1PeerIdImpl(init)
}
throw new CodeError('Type must be "RSA", "Ed25519" or "secp256k1"', 'ERR_INVALID_PARAMETERS')
}
export function peerIdFromPeerId (other: any): PeerId {
if (other.type === 'RSA') {
return new RSAPeerIdImpl(other)
}
if (other.type === 'Ed25519') {
return new Ed25519PeerIdImpl(other)
}
if (other.type === 'secp256k1') {
return new Secp256k1PeerIdImpl(other)
}
throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS')
}
export function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>): PeerId {
decoder = decoder ?? baseDecoder
if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
// identity hash ed25519/secp256k1 key or sha2-256 hash of
// rsa public key - base58btc encoded either way
const multihash = Digest.decode(base58btc.decode(`z${str}`))
if (str.startsWith('12D')) {
return new Ed25519PeerIdImpl({ multihash })
} else if (str.startsWith('16U')) {
return new Secp256k1PeerIdImpl({ multihash })
} else {
return new RSAPeerIdImpl({ multihash })
}
}
return peerIdFromBytes(baseDecoder.decode(str))
}
export function peerIdFromBytes (buf: Uint8Array): PeerId {
try {
const multihash = Digest.decode(buf)
if (multihash.code === identity.code) {
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
return new Ed25519PeerIdImpl({ multihash })
} else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
return new Secp256k1PeerIdImpl({ multihash })
}
}
if (multihash.code === sha256.code) {
return new RSAPeerIdImpl({ multihash })
}
} catch {
return peerIdFromCID(CID.decode(buf))
}
throw new Error('Supplied PeerID CID is invalid')
}
export function peerIdFromCID (cid: CID): PeerId {
if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {
throw new Error('Supplied PeerID CID is invalid')
}
const multihash = cid.multihash
if (multihash.code === sha256.code) {
return new RSAPeerIdImpl({ multihash: cid.multihash })
} else if (multihash.code === identity.code) {
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
return new Ed25519PeerIdImpl({ multihash: cid.multihash })
} else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
return new Secp256k1PeerIdImpl({ multihash: cid.multihash })
}
}
throw new Error('Supplied PeerID CID is invalid')
}
/**
* @param publicKey - A marshalled public key
* @param privateKey - A marshalled private key
*/
export async function peerIdFromKeys (publicKey: Uint8Array, privateKey?: Uint8Array): Promise<PeerId> {
if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })
}
if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey })
}
return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey })
}