forked from Irys-xyz/bundles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataItem.ts
285 lines (234 loc) · 7.97 KB
/
DataItem.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import { byteArrayToLong } from "./utils";
import base64url from "base64url";
import { Buffer } from "buffer";
import { sign } from "./ar-data-bundle";
import type { BundleItem } from "./BundleItem";
import type { Signer } from "./signing/index";
import { indexToType } from "./signing/index";
import getSignatureData from "./ar-data-base";
import { SIG_CONFIG, SignatureConfig } from "./constants";
import { getCryptoDriver } from "$/utils";
import { deserializeTags } from "./tags";
import { createHash } from "crypto";
import type { Base58String, Base64URLString } from "./types";
import base58 from "bs58";
export const MIN_BINARY_SIZE = 80;
export const MAX_TAG_BYTES = 4096;
export class DataItem implements BundleItem {
private readonly binary: Buffer;
private _id: Buffer;
constructor(binary: Buffer) {
this.binary = binary;
}
static isDataItem(obj: any): obj is DataItem {
return obj.binary !== undefined;
}
get signatureType(): SignatureConfig {
const signatureTypeVal: number = byteArrayToLong(this.binary.subarray(0, 2));
if (SignatureConfig?.[signatureTypeVal] !== undefined) {
return signatureTypeVal;
}
throw new Error("Unknown signature type: " + signatureTypeVal);
}
async isValid(): Promise<boolean> {
return DataItem.verify(this.binary);
}
get id(): Base58String {
return base58.encode(this.rawId);
}
set id(id: string) {
this._id = base64url.toBuffer(id);
}
get rawId(): Buffer {
return createHash("sha256").update(this.rawSignature).digest();
}
set rawId(id: Buffer) {
this._id = id;
}
get rawSignature(): Buffer {
return this.binary.subarray(2, 2 + this.signatureLength);
}
get signature(): Base64URLString {
return base64url.encode(this.rawSignature);
}
set rawOwner(pubkey: Buffer) {
if (pubkey.byteLength != this.ownerLength)
throw new Error(`Expected raw owner (pubkey) to be ${this.ownerLength} bytes, got ${pubkey.byteLength} bytes.`);
this.binary.set(pubkey, 2 + this.signatureLength);
}
get rawOwner(): Buffer {
return this.binary.subarray(2 + this.signatureLength, 2 + this.signatureLength + this.ownerLength);
}
get signatureLength(): number {
return SIG_CONFIG[this.signatureType].sigLength;
}
get owner(): Base64URLString {
return base64url.encode(this.rawOwner);
}
get ownerLength(): number {
return SIG_CONFIG[this.signatureType].pubLength;
}
get rawTarget(): Buffer {
const targetStart = this.getTargetStart();
const isPresent = this.binary[targetStart] == 1;
return isPresent ? this.binary.subarray(targetStart + 1, targetStart + 33) : Buffer.alloc(0);
}
get target(): Base64URLString {
return base64url.encode(this.rawTarget);
}
get rawAnchor(): Buffer {
const anchorStart = this.getAnchorStart();
const isPresent = this.binary[anchorStart] == 1;
return isPresent ? this.binary.subarray(anchorStart + 1, anchorStart + 33) : Buffer.alloc(0);
}
get anchor(): Base64URLString {
return base64url.encode(this.rawAnchor); /* .toString(); */
}
get rawTags(): Buffer {
const tagsStart = this.getTagsStart();
const tagsSize = byteArrayToLong(this.binary.subarray(tagsStart + 8, tagsStart + 16));
return this.binary.subarray(tagsStart + 16, tagsStart + 16 + tagsSize);
}
get tags(): { name: string; value: string }[] {
const tagsStart = this.getTagsStart();
const tagsCount = byteArrayToLong(this.binary.subarray(tagsStart, tagsStart + 8));
if (tagsCount == 0) {
return [];
}
const tagsSize = byteArrayToLong(this.binary.subarray(tagsStart + 8, tagsStart + 16));
return deserializeTags(Buffer.from(this.binary.subarray(tagsStart + 16, tagsStart + 16 + tagsSize)));
}
get tagsB64Url(): { name: Base64URLString; value: Base64URLString }[] {
const _tags = this.tags;
return _tags.map((t) => ({
name: base64url.encode(t.name),
value: base64url.encode(t.value),
}));
}
getStartOfData(): number {
const tagsStart = this.getTagsStart();
const numberOfTagBytesArray = this.binary.subarray(tagsStart + 8, tagsStart + 16);
const numberOfTagBytes = byteArrayToLong(numberOfTagBytesArray);
return tagsStart + 16 + numberOfTagBytes;
}
get rawData(): Buffer {
const tagsStart = this.getTagsStart();
const numberOfTagBytesArray = this.binary.subarray(tagsStart + 8, tagsStart + 16);
const numberOfTagBytes = byteArrayToLong(numberOfTagBytesArray);
const dataStart = tagsStart + 16 + numberOfTagBytes;
return this.binary.subarray(dataStart, this.binary.length);
}
get data(): Base64URLString {
return base64url.encode(this.rawData);
}
/**
* UNSAFE!!
* DO NOT MUTATE THE BINARY ARRAY. THIS WILL CAUSE UNDEFINED BEHAVIOUR.
*/
getRaw(): Buffer {
return this.binary;
}
public async sign(signer: Signer): Promise<Buffer> {
this._id = await sign(this, signer);
return this.rawId;
}
public async setSignature(signature: Buffer): Promise<void> {
this.binary.set(signature, 2);
this._id = Buffer.from(await getCryptoDriver().hash(signature));
}
public isSigned(): boolean {
return (this._id?.length ?? 0) > 0;
}
/**
* Returns a JSON representation of a DataItem
*/
// eslint-disable-next-line @typescript-eslint/naming-convention
public toJSON(): {
owner: string;
data: string;
signature: string;
target: string;
tags: { name: Base64URLString; value: Base64URLString }[];
} {
return {
signature: this.signature,
owner: this.owner,
target: this.target,
tags: this.tags.map((t) => ({
name: base64url.encode(t.name),
value: base64url.encode(t.value),
})),
data: this.data,
};
}
/**
* Verifies a `Buffer` and checks it fits the format of a DataItem
*
* A binary is valid iff:
* - the tags are encoded correctly
*/
static async verify(buffer: Buffer): Promise<boolean> {
if (buffer.byteLength < MIN_BINARY_SIZE) {
return false;
}
const item = new DataItem(buffer);
const sigType = item.signatureType;
const tagsStart = item.getTagsStart();
const numberOfTags = byteArrayToLong(buffer.subarray(tagsStart, tagsStart + 8));
const numberOfTagBytesArray = buffer.subarray(tagsStart + 8, tagsStart + 16);
const numberOfTagBytes = byteArrayToLong(numberOfTagBytesArray);
if (numberOfTagBytes > MAX_TAG_BYTES) return false;
if (numberOfTags > 0) {
try {
const tags: { name: string; value: string }[] = deserializeTags(
Buffer.from(buffer.subarray(tagsStart + 16, tagsStart + 16 + numberOfTagBytes)),
);
if (tags.length !== numberOfTags) {
return false;
}
} catch (e) {
return false;
}
}
// eslint-disable-next-line @typescript-eslint/naming-convention
const Signer = indexToType[sigType];
const signatureData = await getSignatureData(item);
return await Signer.verify(item.rawOwner, signatureData, item.rawSignature);
}
public async getSignatureData(): Promise<Uint8Array> {
return getSignatureData(this);
}
/**
* Returns the start byte of the tags section (number of tags)
*
* @private
*/
private getTagsStart(): number {
const targetStart = this.getTargetStart();
const targetPresent = this.binary[targetStart] == 1;
let tagsStart = targetStart + (targetPresent ? 33 : 1);
const anchorPresent = this.binary[tagsStart] == 1;
tagsStart += anchorPresent ? 33 : 1;
return tagsStart;
}
/**
* Returns the start byte of the tags section (number of tags)
*
* @private
*/
private getTargetStart(): number {
return 2 + this.signatureLength + this.ownerLength;
}
/**
* Returns the start byte of the tags section (number of tags)
*
* @private
*/
private getAnchorStart(): number {
let anchorStart = this.getTargetStart() + 1;
const targetPresent = this.binary[this.getTargetStart()] == 1;
anchorStart += targetPresent ? 32 : 0;
return anchorStart;
}
}
export default DataItem;