@@ -16,6 +16,8 @@ import { uint16BEDecode, uint16BEEncode } from './encoder.js'
1616import { XXHandshake } from './handshake-xx.js'
1717import { getPayload } from './utils.js'
1818import type { NoiseExtensions } from './proto/payload.js'
19+ import type { Metrics } from '@libp2p/interface-metrics'
20+ import { MetricsRegistry , registerMetrics } from './metrics.js'
1921
2022interface HandshakeParams {
2123 connection : ProtobufStream
@@ -32,6 +34,7 @@ export interface NoiseInit {
3234 extensions ?: NoiseExtensions
3335 crypto ?: ICryptoInterface
3436 prologueBytes ?: Uint8Array
37+ metrics ?: Metrics
3538}
3639
3740export class Noise implements INoiseConnection {
@@ -41,12 +44,14 @@ export class Noise implements INoiseConnection {
4144 private readonly prologue : Uint8Array
4245 private readonly staticKeys : KeyPair
4346 private readonly extensions ?: NoiseExtensions
47+ private readonly metrics ?: MetricsRegistry
4448
4549 constructor ( init : NoiseInit = { } ) {
46- const { staticNoiseKey, extensions, crypto, prologueBytes } = init
50+ const { staticNoiseKey, extensions, crypto, prologueBytes, metrics } = init
4751
4852 this . crypto = crypto ?? stablelib
4953 this . extensions = extensions
54+ this . metrics = metrics ? registerMetrics ( metrics ) : undefined
5055
5156 if ( staticNoiseKey ) {
5257 // accepts x25519 private key of length 32
@@ -153,7 +158,9 @@ export class Noise implements INoiseConnection {
153158 await handshake . propose ( )
154159 await handshake . exchange ( )
155160 await handshake . finish ( )
161+ this . metrics ?. xxHandshakeSuccesses . increment ( )
156162 } catch ( e : unknown ) {
163+ this . metrics ?. xxHandshakeErrors . increment ( )
157164 if ( e instanceof Error ) {
158165 e . message = `Error occurred during XX handshake: ${ e . message } `
159166 throw e
@@ -173,10 +180,10 @@ export class Noise implements INoiseConnection {
173180
174181 await pipe (
175182 secure , // write to wrapper
176- encryptStream ( handshake ) , // encrypt data + prefix with message length
183+ encryptStream ( handshake , this . metrics ) , // encrypt data + prefix with message length
177184 network , // send to the remote peer
178185 decode ( { lengthDecoder : uint16BEDecode } ) , // read message length prefix
179- decryptStream ( handshake ) , // decrypt the incoming data
186+ decryptStream ( handshake , this . metrics ) , // decrypt the incoming data
180187 secure // pipe to the wrapper
181188 )
182189
0 commit comments