forked from ChainSafe/js-libp2p-noise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnonce.ts
More file actions
50 lines (42 loc) · 1.66 KB
/
nonce.ts
File metadata and controls
50 lines (42 loc) · 1.66 KB
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
import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc'
import type { bytes, uint64 } from './@types/basic.js'
export const MIN_NONCE = 0
// For performance reasons, the nonce is represented as a JS `number`
// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use
// 4 bytes to store the data for performance reason.
// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2
// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.
// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.
export const MAX_NONCE = 0xffffffff
const ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed'
/**
* The nonce is an uint that's increased over time.
* Maintaining different representations help improve performance.
*/
export class Nonce {
private n: uint64
private readonly bytes: bytes
private readonly view: DataView
constructor (n = MIN_NONCE) {
this.n = n
this.bytes = uint8ArrayAlloc(12)
this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength)
this.view.setUint32(4, n, true)
}
increment (): void {
this.n++
// Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.
this.view.setUint32(4, this.n, true)
}
getBytes (): bytes {
return this.bytes
}
getUint64 (): uint64 {
return this.n
}
assertValue (): void {
if (this.n > MAX_NONCE) {
throw new Error(ERR_MAX_NONCE)
}
}
}