forked from ChainSafe/js-libp2p-noise
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.ts
More file actions
80 lines (64 loc) · 2.42 KB
/
encoder.ts
File metadata and controls
80 lines (64 loc) · 2.42 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
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
import { bytes } from './@types/basic'
import { MessageBuffer } from './@types/handshake'
import BufferList from 'bl/BufferList'
import { concat as uint8ArrayConcat } from 'uint8arrays/concat'
const allocUnsafe = (len: number): Uint8Array => {
if (globalThis.Buffer) {
return globalThis.Buffer.allocUnsafe(len)
}
return new Uint8Array(len)
}
export const uint16BEEncode = (value: number, target: Uint8Array, offset: number): Uint8Array => {
target = target || allocUnsafe(2)
new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(offset, value, false)
return target
}
uint16BEEncode.bytes = 2
export const uint16BEDecode = (data: Uint8Array | BufferList): number => {
if (data.length < 2) throw RangeError('Could not decode int16BE')
if (data instanceof BufferList) {
return data.readUInt16BE(0)
}
return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false)
}
uint16BEDecode.bytes = 2
// Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1)
export function encode0 (message: MessageBuffer): bytes {
return uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)
}
export function encode1 (message: MessageBuffer): bytes {
return uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)
}
export function encode2 (message: MessageBuffer): bytes {
return uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)
}
export function decode0 (input: bytes): MessageBuffer {
if (input.length < 32) {
throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')
}
return {
ne: input.slice(0, 32),
ciphertext: input.slice(32, input.length),
ns: new Uint8Array(0)
}
}
export function decode1 (input: bytes): MessageBuffer {
if (input.length < 80) {
throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')
}
return {
ne: input.slice(0, 32),
ns: input.slice(32, 80),
ciphertext: input.slice(80, input.length)
}
}
export function decode2 (input: bytes): MessageBuffer {
if (input.length < 48) {
throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')
}
return {
ne: new Uint8Array(0),
ns: input.slice(0, 48),
ciphertext: input.slice(48, input.length)
}
}