-
Notifications
You must be signed in to change notification settings - Fork 284
/
serializer.ts
71 lines (57 loc) · 2.67 KB
/
serializer.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
import ByteBuffer from "bytebuffer";
import { PreviousBlockIdFormatError } from "../errors";
import { IBlockData, ITransactionData } from "../interfaces";
import { configManager } from "../managers/config";
import { Utils } from "../transactions";
import { Block } from "./block";
export class Serializer {
public static serializeWithTransactions(block: IBlockData): Buffer {
const transactions: ITransactionData[] = block.transactions || [];
block.numberOfTransactions = block.numberOfTransactions || transactions.length;
const serializedHeader: Buffer = this.serialize(block);
const buffer: ByteBuffer = new ByteBuffer(serializedHeader.length + transactions.length * 4, true)
.append(serializedHeader)
.skip(transactions.length * 4);
for (let i = 0; i < transactions.length; i++) {
const serialized: Buffer = Utils.toBytes(transactions[i]);
buffer.writeUint32(serialized.length, serializedHeader.length + i * 4);
buffer.append(serialized);
}
return buffer.flip().toBuffer();
}
public static serialize(block: IBlockData, includeSignature: boolean = true): Buffer {
const buffer: ByteBuffer = new ByteBuffer(512, true);
this.serializeHeader(block, buffer);
if (includeSignature) {
this.serializeSignature(block, buffer);
}
return buffer.flip().toBuffer();
}
private static serializeHeader(block: IBlockData, buffer: ByteBuffer): void {
const constants = configManager.getMilestone(block.height - 1 || 1);
if (constants.block.idFullSha256) {
if (block.previousBlock.length !== 64) {
throw new PreviousBlockIdFormatError(block.height, block.previousBlock);
}
block.previousBlockHex = block.previousBlock;
} else {
block.previousBlockHex = Block.toBytesHex(block.previousBlock);
}
buffer.writeUint32(block.version);
buffer.writeUint32(block.timestamp);
buffer.writeUint32(block.height);
buffer.append(block.previousBlockHex, "hex");
buffer.writeUint32(block.numberOfTransactions);
buffer.writeUint64(+block.totalAmount.toFixed());
buffer.writeUint64(+block.totalFee.toFixed());
buffer.writeUint64(+block.reward.toFixed());
buffer.writeUint32(block.payloadLength);
buffer.append(block.payloadHash, "hex");
buffer.append(block.generatorPublicKey, "hex");
}
private static serializeSignature(block: IBlockData, buffer: ByteBuffer): void {
if (block.blockSignature) {
buffer.append(block.blockSignature, "hex");
}
}
}