Skip to content
This repository was archived by the owner on Jul 21, 2023. It is now read-only.

Commit f578b39

Browse files
committed
refactor: replace err-code with CodeError
1 parent a5526bf commit f578b39

15 files changed

+43
-43
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -180,9 +180,9 @@
180180
},
181181
"dependencies": {
182182
"@libp2p/interface-keys": "^1.0.2",
183+
"@libp2p/interfaces": "^3.2.0",
183184
"@noble/ed25519": "^1.6.0",
184185
"@noble/secp256k1": "^1.5.4",
185-
"err-code": "^3.0.1",
186186
"multiformats": "^11.0.0",
187187
"node-forge": "^1.1.0",
188188
"protons-runtime": "^4.0.1",

src/aes/cipher-mode.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errcode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22

33
const CIPHER_MODES = {
44
16: 'aes-128-ctr',
@@ -11,5 +11,5 @@ export function cipherMode (key: Uint8Array) {
1111
}
1212

1313
const modes = Object.entries(CIPHER_MODES).map(([k, v]) => `${k} (${v})`).join(' / ')
14-
throw errcode(new Error(`Invalid key length ${key.length} bytes. Must be ${modes}`), 'ERR_INVALID_KEY_LENGTH')
14+
throw new CodeError(`Invalid key length ${key.length} bytes. Must be ${modes}`, 'ERR_INVALID_KEY_LENGTH')
1515
}

src/keys/ecdh-browser.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errcode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22
import webcrypto from '../webcrypto.js'
33
import { base64urlToBuffer } from '../util.js'
44
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
@@ -17,7 +17,7 @@ const names = curveTypes.join(' / ')
1717

1818
export async function generateEphmeralKeyPair (curve: string) {
1919
if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {
20-
throw errcode(new Error(`Unknown curve: ${curve}. Must be ${names}`), 'ERR_INVALID_CURVE')
20+
throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')
2121
}
2222

2323
const pair = await webcrypto.get().subtle.generateKey(
@@ -94,11 +94,11 @@ const curveLengths = {
9494
// go-ipfs uses)
9595
function marshalPublicKey (jwk: JsonWebKey) {
9696
if (jwk.crv == null || jwk.x == null || jwk.y == null) {
97-
throw errcode(new Error('JWK was missing components'), 'ERR_INVALID_PARAMETERS')
97+
throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')
9898
}
9999

100100
if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {
101-
throw errcode(new Error(`Unknown curve: ${jwk.crv}. Must be ${names}`), 'ERR_INVALID_CURVE')
101+
throw new CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE')
102102
}
103103

104104
const byteLen = curveLengths[jwk.crv]
@@ -113,13 +113,13 @@ function marshalPublicKey (jwk: JsonWebKey) {
113113
// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key
114114
function unmarshalPublicKey (curve: string, key: Uint8Array) {
115115
if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {
116-
throw errcode(new Error(`Unknown curve: ${curve}. Must be ${names}`), 'ERR_INVALID_CURVE')
116+
throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')
117117
}
118118

119119
const byteLen = curveLengths[curve]
120120

121121
if (!uint8ArrayEquals(key.subarray(0, 1), Uint8Array.from([4]))) {
122-
throw errcode(new Error('Cannot unmarshal public key - invalid key format'), 'ERR_INVALID_KEY_FORMAT')
122+
throw new CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT')
123123
}
124124

125125
return {

src/keys/ecdh.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import crypto from 'crypto'
2-
import errcode from 'err-code'
2+
import { CodeError } from '@libp2p/interfaces/errors'
33
import type { ECDHKey, ECDHKeyPair } from './interface.js'
44

55
const curves = {
@@ -13,7 +13,7 @@ const names = curveTypes.join(' / ')
1313

1414
export async function generateEphmeralKeyPair (curve: string): Promise<ECDHKey> { // eslint-disable-line require-await
1515
if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {
16-
throw errcode(new Error(`Unknown curve: ${curve}. Must be ${names}`), 'ERR_INVALID_CURVE')
16+
throw new CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE')
1717
}
1818

1919
const ecdh = crypto.createECDH(curves[curve])

src/keys/ed25519-class.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errcode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
33
import { sha256 } from 'multiformats/hashes/sha2'
44
import { base58btc } from 'multiformats/bases/base58'
@@ -101,7 +101,7 @@ export class Ed25519PrivateKey {
101101
if (format === 'libp2p-key') {
102102
return await exporter(this.bytes, password)
103103
} else {
104-
throw errcode(new Error(`export format '${format}' is not supported`), 'ERR_INVALID_EXPORT_FORMAT')
104+
throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')
105105
}
106106
}
107107
}
@@ -139,7 +139,7 @@ export async function generateKeyPairFromSeed (seed: Uint8Array) {
139139
function ensureKey (key: Uint8Array, length: number) {
140140
key = Uint8Array.from(key ?? [])
141141
if (key.length !== length) {
142-
throw errcode(new Error(`Key must be a Uint8Array of length ${length}, got ${key.length}`), 'ERR_INVALID_KEY_TYPE')
142+
throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE')
143143
}
144144
return key
145145
}

src/keys/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import 'node-forge/lib/asn1.js'
33
import 'node-forge/lib/pbe.js'
44
// @ts-expect-error types are missing
55
import forge from 'node-forge/lib/forge.js'
6-
import errcode from 'err-code'
6+
import { CodeError } from '@libp2p/interfaces/errors'
77
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
88
import { keyStretcher } from './key-stretcher.js'
99
import generateEphemeralKeyPair from './ephemeral-keys.js'
@@ -27,7 +27,7 @@ export const supportedKeys = {
2727

2828
function unsupportedKey (type: string) {
2929
const supported = Object.keys(supportedKeys).join(' / ')
30-
return errcode(new Error(`invalid or unsupported key type ${type}. Must be ${supported}`), 'ERR_UNSUPPORTED_KEY_TYPE')
30+
return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE')
3131
}
3232

3333
function typeToKey (type: string) {
@@ -49,7 +49,7 @@ export async function generateKeyPair (type: KeyTypes, bits?: number): Promise<P
4949
// seed is a 32 byte uint8array
5050
export async function generateKeyPairFromSeed (type: KeyTypes, seed: Uint8Array, bits?: number): Promise<PrivateKey> { // eslint-disable-line require-await
5151
if (type.toLowerCase() !== 'ed25519') {
52-
throw errcode(new Error('Seed key derivation is unimplemented for RSA or secp256k1'), 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')
52+
throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')
5353
}
5454

5555
return await Ed25519.generateKeyPairFromSeed(seed)
@@ -121,7 +121,7 @@ export async function importKey (encryptedKey: string, password: string): Promis
121121
// Only rsa supports pem right now
122122
const key = forge.pki.decryptRsaPrivateKey(encryptedKey, password)
123123
if (key === null) {
124-
throw errcode(new Error('Cannot read the key, most likely the password is wrong or not a RSA key'), 'ERR_CANNOT_DECRYPT_PEM')
124+
throw new CodeError('Cannot read the key, most likely the password is wrong or not a RSA key', 'ERR_CANNOT_DECRYPT_PEM')
125125
}
126126
let der = forge.asn1.toDer(forge.pki.privateKeyToAsn1(key))
127127
der = uint8ArrayFromString(der.getBytes(), 'ascii')

src/keys/key-stretcher.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errcode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22
import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
33
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
44
import * as hmac from '../hmac/index.js'
@@ -27,11 +27,11 @@ export async function keyStretcher (cipherType: 'AES-128' | 'AES-256' | 'Blowfis
2727

2828
if (cipher == null) {
2929
const allowed = Object.keys(cipherMap).join(' / ')
30-
throw errcode(new Error(`unknown cipher type '${cipherType}'. Must be ${allowed}`), 'ERR_INVALID_CIPHER_TYPE')
30+
throw new CodeError(`unknown cipher type '${cipherType}'. Must be ${allowed}`, 'ERR_INVALID_CIPHER_TYPE')
3131
}
3232

3333
if (hash == null) {
34-
throw errcode(new Error('missing hash type'), 'ERR_MISSING_HASH_TYPE')
34+
throw new CodeError('missing hash type', 'ERR_MISSING_HASH_TYPE')
3535
}
3636

3737
const cipherKeySize = cipher.keySize

src/keys/rsa-browser.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
44
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
55
import * as utils from './rsa-utils.js'
66
import { jwk2pub, jwk2priv } from './jwk2pem.js'
7-
import errcode from 'err-code'
7+
import { CodeError } from '@libp2p/interfaces/errors'
88

99
export { utils }
1010

@@ -102,7 +102,7 @@ export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint
102102

103103
async function exportKey (pair: CryptoKeyPair) {
104104
if (pair.privateKey == null || pair.publicKey == null) {
105-
throw errcode(new Error('Private and public key are required'), 'ERR_INVALID_PARAMETERS')
105+
throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS')
106106
}
107107

108108
return await Promise.all([

src/keys/rsa-class.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22
import { sha256 } from 'multiformats/hashes/sha2'
3-
import errcode from 'err-code'
3+
import { CodeError } from '@libp2p/interfaces/errors'
44
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
55
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
66
import 'node-forge/lib/sha512.js'
@@ -66,7 +66,7 @@ export class RsaPrivateKey {
6666

6767
get public () {
6868
if (this._publicKey == null) {
69-
throw errcode(new Error('public key not provided'), 'ERR_PUBKEY_NOT_PROVIDED')
69+
throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED')
7070
}
7171

7272
return new RsaPublicKey(this._publicKey)
@@ -128,7 +128,7 @@ export class RsaPrivateKey {
128128
} else if (format === 'libp2p-key') {
129129
return await exporter(this.bytes, password)
130130
} else {
131-
throw errcode(new Error(`export format '${format}' is not supported`), 'ERR_INVALID_EXPORT_FORMAT')
131+
throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')
132132
}
133133
}
134134
}

src/keys/rsa-utils.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import forge from 'node-forge/lib/forge.js'
55
import { bigIntegerToUintBase64url, base64urlToBigInteger } from './../util.js'
66
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'
77
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
8-
import errcode from 'err-code'
8+
import { CodeError } from '@libp2p/interfaces/errors'
99

1010
// Convert a PKCS#1 in ASN1 DER format to a JWK key
1111
export function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {
@@ -30,7 +30,7 @@ export function pkcs1ToJwk (bytes: Uint8Array): JsonWebKey {
3030
// Convert a JWK key into PKCS#1 in ASN1 DER format
3131
export function jwkToPkcs1 (jwk: JsonWebKey) {
3232
if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {
33-
throw errcode(new Error('JWK was missing components'), 'ERR_INVALID_PARAMETERS')
33+
throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')
3434
}
3535

3636
const asn1 = forge.pki.privateKeyToAsn1({
@@ -62,7 +62,7 @@ export function pkixToJwk (bytes: Uint8Array): JsonWebKey {
6262
// Convert a JWK key to PKCIX in ASN1 DER format
6363
export function jwkToPkix (jwk: JsonWebKey) {
6464
if (jwk.n == null || jwk.e == null) {
65-
throw errcode(new Error('JWK was missing components'), 'ERR_INVALID_PARAMETERS')
65+
throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS')
6666
}
6767

6868
const asn1 = forge.pki.publicKeyToAsn1({

src/keys/rsa.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import crypto from 'crypto'
22
import { promisify } from 'util'
3-
import errcode from 'err-code'
3+
import { CodeError } from '@libp2p/interfaces/errors'
44
import randomBytes from '../random-bytes.js'
55
import * as utils from './rsa-utils.js'
66
import type { JWKKeyPair } from './interface.js'
@@ -28,7 +28,7 @@ export async function generateKey (bits: number): Promise<JWKKeyPair> { // eslin
2828
// Takes a jwk key
2929
export async function unmarshalPrivateKey (key: JsonWebKey): Promise<JWKKeyPair> { // eslint-disable-line require-await
3030
if (key == null) {
31-
throw errcode(new Error('Missing key parameter'), 'ERR_MISSING_KEY')
31+
throw new CodeError('Missing key parameter', 'ERR_MISSING_KEY')
3232
}
3333
return {
3434
privateKey: key,

src/keys/secp256k1-class.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { sha256 } from 'multiformats/hashes/sha2'
2-
import errcode from 'err-code'
2+
import { CodeError } from '@libp2p/interfaces/errors'
33
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
44
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
55
import * as crypto from './secp256k1.js'
@@ -99,7 +99,7 @@ export class Secp256k1PrivateKey {
9999
if (format === 'libp2p-key') {
100100
return await exporter(this.bytes, password)
101101
} else {
102-
throw errcode(new Error(`export format '${format}' is not supported`), 'ERR_INVALID_EXPORT_FORMAT')
102+
throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT')
103103
}
104104
}
105105
}

src/keys/secp256k1.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errcode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22
import * as secp from '@noble/secp256k1'
33
import { sha256 } from 'multiformats/hashes/sha2'
44

@@ -18,7 +18,7 @@ export async function hashAndSign (key: Uint8Array, msg: Uint8Array) {
1818
try {
1919
return await secp.sign(digest, key)
2020
} catch (err) {
21-
throw errcode(err, 'ERR_INVALID_INPUT')
21+
throw new CodeError(String(err), 'ERR_INVALID_INPUT')
2222
}
2323
}
2424

@@ -30,7 +30,7 @@ export async function hashAndVerify (key: Uint8Array, sig: Uint8Array, msg: Uint
3030
const { digest } = await sha256.digest(msg)
3131
return secp.verify(sig, digest, key)
3232
} catch (err) {
33-
throw errcode(err, 'ERR_INVALID_INPUT')
33+
throw new CodeError(String(err), 'ERR_INVALID_INPUT')
3434
}
3535
}
3636

@@ -48,22 +48,22 @@ export function validatePrivateKey (key: Uint8Array) {
4848
try {
4949
secp.getPublicKey(key, true)
5050
} catch (err) {
51-
throw errcode(err, 'ERR_INVALID_PRIVATE_KEY')
51+
throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')
5252
}
5353
}
5454

5555
export function validatePublicKey (key: Uint8Array) {
5656
try {
5757
secp.Point.fromHex(key)
5858
} catch (err) {
59-
throw errcode(err, 'ERR_INVALID_PUBLIC_KEY')
59+
throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY')
6060
}
6161
}
6262

6363
export function computePublicKey (privateKey: Uint8Array) {
6464
try {
6565
return secp.getPublicKey(privateKey, true)
6666
} catch (err) {
67-
throw errcode(err, 'ERR_INVALID_PRIVATE_KEY')
67+
throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY')
6868
}
6969
}

src/pbkdf2.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import forgePbkdf2 from 'node-forge/lib/pbkdf2.js'
33
// @ts-expect-error types are missing
44
import forgeUtil from 'node-forge/lib/util.js'
5-
import errcode from 'err-code'
5+
import { CodeError } from '@libp2p/interfaces/errors'
66

77
/**
88
* Maps an IPFS hash name to its node-forge equivalent.
@@ -23,7 +23,7 @@ const hashName = {
2323
export default function pbkdf2 (password: string, salt: string, iterations: number, keySize: number, hash: string): string {
2424
if (hash !== 'sha1' && hash !== 'sha2-256' && hash !== 'sha2-512') {
2525
const types = Object.keys(hashName).join(' / ')
26-
throw errcode(new Error(`Hash '${hash}' is unknown or not supported. Must be ${types}`), 'ERR_UNSUPPORTED_HASH_TYPE')
26+
throw new CodeError(`Hash '${hash}' is unknown or not supported. Must be ${types}`, 'ERR_UNSUPPORTED_HASH_TYPE')
2727
}
2828

2929
const hasher = hashName[hash]

src/random-bytes.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import { utils } from '@noble/secp256k1'
2-
import errcode from 'err-code'
2+
import { CodeError } from '@libp2p/interfaces/errors'
33

44
export default function randomBytes (length: number): Uint8Array {
55
if (isNaN(length) || length <= 0) {
6-
throw errcode(new Error('random bytes length must be a Number bigger than 0'), 'ERR_INVALID_LENGTH')
6+
throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH')
77
}
88
return utils.randomBytes(length)
99
}

0 commit comments

Comments
 (0)