-
Notifications
You must be signed in to change notification settings - Fork 0
/
piece.ts
65 lines (57 loc) · 1.98 KB
/
piece.ts
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
// Copyright (C) 2020-2022 Russell Clarey. All rights reserved. MIT license.
import { InfoDict } from "./metainfo.ts";
import { PieceMsg, RequestMsg } from "./protocol.ts";
export const BLOCK_SIZE = 1024 * 16;
function stringify(msg: RequestMsg | PieceMsg) {
return JSON.stringify(
"block" in msg
? { ...msg, block: `[Uint8Array; ${msg.block.length}]` }
: msg,
);
}
function pieceLength(n: number, info: InfoDict) {
return (n === info.pieces.length - 1 && info.length % info.pieceLength) ||
info.pieceLength;
}
export function validateRequestedBlock(info: InfoDict, msg: RequestMsg) {
if (msg.index >= info.pieces.length) {
throw new Error(
`request message with invalid piece index ${stringify(msg)}`,
);
}
const reqEnd = msg.offset + msg.length;
const lastPieceLength = pieceLength(info.pieces.length - 1, info);
if (
(msg.index === info.pieces.length - 1 && reqEnd > lastPieceLength) ||
reqEnd > info.pieceLength
) {
throw new Error(
`request message with invalid block length ${stringify(msg)}`,
);
}
}
export function validateReceivedBlock(info: InfoDict, msg: PieceMsg) {
if (msg.index >= info.pieces.length) {
throw new Error(`piece message with invalid piece index ${stringify(msg)}`);
}
if (msg.offset % BLOCK_SIZE !== 0) {
throw new Error(
`piece message with invalid block offset ${stringify(msg)}`,
);
}
const pieceLen = pieceLength(msg.index, info);
const numBlocks = Math.ceil(pieceLen / BLOCK_SIZE);
const nBlock = Math.floor(msg.offset / BLOCK_SIZE);
if (msg.index === info.pieces.length - 1 && nBlock === numBlocks - 1) {
const lastBlockLength = pieceLen % BLOCK_SIZE || BLOCK_SIZE;
if (msg.block.length !== lastBlockLength) {
throw new Error(
`piece message with invalid last block length ${stringify(msg)}`,
);
}
} else if (msg.block.length !== BLOCK_SIZE) {
throw new Error(
`piece message with invalid block length ${stringify(msg)}`,
);
}
}