@libp2p/noise 12.0.1 → 16.1.4-6059227cb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +95 -0
  2. package/dist/index.min.js +16 -20
  3. package/dist/index.min.js.map +7 -0
  4. package/dist/src/constants.d.ts +1 -0
  5. package/dist/src/constants.d.ts.map +1 -1
  6. package/dist/src/constants.js +1 -0
  7. package/dist/src/constants.js.map +1 -1
  8. package/dist/src/crypto/index.browser.d.ts +2 -0
  9. package/dist/src/crypto/index.browser.d.ts.map +1 -0
  10. package/dist/src/crypto/index.browser.js +3 -0
  11. package/dist/src/crypto/index.browser.js.map +1 -0
  12. package/dist/src/crypto/index.d.ts +3 -0
  13. package/dist/src/crypto/index.d.ts.map +1 -0
  14. package/dist/src/crypto/index.js +188 -0
  15. package/dist/src/crypto/index.js.map +1 -0
  16. package/dist/src/crypto/js.d.ts.map +1 -1
  17. package/dist/src/crypto/js.js +18 -17
  18. package/dist/src/crypto/js.js.map +1 -1
  19. package/dist/src/crypto.d.ts +11 -10
  20. package/dist/src/crypto.d.ts.map +1 -1
  21. package/dist/src/crypto.js +10 -1
  22. package/dist/src/crypto.js.map +1 -1
  23. package/dist/src/encoder.d.ts +5 -10
  24. package/dist/src/encoder.d.ts.map +1 -1
  25. package/dist/src/encoder.js +10 -51
  26. package/dist/src/encoder.js.map +1 -1
  27. package/dist/src/errors.d.ts +6 -0
  28. package/dist/src/errors.d.ts.map +1 -0
  29. package/dist/src/errors.js +9 -0
  30. package/dist/src/errors.js.map +1 -0
  31. package/dist/src/index.d.ts +50 -5
  32. package/dist/src/index.d.ts.map +1 -1
  33. package/dist/src/index.js +38 -1
  34. package/dist/src/index.js.map +1 -1
  35. package/dist/src/logger.d.ts +9 -10
  36. package/dist/src/logger.d.ts.map +1 -1
  37. package/dist/src/logger.js +39 -28
  38. package/dist/src/logger.js.map +1 -1
  39. package/dist/src/metrics.d.ts +1 -1
  40. package/dist/src/metrics.d.ts.map +1 -1
  41. package/dist/src/noise.d.ts +33 -30
  42. package/dist/src/noise.d.ts.map +1 -1
  43. package/dist/src/noise.js +122 -78
  44. package/dist/src/noise.js.map +1 -1
  45. package/dist/src/nonce.d.ts +2 -3
  46. package/dist/src/nonce.d.ts.map +1 -1
  47. package/dist/src/nonce.js +3 -2
  48. package/dist/src/nonce.js.map +1 -1
  49. package/dist/src/performHandshake.d.ts +5 -0
  50. package/dist/src/performHandshake.d.ts.map +1 -0
  51. package/dist/src/performHandshake.js +69 -0
  52. package/dist/src/performHandshake.js.map +1 -0
  53. package/dist/src/proto/payload.d.ts +4 -3
  54. package/dist/src/proto/payload.d.ts.map +1 -1
  55. package/dist/src/proto/payload.js +48 -29
  56. package/dist/src/proto/payload.js.map +1 -1
  57. package/dist/src/protocol.d.ts +71 -0
  58. package/dist/src/protocol.d.ts.map +1 -0
  59. package/dist/src/protocol.js +257 -0
  60. package/dist/src/protocol.js.map +1 -0
  61. package/dist/src/types.d.ts +98 -0
  62. package/dist/src/types.d.ts.map +1 -0
  63. package/dist/src/types.js +2 -0
  64. package/dist/src/types.js.map +1 -0
  65. package/dist/src/utils.d.ts +10 -19
  66. package/dist/src/utils.d.ts.map +1 -1
  67. package/dist/src/utils.js +159 -57
  68. package/dist/src/utils.js.map +1 -1
  69. package/package.json +43 -48
  70. package/src/constants.ts +1 -0
  71. package/src/crypto/index.browser.ts +3 -0
  72. package/src/crypto/index.ts +219 -0
  73. package/src/crypto/js.ts +25 -27
  74. package/src/crypto.ts +21 -10
  75. package/src/encoder.ts +10 -67
  76. package/src/errors.ts +10 -0
  77. package/src/index.ts +54 -6
  78. package/src/logger.ts +46 -32
  79. package/src/metrics.ts +1 -1
  80. package/src/noise.ts +176 -131
  81. package/src/nonce.ts +7 -7
  82. package/src/performHandshake.ts +91 -0
  83. package/src/proto/payload.proto +2 -1
  84. package/src/proto/payload.ts +53 -31
  85. package/src/protocol.ts +313 -0
  86. package/src/types.ts +105 -0
  87. package/src/utils.ts +189 -79
  88. package/dist/src/@types/basic.d.ts +0 -5
  89. package/dist/src/@types/basic.d.ts.map +0 -1
  90. package/dist/src/@types/basic.js +0 -2
  91. package/dist/src/@types/basic.js.map +0 -1
  92. package/dist/src/@types/handshake-interface.d.ts +0 -15
  93. package/dist/src/@types/handshake-interface.d.ts.map +0 -1
  94. package/dist/src/@types/handshake-interface.js +0 -2
  95. package/dist/src/@types/handshake-interface.js.map +0 -1
  96. package/dist/src/@types/handshake.d.ts +0 -40
  97. package/dist/src/@types/handshake.d.ts.map +0 -1
  98. package/dist/src/@types/handshake.js +0 -2
  99. package/dist/src/@types/handshake.js.map +0 -1
  100. package/dist/src/@types/libp2p.d.ts +0 -10
  101. package/dist/src/@types/libp2p.d.ts.map +0 -1
  102. package/dist/src/@types/libp2p.js +0 -2
  103. package/dist/src/@types/libp2p.js.map +0 -1
  104. package/dist/src/crypto/streaming.d.ts +0 -7
  105. package/dist/src/crypto/streaming.d.ts.map +0 -1
  106. package/dist/src/crypto/streaming.js +0 -50
  107. package/dist/src/crypto/streaming.js.map +0 -1
  108. package/dist/src/handshake-xx.d.ts +0 -33
  109. package/dist/src/handshake-xx.d.ts.map +0 -1
  110. package/dist/src/handshake-xx.js +0 -139
  111. package/dist/src/handshake-xx.js.map +0 -1
  112. package/dist/src/handshakes/abstract-handshake.d.ts +0 -36
  113. package/dist/src/handshakes/abstract-handshake.d.ts.map +0 -1
  114. package/dist/src/handshakes/abstract-handshake.js +0 -140
  115. package/dist/src/handshakes/abstract-handshake.js.map +0 -1
  116. package/dist/src/handshakes/xx.d.ts +0 -18
  117. package/dist/src/handshakes/xx.d.ts.map +0 -1
  118. package/dist/src/handshakes/xx.js +0 -161
  119. package/dist/src/handshakes/xx.js.map +0 -1
  120. package/src/@types/basic.ts +0 -5
  121. package/src/@types/handshake-interface.ts +0 -12
  122. package/src/@types/handshake.ts +0 -48
  123. package/src/@types/libp2p.ts +0 -10
  124. package/src/crypto/streaming.ts +0 -58
  125. package/src/handshake-xx.ts +0 -177
  126. package/src/handshakes/abstract-handshake.ts +0 -180
  127. package/src/handshakes/xx.ts +0 -184
@@ -0,0 +1,219 @@
1
+ import crypto from 'node:crypto'
2
+ import { newInstance, ChaCha20Poly1305 } from '@chainsafe/as-chacha20poly1305'
3
+ import { digest } from '@chainsafe/as-sha256'
4
+ import { Uint8ArrayList } from 'uint8arraylist'
5
+ import { isElectronMain } from 'wherearewe'
6
+ import { pureJsCrypto } from './js.js'
7
+ import type { ICryptoInterface } from '../crypto.js'
8
+ import type { KeyPair } from '../types.js'
9
+
10
+ const ctx = newInstance()
11
+ const asImpl = new ChaCha20Poly1305(ctx)
12
+ const CHACHA_POLY1305 = 'chacha20-poly1305'
13
+ const PKCS8_PREFIX = Buffer.from([0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20])
14
+ const X25519_PREFIX = Buffer.from([0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x03, 0x21, 0x00])
15
+ const nodeCrypto: Pick<ICryptoInterface, 'hashSHA256' | 'chaCha20Poly1305Encrypt' | 'chaCha20Poly1305Decrypt'> = {
16
+ hashSHA256 (data) {
17
+ const hash = crypto.createHash('sha256')
18
+
19
+ if (data instanceof Uint8Array) {
20
+ return hash.update(data).digest()
21
+ }
22
+
23
+ for (const buf of data) {
24
+ hash.update(buf)
25
+ }
26
+
27
+ return hash.digest()
28
+ },
29
+
30
+ chaCha20Poly1305Encrypt (plaintext, nonce, ad, k) {
31
+ const cipher = crypto.createCipheriv(CHACHA_POLY1305, k, nonce, {
32
+ authTagLength: 16
33
+ })
34
+ cipher.setAAD(ad, { plaintextLength: plaintext.byteLength })
35
+
36
+ if (plaintext instanceof Uint8Array) {
37
+ const updated = cipher.update(plaintext)
38
+ const final = cipher.final()
39
+ const tag = cipher.getAuthTag()
40
+
41
+ return Buffer.concat([updated, final, tag], updated.byteLength + final.byteLength + tag.byteLength)
42
+ }
43
+
44
+ const output = new Uint8ArrayList()
45
+
46
+ for (const buf of plaintext) {
47
+ output.append(cipher.update(buf))
48
+ }
49
+
50
+ const final = cipher.final()
51
+
52
+ if (final.byteLength > 0) {
53
+ output.append(final)
54
+ }
55
+
56
+ output.append(cipher.getAuthTag())
57
+
58
+ return output
59
+ },
60
+
61
+ chaCha20Poly1305Decrypt (ciphertext, nonce, ad, k, _dst) {
62
+ const authTag = ciphertext.subarray(ciphertext.length - 16)
63
+ const decipher = crypto.createDecipheriv(CHACHA_POLY1305, k, nonce, {
64
+ authTagLength: 16
65
+ })
66
+
67
+ let text: Uint8Array | Uint8ArrayList
68
+
69
+ if (ciphertext instanceof Uint8Array) {
70
+ text = ciphertext.subarray(0, ciphertext.length - 16)
71
+ } else {
72
+ text = ciphertext.sublist(0, ciphertext.length - 16)
73
+ }
74
+
75
+ decipher.setAAD(ad, {
76
+ plaintextLength: text.byteLength
77
+ })
78
+ decipher.setAuthTag(authTag)
79
+
80
+ if (text instanceof Uint8Array) {
81
+ const output = decipher.update(text)
82
+ const final = decipher.final()
83
+
84
+ if (final.byteLength > 0) {
85
+ return Buffer.concat([output, final], output.byteLength + final.byteLength)
86
+ }
87
+
88
+ return output
89
+ }
90
+
91
+ const output = new Uint8ArrayList()
92
+
93
+ for (const buf of text) {
94
+ output.append(decipher.update(buf))
95
+ }
96
+
97
+ const final = decipher.final()
98
+
99
+ if (final.byteLength > 0) {
100
+ output.append(final)
101
+ }
102
+
103
+ return output
104
+ }
105
+ }
106
+
107
+ const asCrypto: Pick<ICryptoInterface, 'hashSHA256' | 'chaCha20Poly1305Encrypt' | 'chaCha20Poly1305Decrypt'> = {
108
+ hashSHA256 (data) {
109
+ return digest(data.subarray())
110
+ },
111
+ chaCha20Poly1305Encrypt (plaintext, nonce, ad, k) {
112
+ return asImpl.seal(k, nonce, plaintext.subarray(), ad)
113
+ },
114
+ chaCha20Poly1305Decrypt (ciphertext, nonce, ad, k, dst) {
115
+ const plaintext = asImpl.open(k, nonce, ciphertext.subarray(), ad, dst)
116
+ if (!plaintext) {
117
+ throw new Error('Invalid chacha20poly1305 decryption')
118
+ }
119
+ return plaintext
120
+ }
121
+ }
122
+
123
+ // benchmarks show that for chacha20poly1305
124
+ // the as implementation is faster for smaller payloads(<1200)
125
+ // and the node implementation is faster for larger payloads
126
+ export const defaultCrypto: ICryptoInterface = {
127
+ ...pureJsCrypto,
128
+ hashSHA256 (data) {
129
+ return nodeCrypto.hashSHA256(data)
130
+ },
131
+ chaCha20Poly1305Encrypt (plaintext, nonce, ad, k) {
132
+ if (plaintext.byteLength < 1200) {
133
+ return asCrypto.chaCha20Poly1305Encrypt(plaintext, nonce, ad, k)
134
+ }
135
+ return nodeCrypto.chaCha20Poly1305Encrypt(plaintext, nonce, ad, k)
136
+ },
137
+ chaCha20Poly1305Decrypt (ciphertext, nonce, ad, k, dst) {
138
+ if (ciphertext.byteLength < 1200) {
139
+ return asCrypto.chaCha20Poly1305Decrypt(ciphertext, nonce, ad, k, dst)
140
+ }
141
+ return nodeCrypto.chaCha20Poly1305Decrypt(ciphertext, nonce, ad, k, dst)
142
+ },
143
+ generateX25519KeyPair (): KeyPair {
144
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('x25519', {
145
+ publicKeyEncoding: {
146
+ type: 'spki',
147
+ format: 'der'
148
+ },
149
+ privateKeyEncoding: {
150
+ type: 'pkcs8',
151
+ format: 'der'
152
+ }
153
+ })
154
+
155
+ return {
156
+ publicKey: publicKey.subarray(X25519_PREFIX.length),
157
+ privateKey: privateKey.subarray(PKCS8_PREFIX.length)
158
+ }
159
+ },
160
+ generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {
161
+ const privateKey = crypto.createPrivateKey({
162
+ key: Buffer.concat([
163
+ PKCS8_PREFIX,
164
+ seed
165
+ ], PKCS8_PREFIX.byteLength + seed.byteLength),
166
+ type: 'pkcs8',
167
+ format: 'der'
168
+ })
169
+
170
+ const publicKey = crypto.createPublicKey(privateKey)
171
+ .export({
172
+ type: 'spki',
173
+ format: 'der'
174
+ }).subarray(X25519_PREFIX.length)
175
+
176
+ return {
177
+ publicKey,
178
+ privateKey: seed
179
+ }
180
+ },
181
+ generateX25519SharedKey (privateKey: Uint8Array | Uint8ArrayList, publicKey: Uint8Array | Uint8ArrayList): Uint8Array {
182
+ if (publicKey instanceof Uint8Array) {
183
+ publicKey = Buffer.concat([
184
+ X25519_PREFIX,
185
+ publicKey
186
+ ], X25519_PREFIX.byteLength + publicKey.byteLength)
187
+ } else {
188
+ publicKey = new Uint8ArrayList(X25519_PREFIX, publicKey).subarray()
189
+ }
190
+
191
+ if (privateKey instanceof Uint8Array) {
192
+ privateKey = Buffer.concat([
193
+ PKCS8_PREFIX,
194
+ privateKey
195
+ ], PKCS8_PREFIX.byteLength + privateKey.byteLength)
196
+ } else {
197
+ privateKey = new Uint8ArrayList(PKCS8_PREFIX, privateKey).subarray()
198
+ }
199
+
200
+ return crypto.diffieHellman({
201
+ publicKey: crypto.createPublicKey({
202
+ key: Buffer.from(publicKey.buffer, publicKey.byteOffset, publicKey.byteLength),
203
+ type: 'spki',
204
+ format: 'der'
205
+ }),
206
+ privateKey: crypto.createPrivateKey({
207
+ key: Buffer.from(privateKey.buffer, privateKey.byteOffset, privateKey.byteLength),
208
+ type: 'pkcs8',
209
+ format: 'der'
210
+ })
211
+ })
212
+ }
213
+ }
214
+
215
+ // no chacha20-poly1305 in electron https://github.com/electron/electron/issues/24024
216
+ if (isElectronMain) {
217
+ defaultCrypto.chaCha20Poly1305Encrypt = asCrypto.chaCha20Poly1305Encrypt
218
+ defaultCrypto.chaCha20Poly1305Decrypt = asCrypto.chaCha20Poly1305Decrypt
219
+ }
package/src/crypto/js.ts CHANGED
@@ -1,19 +1,20 @@
1
- import { hkdf } from '@noble/hashes/hkdf'
2
- import { sha256 } from '@noble/hashes/sha256'
3
- import { ChaCha20Poly1305 } from '@stablelib/chacha20poly1305'
4
- import * as x25519 from '@stablelib/x25519'
5
- import type { bytes, bytes32 } from '../@types/basic.js'
6
- import type { Hkdf } from '../@types/handshake.js'
7
- import type { KeyPair } from '../@types/libp2p.js'
1
+ import { chacha20poly1305 } from '@noble/ciphers/chacha'
2
+ import { x25519 } from '@noble/curves/ed25519'
3
+ import { extract, expand } from '@noble/hashes/hkdf'
4
+ import { sha256 } from '@noble/hashes/sha2'
8
5
  import type { ICryptoInterface } from '../crypto.js'
6
+ import type { KeyPair } from '../types.js'
7
+ import type { Uint8ArrayList } from 'uint8arraylist'
9
8
 
10
9
  export const pureJsCrypto: ICryptoInterface = {
11
- hashSHA256 (data: Uint8Array): Uint8Array {
12
- return sha256(data)
10
+ hashSHA256 (data: Uint8Array | Uint8ArrayList): Uint8Array {
11
+ return sha256(data.subarray())
13
12
  },
14
13
 
15
- getHKDF (ck: bytes32, ikm: Uint8Array): Hkdf {
16
- const okm = hkdf(sha256, ikm, ck, undefined, 96)
14
+ getHKDF (ck: Uint8Array, ikm: Uint8Array): [Uint8Array, Uint8Array, Uint8Array] {
15
+ const prk = extract(sha256, ikm, ck)
16
+ const okmU8Array = expand(sha256, prk, undefined, 96)
17
+ const okm = okmU8Array
17
18
 
18
19
  const k1 = okm.subarray(0, 32)
19
20
  const k2 = okm.subarray(32, 64)
@@ -23,36 +24,33 @@ export const pureJsCrypto: ICryptoInterface = {
23
24
  },
24
25
 
25
26
  generateX25519KeyPair (): KeyPair {
26
- const keypair = x25519.generateKeyPair()
27
+ const secretKey = x25519.utils.randomSecretKey()
28
+ const publicKey = x25519.getPublicKey(secretKey)
27
29
 
28
30
  return {
29
- publicKey: keypair.publicKey,
30
- privateKey: keypair.secretKey
31
+ publicKey,
32
+ privateKey: secretKey
31
33
  }
32
34
  },
33
35
 
34
36
  generateX25519KeyPairFromSeed (seed: Uint8Array): KeyPair {
35
- const keypair = x25519.generateKeyPairFromSeed(seed)
37
+ const publicKey = x25519.getPublicKey(seed)
36
38
 
37
39
  return {
38
- publicKey: keypair.publicKey,
39
- privateKey: keypair.secretKey
40
+ publicKey,
41
+ privateKey: seed
40
42
  }
41
43
  },
42
44
 
43
- generateX25519SharedKey (privateKey: Uint8Array, publicKey: Uint8Array): Uint8Array {
44
- return x25519.sharedKey(privateKey, publicKey)
45
+ generateX25519SharedKey (privateKey: Uint8Array | Uint8ArrayList, publicKey: Uint8Array | Uint8ArrayList): Uint8Array {
46
+ return x25519.getSharedSecret(privateKey.subarray(), publicKey.subarray())
45
47
  },
46
48
 
47
- chaCha20Poly1305Encrypt (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32): bytes {
48
- const ctx = new ChaCha20Poly1305(k)
49
-
50
- return ctx.seal(nonce, plaintext, ad)
49
+ chaCha20Poly1305Encrypt (plaintext: Uint8Array | Uint8ArrayList, nonce: Uint8Array, ad: Uint8Array, k: Uint8Array): Uint8Array {
50
+ return chacha20poly1305(k, nonce, ad).encrypt(plaintext.subarray())
51
51
  },
52
52
 
53
- chaCha20Poly1305Decrypt (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32, dst?: Uint8Array): bytes | null {
54
- const ctx = new ChaCha20Poly1305(k)
55
-
56
- return ctx.open(nonce, ciphertext, ad, dst)
53
+ chaCha20Poly1305Decrypt (ciphertext: Uint8Array | Uint8ArrayList, nonce: Uint8Array, ad: Uint8Array, k: Uint8Array, dst?: Uint8Array): Uint8Array {
54
+ return chacha20poly1305(k, nonce, ad).decrypt(ciphertext.subarray(), dst)
57
55
  }
58
56
  }
package/src/crypto.ts CHANGED
@@ -1,16 +1,27 @@
1
- import type { bytes32, bytes } from './@types/basic.js'
2
- import type { Hkdf } from './@types/handshake.js'
3
- import type { KeyPair } from './@types/libp2p.js'
1
+ import type { ICrypto, KeyPair } from './types.js'
2
+ import type { Uint8ArrayList } from 'uint8arraylist'
4
3
 
4
+ /** Underlying crypto implementation, meant to be overridable */
5
5
  export interface ICryptoInterface {
6
- hashSHA256: (data: Uint8Array) => Uint8Array
6
+ hashSHA256(data: Uint8Array | Uint8ArrayList): Uint8Array
7
7
 
8
- getHKDF: (ck: bytes32, ikm: Uint8Array) => Hkdf
8
+ getHKDF(ck: Uint8Array, ikm: Uint8Array): [Uint8Array, Uint8Array, Uint8Array]
9
9
 
10
- generateX25519KeyPair: () => KeyPair
11
- generateX25519KeyPairFromSeed: (seed: Uint8Array) => KeyPair
12
- generateX25519SharedKey: (privateKey: Uint8Array, publicKey: Uint8Array) => Uint8Array
10
+ generateX25519KeyPair(): KeyPair
11
+ generateX25519KeyPairFromSeed(seed: Uint8Array): KeyPair
12
+ generateX25519SharedKey(privateKey: Uint8Array | Uint8ArrayList, publicKey: Uint8Array | Uint8ArrayList): Uint8Array
13
13
 
14
- chaCha20Poly1305Encrypt: (plaintext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32) => bytes
15
- chaCha20Poly1305Decrypt: (ciphertext: Uint8Array, nonce: Uint8Array, ad: Uint8Array, k: bytes32, dst?: Uint8Array) => bytes | null
14
+ chaCha20Poly1305Encrypt(plaintext: Uint8Array | Uint8ArrayList, nonce: Uint8Array, ad: Uint8Array, k: Uint8Array): Uint8ArrayList | Uint8Array
15
+ chaCha20Poly1305Decrypt(ciphertext: Uint8Array | Uint8ArrayList, nonce: Uint8Array, ad: Uint8Array, k: Uint8Array, dst?: Uint8Array): Uint8ArrayList | Uint8Array
16
+ }
17
+
18
+ export function wrapCrypto (crypto: ICryptoInterface): ICrypto {
19
+ return {
20
+ generateKeypair: crypto.generateX25519KeyPair,
21
+ dh: (keypair, publicKey) => crypto.generateX25519SharedKey(keypair.privateKey, publicKey).subarray(0, 32),
22
+ encrypt: crypto.chaCha20Poly1305Encrypt,
23
+ decrypt: crypto.chaCha20Poly1305Decrypt,
24
+ hash: crypto.hashSHA256,
25
+ hkdf: crypto.getHKDF
26
+ }
16
27
  }
package/src/encoder.ts CHANGED
@@ -1,81 +1,24 @@
1
- import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
2
- import type { bytes } from './@types/basic.js'
3
- import type { MessageBuffer } from './@types/handshake.js'
4
- import type { LengthDecoderFunction } from 'it-length-prefixed'
1
+ import { allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc'
5
2
  import type { Uint8ArrayList } from 'uint8arraylist'
6
3
 
7
- const allocUnsafe = (len: number): Uint8Array => {
8
- if (globalThis.Buffer) {
9
- return globalThis.Buffer.allocUnsafe(len)
10
- }
11
-
12
- return new Uint8Array(len)
13
- }
14
-
15
4
  export const uint16BEEncode = (value: number): Uint8Array => {
16
- const target = allocUnsafe(2)
17
- new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(0, value, false)
5
+ const target = uint8ArrayAllocUnsafe(2)
6
+ target[0] = value >> 8
7
+ target[1] = value
18
8
  return target
19
9
  }
20
10
  uint16BEEncode.bytes = 2
21
11
 
22
- export const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {
23
- if (data.length < 2) throw RangeError('Could not decode int16BE')
12
+ export const uint16BEDecode = (data: Uint8Array | Uint8ArrayList): number => {
13
+ if (data.length < 2) { throw RangeError('Could not decode int16BE') }
24
14
 
25
15
  if (data instanceof Uint8Array) {
26
- return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)
16
+ let value = 0
17
+ value += data[0] << 8
18
+ value += data[1]
19
+ return value
27
20
  }
28
21
 
29
22
  return data.getUint16(0)
30
23
  }
31
24
  uint16BEDecode.bytes = 2
32
-
33
- // Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)
34
-
35
- export function encode0 (message: MessageBuffer): bytes {
36
- return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)
37
- }
38
-
39
- export function encode1 (message: MessageBuffer): bytes {
40
- return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)
41
- }
42
-
43
- export function encode2 (message: MessageBuffer): bytes {
44
- return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)
45
- }
46
-
47
- export function decode0 (input: bytes): MessageBuffer {
48
- if (input.length < 32) {
49
- throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')
50
- }
51
-
52
- return {
53
- ne: input.subarray(0, 32),
54
- ciphertext: input.subarray(32, input.length),
55
- ns: new Uint8Array(0)
56
- }
57
- }
58
-
59
- export function decode1 (input: bytes): MessageBuffer {
60
- if (input.length < 80) {
61
- throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')
62
- }
63
-
64
- return {
65
- ne: input.subarray(0, 32),
66
- ns: input.subarray(32, 80),
67
- ciphertext: input.subarray(80, input.length)
68
- }
69
- }
70
-
71
- export function decode2 (input: bytes): MessageBuffer {
72
- if (input.length < 48) {
73
- throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')
74
- }
75
-
76
- return {
77
- ne: new Uint8Array(0),
78
- ns: input.subarray(0, 48),
79
- ciphertext: input.subarray(48, input.length)
80
- }
81
- }
package/src/errors.ts ADDED
@@ -0,0 +1,10 @@
1
+ export class InvalidCryptoExchangeError extends Error {
2
+ public code: string
3
+
4
+ constructor (message = 'Invalid crypto exchange') {
5
+ super(message)
6
+ this.code = InvalidCryptoExchangeError.code
7
+ }
8
+
9
+ static readonly code = 'ERR_INVALID_CRYPTO_EXCHANGE'
10
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,58 @@
1
+ /**
2
+ * @packageDocumentation
3
+ *
4
+ * This repository contains TypeScript implementation of noise protocol, an encryption protocol used in libp2p.
5
+ *
6
+ * ## Usage
7
+ *
8
+ * Install with `yarn add @libp2p/noise` or `npm i @libp2p/noise`.
9
+ *
10
+ * Example of using default noise configuration and passing it to the libp2p config:
11
+ *
12
+ * ```ts
13
+ * import {createLibp2p} from "libp2p"
14
+ * import {noise} from "@libp2p/noise"
15
+ *
16
+ * //custom noise configuration, pass it instead of `noise()`
17
+ * //x25519 private key
18
+ * const n = noise({ staticNoiseKey });
19
+ *
20
+ * const libp2p = await createLibp2p({
21
+ * connectionEncrypters: [noise()],
22
+ * //... other options
23
+ * })
24
+ * ```
25
+ *
26
+ * See the [NoiseInit](https://github.com/ChainSafe/js-libp2p-noise/blob/master/src/noise.ts#L22-L30) interface for noise configuration options.
27
+ *
28
+ * ## API
29
+ *
30
+ * This module exposes an implementation of the [ConnectionEncrypter](https://libp2p.github.io/js-libp2p/interfaces/_libp2p_interface.ConnectionEncrypter.html) interface.
31
+ *
32
+ * ## Bring your own crypto
33
+ *
34
+ * You can provide a custom crypto implementation (instead of the default, based on [@noble](https://paulmillr.com/noble/)) by adding a `crypto` field to the init argument passed to the `Noise` factory.
35
+ *
36
+ * The implementation must conform to the `ICryptoInterface`, defined in <https://github.com/ChainSafe/js-libp2p-noise/blob/master/src/crypto.ts>
37
+ */
38
+
1
39
  import { Noise } from './noise.js'
2
- import type { NoiseInit } from './noise.js'
3
- import type { NoiseExtensions } from './proto/payload.js'
4
- import type { ConnectionEncrypter } from '@libp2p/interface/connection-encrypter'
5
- export type { ICryptoInterface } from './crypto.js'
40
+ import type { NoiseInit, NoiseExtensions } from './noise.js'
41
+ import type { KeyPair } from './types.js'
42
+ import type { ComponentLogger, ConnectionEncrypter, Metrics, PeerId, PrivateKey, Upgrader } from '@libp2p/interface'
43
+
6
44
  export { pureJsCrypto } from './crypto/js.js'
45
+ export type { ICryptoInterface } from './crypto.js'
46
+ export type { NoiseInit, NoiseExtensions, KeyPair }
47
+
48
+ export interface NoiseComponents {
49
+ peerId: PeerId
50
+ privateKey: PrivateKey
51
+ logger: ComponentLogger
52
+ upgrader: Upgrader
53
+ metrics?: Metrics
54
+ }
7
55
 
8
- export function noise (init: NoiseInit = {}): () => ConnectionEncrypter<NoiseExtensions> {
9
- return () => new Noise(init)
56
+ export function noise (init: NoiseInit = {}): (components: NoiseComponents) => ConnectionEncrypter<NoiseExtensions> {
57
+ return (components: NoiseComponents) => new Noise(components, init)
10
58
  }
package/src/logger.ts CHANGED
@@ -1,30 +1,28 @@
1
- import { type Logger, logger } from '@libp2p/logger'
2
1
  import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
3
2
  import { DUMP_SESSION_KEYS } from './constants.js'
4
- import type { NoiseSession } from './@types/handshake.js'
5
- import type { KeyPair } from './@types/libp2p.js'
6
-
7
- const log = logger('libp2p:noise')
8
-
9
- export { log as logger }
10
-
11
- let keyLogger: Logger
12
- if (DUMP_SESSION_KEYS) {
13
- keyLogger = log
14
- } else {
15
- keyLogger = Object.assign(() => { /* do nothing */ }, {
16
- enabled: false,
17
- trace: () => {},
18
- error: () => {}
19
- })
20
- }
3
+ import type { CipherState } from './protocol.js'
4
+ import type { KeyPair } from './types.js'
5
+ import type { Logger } from '@libp2p/interface'
6
+ import type { Uint8ArrayList } from 'uint8arraylist'
7
+
8
+ export function logLocalStaticKeys (s: KeyPair | undefined, keyLogger: Logger): void {
9
+ if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {
10
+ return
11
+ }
21
12
 
22
- export function logLocalStaticKeys (s: KeyPair): void {
23
- keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)
24
- keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)
13
+ if (s) {
14
+ keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`)
15
+ keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`)
16
+ } else {
17
+ keyLogger('Missing local static keys.')
18
+ }
25
19
  }
26
20
 
27
- export function logLocalEphemeralKeys (e: KeyPair | undefined): void {
21
+ export function logLocalEphemeralKeys (e: KeyPair | undefined, keyLogger: Logger): void {
22
+ if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {
23
+ return
24
+ }
25
+
28
26
  if (e) {
29
27
  keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`)
30
28
  keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`)
@@ -33,19 +31,35 @@ export function logLocalEphemeralKeys (e: KeyPair | undefined): void {
33
31
  }
34
32
  }
35
33
 
36
- export function logRemoteStaticKey (rs: Uint8Array): void {
37
- keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs, 'hex')}`)
38
- }
34
+ export function logRemoteStaticKey (rs: Uint8Array | Uint8ArrayList | undefined, keyLogger: Logger): void {
35
+ if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {
36
+ return
37
+ }
39
38
 
40
- export function logRemoteEphemeralKey (re: Uint8Array): void {
41
- keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re, 'hex')}`)
39
+ if (rs) {
40
+ keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs.subarray(), 'hex')}`)
41
+ } else {
42
+ keyLogger('Missing remote static public key.')
43
+ }
42
44
  }
43
45
 
44
- export function logCipherState (session: NoiseSession): void {
45
- if (session.cs1 && session.cs2) {
46
- keyLogger(`CIPHER_STATE_1 ${session.cs1.n.getUint64()} ${uint8ArrayToString(session.cs1.k, 'hex')}`)
47
- keyLogger(`CIPHER_STATE_2 ${session.cs2.n.getUint64()} ${uint8ArrayToString(session.cs2.k, 'hex')}`)
46
+ export function logRemoteEphemeralKey (re: Uint8Array | Uint8ArrayList | undefined, keyLogger: Logger): void {
47
+ if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {
48
+ return
49
+ }
50
+
51
+ if (re) {
52
+ keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re.subarray(), 'hex')}`)
48
53
  } else {
49
- keyLogger('Missing cipher state.')
54
+ keyLogger('Missing remote ephemeral keys.')
50
55
  }
51
56
  }
57
+
58
+ export function logCipherState (cs1: CipherState, cs2: CipherState, keyLogger: Logger): void {
59
+ if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {
60
+ return
61
+ }
62
+
63
+ keyLogger(`CIPHER_STATE_1 ${cs1.n.getUint64()} ${cs1.k && uint8ArrayToString(cs1.k, 'hex')}`)
64
+ keyLogger(`CIPHER_STATE_2 ${cs2.n.getUint64()} ${cs2.k && uint8ArrayToString(cs2.k, 'hex')}`)
65
+ }
package/src/metrics.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Counter, Metrics } from '@libp2p/interface/metrics'
1
+ import type { Counter, Metrics } from '@libp2p/interface'
2
2
 
3
3
  export type MetricsRegistry = Record<string, Counter>
4
4