-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathBlocksUnit.pas
493 lines (383 loc) · 11.2 KB
/
BlocksUnit.pas
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
unit BlocksUnit;
interface
uses
System.Classes,
System.Contnrs,
Generics.Collections,
SeSHA256;
type
TCrypto = (tcBitcoin);
TNet = (tnMainNet, tnTestNet);
TBlockChainFiles = class;
TBlockFile = class(TObject)
parent: TBlockChainFiles;
aFileName: string;
aBlockNumber: integer;
afs: TBufferedFileStream;
end;
TBlockChainFiles = class(TList<TBlockFile>)
end;
TBlockHeader = record
versionNumber: UInt32;
aPreviousBlockHash: T32; // reverse please
aMerkleRoot: T32; // reverse please
time: UInt32; // UnixTime
DifficultyTarget: UInt32;
nonce: UInt32;
end;
TInput = class(TObject)
aTXID: T32;
aVOUT: UInt32;
CoinBaseLength: uint64;
CoinBase: PByte;
destructor Destroy; override;
end;
TOutput = class(TObject)
nValue: uint64;
OutputScriptLength: uint64;
OutputScript: PByte;
destructor Destroy; override;
end;
TInputs = class(TObjectList)
private
function GetInput(index: integer): TInput;
public
function NewInput: TInput;
property items[index: integer]: TInput read GetInput; default;
end;
TOutputs = class(TObjectList)
private
function GetOutput(index: integer): TOutput;
public
function NewOutput: TOutput;
property items[index: integer]: TOutput read GetOutput; default;
end;
TTransaction = class(TObject)
version: UInt32;
inputs: TInputs;
outputs: TOutputs;
public
constructor Create;
destructor Destroy; override;
end;
TBlockTransactions = class(TObjectList)
private
function GetTransaction(index: integer): TTransaction;
public
function NewTransaction: TTransaction;
property items[index: integer]: TTransaction read GetTransaction; default;
end;
TBlockRecord = class(TObject)
nblock: uint64;
blocktype: TCrypto;
network: TNet;
headerLenght: UInt32;
hash: string;
header: TBlockHeader;
transactions: TBlockTransactions;
ninputs, noutputs: uint64;
public
constructor Create;
destructor Destroy; override;
end;
TStartFileBlockFoundNotify = procedure(const aBlockFiles: TList<String>) of object;
TFoundFileBlockNotify = procedure(const aBlockFile: TBlockFile; var next: boolean) of object;
TEndFilesBlockFoundNotify = procedure(const aBlockFiles: tstringlist) of object;
TFoundBlockNotify = procedure(const aBlock: TBlockRecord; var findnext: boolean) of object;
TBlockProcessStepNotify = procedure(const aPos, asize: int64) of object;
TBlocks = class(tthread)
private
// File block events
fOnStartProcessFiles: TStartFileBlockFoundNotify;
fOnAfterFileBlockProcessed: TFoundFileBlockNotify;
fOnMagicBlockFound: TFoundBlockNotify;
fBlockProcessStep: TBlockProcessStepNotify;
// fEndProcessBlockFile: TEndProcessBlockFile;
fOnEndProc: TNotifyEvent;
fOnStartProc: TNotifyEvent;
fOnBeforeFileBlockProcess: TFoundFileBlockNotify;
procedure InternalProcessBlock(const aBlockFile: TBlockFile);
public
aBlockChainFiles: TBlockChainFiles;
BlocksDir: string;
aBlocksDirectory: string;
procedure Execute; override;
// Inicio y fin del parseo
property OnStartingParsingBlockfiles: TNotifyEvent read fOnStartProc write fOnStartProc;
property OnFinishedParsingBlockFiles: TNotifyEvent read fOnEndProc write fOnEndProc;
// Start process all files
property OnStartProcessFiles: TStartFileBlockFoundNotify read fOnStartProcessFiles write fOnStartProcessFiles;
// before process a file
property OnBeforeFileBlockProcess: TFoundFileBlockNotify read fOnBeforeFileBlockProcess write fOnBeforeFileBlockProcess;
// after a processed file
property OnAfterFileBlockProcessed: TFoundFileBlockNotify read fOnAfterFileBlockProcessed write fOnAfterFileBlockProcessed;
// Block found
property OnMagicBlockFound: TFoundBlockNotify read fOnMagicBlockFound write fOnMagicBlockFound;
property OnBlockProcessStep: TBlockProcessStepNotify read fBlockProcessStep write fBlockProcessStep;
end;
implementation
uses
WinApi.Windows,
SysUtils, dialogs, dateutils,
MainFormUnit, System.hash,
inifiles;
procedure TBlocks.Execute;
var
searchResult: TSearchRec;
aBlockFile: TBlockFile;
aBlockFiles: TList<string>;
aBlockFil: string;
next: boolean;
files: string;
begin
aBlockChainFiles := TBlockChainFiles.Create;
// Start parsing component
if Assigned(OnStartingParsingBlockfiles) then
Synchronize(
procedure
begin
OnStartingParsingBlockfiles(self);
end);
SetCurrentDir(aBlocksDirectory);
files := 'blk?????.dat';
// files := 'blk00074.dat';
if findfirst(files, faAnyFile, searchResult) = 0 then
begin
aBlockFiles := TList<String>.Create;
repeat
aBlockFiles.Add(aBlocksDirectory + '\' + searchResult.Name);
until findnext(searchResult) <> 0;
// Must free up resources used by these successful finds
System.SysUtils.FindClose(searchResult);
// Start parsing all files
if Assigned(OnStartProcessFiles) then
Synchronize(
procedure
begin
OnStartProcessFiles(aBlockFiles);
end);
for aBlockFil in aBlockFiles do
begin
aBlockFile := TBlockFile.Create;
aBlockFile.parent := aBlockChainFiles;
aBlockChainFiles.Add(aBlockFile);
aBlockFile.aFileName := aBlockFil;
aBlockFile.aBlockNumber := aBlockFiles.IndexOf(aBlockFil) + 1;
// Start parsing a file
if Assigned(fOnBeforeFileBlockProcess) then
Synchronize(
procedure
begin
fOnBeforeFileBlockProcess(aBlockFile, next);
end);
aBlockFile.afs := TBufferedFileStream.Create(aBlockFile.aFileName, fmOpenRead);
try
InternalProcessBlock(aBlockFile);
finally
aBlockFile.afs.Free;
end;
if Assigned(OnAfterFileBlockProcessed) then
Synchronize(
procedure
begin
OnAfterFileBlockProcessed(aBlockFile, next);
end);
aBlockFile.Free;
if next = false then
break;
end;
aBlockFiles.Free;
end;
if Assigned(OnFinishedParsingBlockFiles) then
Synchronize(
procedure
begin
OnFinishedParsingBlockFiles(self);
end);
end;
procedure TBlocks.InternalProcessBlock(const aBlockFile: TBlockFile);
var
state, car: byte;
aBlock: TBlockRecord;
cont: boolean;
aTransaction: TTransaction;
aseq: longword;
aInput: TInput;
aOutput: TOutput;
tb: THeader;
var
alocktime: UInt32;
txCount, k: uint64;
function ReadVarValue: uint64;
var
atxCount: UInt8;
atxCount2: UInt16;
atxCount4: UInt32;
begin
aBlockFile.afs.Read(atxCount, 1);
if atxCount < $FD then
result := atxCount
else
case atxCount of
$FD:
begin
aBlockFile.afs.Read(atxCount2, 2);
result := atxCount2;
end;
$FE:
begin
aBlockFile.afs.Read(atxCount4, 4);
result := atxCount4;
end;
$FF:
aBlockFile.afs.Read(result, 8);
end;
end;
begin
state := 0;
cont := true;
while (cont = true) and (aBlockFile.afs.Read(car, 1) = 1) do
begin
case state of
0:
if car = $F9 then
inc(state);
1:
if car = $BE then
inc(state)
else
state := 0;
2:
if car = $B4 then
inc(state)
else
state := 0;
3:
if car = $D9 then
begin
if Assigned(OnBlockProcessStep) then
Synchronize(
procedure
begin
OnBlockProcessStep(aBlockFile.afs.Position, aBlockFile.afs.Size);
end);
aBlock := TBlockRecord.Create;
aBlockFile.afs.Read(aBlock.headerLenght, 4);
// Read the header fields
aBlockFile.afs.Read(aBlock.header, HEADERSIZE);
// Re-read the header to calculate hash
aBlockFile.afs.Seek(-HEADERSIZE, soCurrent);
aBlockFile.afs.Read(tb, HEADERSIZE);
// double header hash
aBlock.hash := reversehash(SHA256ToStr(CalcSHA256(SHA256ToBinaryStr(CalcHeaderSHA256(tb)))));
// tx count
txCount := ReadVarValue;
while (txCount > 0) do
begin
aTransaction := aBlock.transactions.NewTransaction;
// Read the transaction version
aBlockFile.afs.Read(aTransaction.version, 4);
// Read the inputs
aBlock.ninputs := ReadVarValue;
if aBlock.ninputs > 0 then
for k := 0 to aBlock.ninputs - 1 do
begin
aInput := aTransaction.inputs.NewInput;
aBlockFile.afs.Read(aInput.aTXID, 32);
aBlockFile.afs.Read(aInput.aVOUT, 4);
aInput.CoinBaseLength := ReadVarValue;
GetMem(aInput.CoinBase, aInput.CoinBaseLength);
aBlockFile.afs.Read(aInput.CoinBase^, aInput.CoinBaseLength);
// No need store the seq
aBlockFile.afs.Read(aseq, 4);
end;
// tx out count
aBlock.noutputs := ReadVarValue;
if aBlock.noutputs > 0 then
for k := 0 to aBlock.noutputs - 1 do
begin
aOutput := aTransaction.outputs.NewOutput;
aBlockFile.afs.Read(aOutput.nValue, 8); // in satoshis
aOutput.OutputScriptLength := ReadVarValue;
GetMem(aOutput.OutputScript, aOutput.OutputScriptLength);
aBlockFile.afs.Read(aOutput.OutputScript^, aOutput.OutputScriptLength);
end;
aBlockFile.afs.Read(alocktime, 4);
dec(txCount);
end;
// Fire the block found event
if Assigned(OnMagicBlockFound) then
Synchronize(
procedure
begin
OnMagicBlockFound(aBlock, cont);
end);
// Free the block so user must copy or use it and forget
aBlock.Free;
state := 0;
end;
end;
end;
end;
{ TBlockRecord }
constructor TBlockRecord.Create;
begin
transactions := TBlockTransactions.Create;
end;
destructor TBlockRecord.Destroy;
begin
transactions.Free;
inherited;
end;
{ TBlockTransactions }
function TBlockTransactions.GetTransaction(index: integer): TTransaction;
begin
result := inherited items[index] as TTransaction;
end;
function TBlockTransactions.NewTransaction: TTransaction;
begin
result := TTransaction.Create;
self.Add(result);
end;
{ TTransaction }
constructor TTransaction.Create;
begin
inputs := TInputs.Create;
outputs := TOutputs.Create;
end;
destructor TTransaction.Destroy;
begin
inputs.Free;
outputs.Free;
end;
{ TOutputs }
function TOutputs.GetOutput(index: integer): TOutput;
begin
result := TOutput(inherited items[index]);
end;
function TOutputs.NewOutput: TOutput;
begin
result := TOutput.Create;
self.Add(result);
end;
{ TInputs }
function TInputs.GetInput(index: integer): TInput;
begin
result := TInput(inherited items[index]);
end;
function TInputs.NewInput: TInput;
begin
result := TInput.Create;
self.Add(result);
end;
destructor TInput.Destroy;
begin
FreeMem(CoinBase);
inherited;
end;
destructor TOutput.Destroy;
begin
FreeMem(OutputScript);
inherited;
end;
end.