/
BlockMarshaler.cs
306 lines (269 loc) · 11.5 KB
/
BlockMarshaler.cs
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Crypto;
using Libplanet.Tx;
namespace Libplanet.Blocks
{
/// <summary>
/// Marshaling and unmarshaling block data.
/// </summary>
public static class BlockMarshaler
{
private const string TimestampFormat = "yyyy-MM-ddTHH:mm:ss.ffffffZ";
// Header fields:
private static readonly byte[] ProtocolVersionKey = { 0x00 };
private static readonly byte[] IndexKey = { 0x69 }; // 'i'
private static readonly byte[] TimestampKey = { 0x74 }; // 't'
private static readonly byte[] DifficultyKey = { 0x64 }; // 'd'
private static readonly byte[] TotalDifficultyKey = { 0x54 }; // 'T'
private static readonly byte[] NonceKey = { 0x6e }; // 'n'
private static readonly byte[] MinerKey = { 0x6d }; // 'm'
private static readonly byte[] PublicKeyKey = { 0x50 }; // 'P'
private static readonly byte[] PreviousHashKey = { 0x70 }; // 'p'
private static readonly byte[] TxHashKey = { 0x78 }; // 'x'
private static readonly byte[] HashKey = { 0x68 }; // 'h'
private static readonly byte[] StateRootHashKey = { 0x73 }; // 's'
private static readonly byte[] SignatureKey = { 0x53 }; // 'S'
private static readonly byte[] PreEvaluationHashKey = { 0x63 }; // 'c'
// Block fields:
private static readonly byte[] HeaderKey = { 0x48 }; // 'H'
private static readonly byte[] TransactionsKey = { 0x54 }; // 'T'
public static Dictionary MarshalBlockMetadata(IBlockMetadata metadata)
{
string timestamp =
metadata.Timestamp.ToString(TimestampFormat, CultureInfo.InvariantCulture);
Dictionary dict = Dictionary.Empty
.Add(IndexKey, metadata.Index)
.Add(TimestampKey, timestamp)
.Add(DifficultyKey, metadata.Difficulty)
.Add(TotalDifficultyKey, (IValue)new Integer(metadata.TotalDifficulty));
if (metadata.ProtocolVersion != 0)
{
dict = dict.Add(ProtocolVersionKey, metadata.ProtocolVersion);
}
if (metadata.PreviousHash is { } prev)
{
dict = dict.Add(PreviousHashKey, prev.ByteArray);
}
if (metadata.TxHash is { } th)
{
dict = dict.Add(TxHashKey, th.ByteArray);
}
dict = metadata.PublicKey is { } pubKey
? dict.Add(PublicKeyKey, pubKey.Format(compress: true))
: dict.Add(MinerKey, metadata.Miner.ByteArray);
return dict;
}
public static Dictionary MarshalPreEvaluationBlockHeader(
Dictionary marshaledMetadata,
Nonce nonce,
ImmutableArray<byte> preEvaluationHash
)
{
Dictionary dict = marshaledMetadata
.Add(NonceKey, nonce.ByteArray);
if (!preEvaluationHash.IsDefaultOrEmpty)
{
dict = dict.Add(PreEvaluationHashKey, preEvaluationHash);
}
return dict;
}
public static Dictionary MarshalPreEvaluationBlockHeader(IPreEvaluationBlockHeader header)
{
return MarshalPreEvaluationBlockHeader(
MarshalBlockMetadata(header),
header.Nonce,
header.PreEvaluationHash
);
}
public static Dictionary MarshalBlockHeader(
Dictionary marshaledPreEvaluatedBlockHeader,
HashDigest<SHA256> stateRootHash,
ImmutableArray<byte>? signature,
BlockHash hash
)
{
Dictionary dict = marshaledPreEvaluatedBlockHeader
.Add(StateRootHashKey, stateRootHash.ByteArray)
.Add(HashKey, hash.ByteArray);
if (signature is { } sig)
{
dict = dict.Add(SignatureKey, sig);
}
return dict;
}
public static Dictionary MarshalBlockHeader(this IBlockHeader header) =>
MarshalBlockHeader(
MarshalPreEvaluationBlockHeader(header),
header.StateRootHash,
header.Signature,
header.Hash
);
public static List MarshalTransactions<T>(this IReadOnlyList<Transaction<T>> txs)
where T : IAction, new()
=>
new List(txs.Select(tx => new Binary(tx.Serialize(true))).Cast<IValue>());
public static Dictionary MarshalBlock(
Dictionary marshaledBlockHeader,
List marshaledTransactions
)
{
Dictionary dict = Dictionary.Empty
.Add(HeaderKey, marshaledBlockHeader);
if (marshaledTransactions.Any())
{
dict = dict.Add(TransactionsKey, (IValue)marshaledTransactions);
}
return dict;
}
public static Dictionary MarshalBlock<T>(this Block<T> block)
where T : IAction, new()
=>
MarshalBlock(
MarshalBlockHeader(block.Header),
MarshalTransactions(block.Transactions)
);
public static Dictionary AppendTxToMarshaledBlock<T>(
Dictionary marshaledBlock,
Transaction<T> tx
)
where T : IAction, new()
{
List marshaledTxs;
try
{
marshaledTxs = (List)marshaledBlock[TransactionsKey];
}
catch (KeyNotFoundException)
{
marshaledTxs = List.Empty;
}
marshaledTxs = marshaledTxs.Add(tx.ToBencodex(true));
return marshaledBlock.SetItem(TransactionsKey, (IValue)marshaledTxs);
}
public static long UnmarshalBlockMetadataIndex(Dictionary marshaledMetadata) =>
marshaledMetadata.GetValue<Integer>(IndexKey);
public static BlockMetadata UnmarshalBlockMetadata(Dictionary marshaled)
{
var metadata = new BlockMetadata
{
ProtocolVersion = marshaled.ContainsKey(ProtocolVersionKey)
? (int)marshaled.GetValue<Integer>(ProtocolVersionKey)
: 0,
Index = UnmarshalBlockMetadataIndex(marshaled),
Timestamp = DateTimeOffset.ParseExact(
marshaled.GetValue<Text>(TimestampKey),
TimestampFormat,
CultureInfo.InvariantCulture
),
Difficulty = marshaled.GetValue<Integer>(DifficultyKey),
TotalDifficulty = marshaled.GetValue<Integer>(TotalDifficultyKey),
PreviousHash = marshaled.ContainsKey(PreviousHashKey)
? new BlockHash(marshaled.GetValue<Binary>(PreviousHashKey).ByteArray)
: (BlockHash?)null,
TxHash = marshaled.ContainsKey(TxHashKey)
? new HashDigest<SHA256>(
marshaled.GetValue<Binary>(TxHashKey).ByteArray)
: (HashDigest<SHA256>?)null,
};
if (marshaled.ContainsKey(PublicKeyKey))
{
metadata.PublicKey =
new PublicKey(marshaled.GetValue<Binary>(PublicKeyKey).ByteArray);
}
else
{
metadata.Miner = new Address(marshaled.GetValue<Binary>(MinerKey).ByteArray);
}
return metadata;
}
public static (BlockMetadata Metadata, Nonce Nonce, ImmutableArray<byte>? PreEvaluationHash)
UnmarshalPreEvaluationBlockHeader(Dictionary marshaled)
{
BlockMetadata metadata = UnmarshalBlockMetadata(marshaled);
var nonce = new Nonce(marshaled.GetValue<Binary>(NonceKey).ByteArray);
ImmutableArray<byte>? preEvalHash = marshaled.ContainsKey(PreEvaluationHashKey)
? marshaled.GetValue<Binary>(PreEvaluationHashKey).ByteArray
: (ImmutableArray<byte>?)null;
return (metadata, nonce, preEvalHash);
}
public static PreEvaluationBlockHeader UnmarshalPreEvaluationBlockHeader(
HashAlgorithmGetter hashAlgorithmGetter,
Dictionary marshaled
)
{
(BlockMetadata metadata, Nonce nonce, ImmutableArray<byte>? preEvalHash) =
UnmarshalPreEvaluationBlockHeader(marshaled);
HashAlgorithmType hashAlgorithm = hashAlgorithmGetter(metadata.Index);
if (preEvalHash is { } peh)
{
return new PreEvaluationBlockHeader(
metadata,
hashAlgorithm,
nonce,
preEvaluationHash: peh
);
}
return new PreEvaluationBlockHeader(metadata, hashAlgorithm, nonce);
}
public static BlockHash UnmarshalBlockHeaderHash(Dictionary marshaledBlockHeader) =>
new BlockHash(marshaledBlockHeader.GetValue<Binary>(HashKey).ByteArray);
public static HashDigest<SHA256> UnmarshalBlockHeaderStateRootHash(
Dictionary marshaledBlockHeader
) =>
new HashDigest<SHA256>(
marshaledBlockHeader.GetValue<Binary>(StateRootHashKey).ByteArray
);
public static ImmutableArray<byte>? UnmarshalBlockHeaderSignature(
Dictionary marshaledBlockHeader
) =>
marshaledBlockHeader.ContainsKey(SignatureKey)
? marshaledBlockHeader.GetValue<Binary>(SignatureKey).ByteArray
: (ImmutableArray<byte>?)null;
public static BlockHeader UnmarshalBlockHeader(
HashAlgorithmGetter hashAlgorithmGetter,
Dictionary marshaled
)
{
PreEvaluationBlockHeader preEvalHeader =
UnmarshalPreEvaluationBlockHeader(hashAlgorithmGetter, marshaled);
HashDigest<SHA256> stateRootHash = UnmarshalBlockHeaderStateRootHash(marshaled);
ImmutableArray<byte>? sig = UnmarshalBlockHeaderSignature(marshaled);
BlockHash hash = UnmarshalBlockHeaderHash(marshaled);
return new BlockHeader(preEvalHeader, stateRootHash, sig, hash);
}
public static IReadOnlyList<Transaction<T>> UnmarshalTransactions<T>(List marshaled)
where T : IAction, new()
=>
marshaled
.Select(tx => Transaction<T>.Deserialize(((Binary)tx).ToByteArray(), true))
.ToImmutableArray();
public static IReadOnlyList<Transaction<T>> UnmarshalBlockTransactions<T>(
Dictionary marshaledBlock
)
where T : IAction, new()
=>
marshaledBlock.ContainsKey(TransactionsKey)
? UnmarshalTransactions<T>(marshaledBlock.GetValue<List>(TransactionsKey))
: ImmutableArray<Transaction<T>>.Empty;
public static Block<T> UnmarshalBlock<T>(
HashAlgorithmGetter hashAlgorithmGetter,
Dictionary marshaled
)
where T : IAction, new()
{
BlockHeader header = UnmarshalBlockHeader(
hashAlgorithmGetter,
marshaled.GetValue<Dictionary>(HeaderKey)
);
IReadOnlyList<Transaction<T>> txs = UnmarshalBlockTransactions<T>(marshaled);
return new Block<T>(header, txs);
}
}
}