-
Notifications
You must be signed in to change notification settings - Fork 2
/
BlockChain.cpp
5835 lines (5189 loc) · 167 KB
/
BlockChain.cpp
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "BlockChain.h"
#include "Base58.h"
#include "BitcoinAddress.h"
#include "HeapSort.h"
#include "RIPEMD160.h"
#include "SHA256.h"
#include "SimpleHash.h"
//
// Written by John W. Ratcliff : mailto: [email protected]
//
// Website: http://codesuppository.blogspot.com/
//
// Source contained in this project includes portions of source code from other open source projects; though that source may have
// been modified to be included here. Original notices are left in where appropriate.
//
// Some of the hash and bignumber implementations are based on source code find in the 'cbitcoin' project; though it has been modified here to remove all memory allocations.
//
// http://cbitcoin.com/
//
// If you find this code snippet useful; you can tip me at this bitcoin address:
//
// BITCOIN TIP JAR: "1NY8SuaXfh8h5WHd4QnYwpgL1mNu9hHVBT"
//
#ifdef _MSC_VER // Disable the stupid ass absurd warning messages from Visual Studio telling you that using stdlib and stdio is 'not valid ANSI C'
#pragma warning(disable:4996)
#pragma warning(disable:4718)
#endif
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
// Note, to minimize dynamic memory allocation this parser pre-allocates memory for the maximum ever expected number
// of bitcoin addresses, transactions, inputs, outputs, and blocks.
// The numbers here are large enough to read the entire blockchain as of January 1, 2014 with a fair amount of room to grow.
// However, they will need to be increased over time as the blockchain grows.
// Dynamic memory allocation isn't free, every time you dynamically allocate memory there is a significant overhead; so by pre-allocating
// all of the memory needed into one contiguous block you actually save an enormous amount of memory overall and also make the code run
// orders of magnitude faster.
#define SMALL_MEMORY_PROFILE 0 // a debug option so I can run/test the code on a small memory configuration machine If this is
static uint32_t ZOMBIE_DAYS=365*3;
#if SMALL_MEMORY_PROFILE
// Enough memory to process the first 200,000 blocks, useful for testing.
#define MAX_BITCOIN_ADDRESSES 14000000 //
#define MAX_TOTAL_TRANSACTIONS 14000000 //
#define MAX_TOTAL_INPUTS 45000000 //
#define MAX_TOTAL_OUTPUTS 45000000 //
#define MAX_TOTAL_BLOCKS 300000 //
#else
#define MAX_BITCOIN_ADDRESSES 70000000 // 60 million unique addresses.
#define MAX_TOTAL_TRANSACTIONS 90000000 // 90 million transactions.
#define MAX_TOTAL_INPUTS 350000000 // 260 million inputs.
#define MAX_TOTAL_OUTPUTS 350000000 // 260 million outputs
#define MAX_TOTAL_BLOCKS 600000 // 600,000 blocks.
#endif
#define MAX_PLOT_COUNT 2000000
// Some globals for error reporting.
static uint32_t gBlockTime=0;
static uint32_t gBlockIndex=0;
static uint32_t gTransactionIndex=0;
//static uint8_t gTransactionHash[256];
static uint32_t gOutputIndex=0;
static bool gIsWarning=false;
static FILE *gWeirdSignatureFile=NULL;
static FILE *gAsciiSignatureFile=NULL;
static FILE *gLogFile=NULL;
static bool gReportTransactionHash=false;
static bool gDumpBlock=false;
static const char *gDummyKeyAscii = "1BadkEyPaj5oW2Uw4nY5BkYbPRYyTyqs9A";
static uint8_t gDummyKey[25];
static const char *gZeroByteAscii = "1zeroBTYRExUcufrTkwg27LsAvrhehtCJ";
static uint8_t gZeroByte[25];
static bool inline isASCII(char c)
{
bool ret = false;
if ( (c >= 32 && c < 127) || c == 13 )
{
ret = true;
}
return ret;
}
static const char *getDateString(time_t t)
{
static char scratch[1024];
struct tm *gtm = gmtime(&t);
// strftime(scratch, 1024, "%m, %d, %Y", gtm);
sprintf(scratch,"%4d-%02d-%02d", gtm->tm_year+1900, gtm->tm_mon+1, gtm->tm_mday );
return scratch;
}
static void logMessage(const char *fmt,...)
{
char wbuff[2048];
va_list arg;
va_start( arg, fmt );
vsprintf(wbuff,fmt, arg);
va_end(arg);
printf("%s",wbuff);
if ( gLogFile == NULL )
{
gLogFile = fopen("blockchain.txt", "wb");
}
if ( gLogFile )
{
fprintf(gLogFile,"%s", wbuff );
fflush(gLogFile);
}
}
class Hash256
{
public:
Hash256(void)
{
mWord0 = 0;
mWord1 = 0;
mWord2 = 0;
mWord3 = 0;
}
Hash256(const Hash256 &h)
{
mWord0 = h.mWord0;
mWord1 = h.mWord1;
mWord2 = h.mWord2;
mWord3 = h.mWord3;
}
inline Hash256(const uint8_t *src)
{
mWord0 = *(const uint64_t *)(src);
mWord1 = *(const uint64_t *)(src+8);
mWord2 = *(const uint64_t *)(src+16);
mWord3 = *(const uint64_t *)(src+24);
}
inline uint32_t getHash(void) const
{
const uint32_t *h = (const uint32_t *)&mWord0;
return h[0] ^ h[1] ^ h[2] ^ h[3] ^ h[4] ^ h[5] ^ h[6] ^ h[7];
}
inline bool operator==(const Hash256 &h) const
{
return mWord0 == h.mWord0 && mWord1 == h.mWord1 && mWord2 == h.mWord2 && mWord3 == h.mWord3;
}
uint64_t mWord0;
uint64_t mWord1;
uint64_t mWord2;
uint64_t mWord3;
};
static void printReverseHash(const uint8_t *hash)
{
if ( hash )
{
for (uint32_t i=0; i<32; i++)
{
logMessage("%02x", hash[31-i] );
}
}
else
{
logMessage("NULL HASH");
}
}
static void fprintReverseHash(FILE *fph,const uint8_t *hash)
{
if ( hash )
{
for (uint32_t i=0; i<32; i++)
{
fprintf(fph,"%02x", hash[31-i] );
}
}
else
{
fprintf(fph,"NULL HASH");
}
}
class BlockHeader : public Hash256
{
public:
BlockHeader(void)
{
mFileIndex = 0;
mFileOffset = 0;
mBlockLength = 0;
}
BlockHeader(const Hash256 &h) : Hash256(h)
{
mFileIndex = 0;
mFileOffset = 0;
mBlockLength = 0;
}
uint32_t mFileIndex;
uint32_t mFileOffset;
uint32_t mBlockLength;
uint8_t mPreviousBlockHash[32];
};
struct BlockPrefix
{
uint32_t mVersion; // The block version number.
uint8_t mPreviousBlock[32]; // The 32 byte (256 bit) hash of the previous block in the blockchain
uint8_t mMerkleRoot[32]; // The 32 bye merkle root hash
uint32_t mTimeStamp; // The block time stamp
uint32_t mBits; // The block bits field.
uint32_t mNonce; // The block random number 'nonce' field.
};
static const char *getTimeString(uint32_t timeStamp)
{
if ( timeStamp == 0 )
{
return "NEVER";
}
static char scratch[1024];
time_t t(timeStamp);
struct tm *gtm = gmtime(&t);
strftime(scratch, 1024, "%m/%d/%Y %H:%M:%S", gtm);
return scratch;
}
#define MAXNUMERIC 32 // JWR support up to 16 32 character long numeric formated strings
#define MAXFNUM 16
static char gFormat[MAXNUMERIC*MAXFNUM];
static int32_t gIndex=0;
static const char * formatNumber(int32_t number) // JWR format this integer into a fancy comma delimited string
{
char * dest = &gFormat[gIndex*MAXNUMERIC];
gIndex++;
if ( gIndex == MAXFNUM ) gIndex = 0;
char scratch[512];
#ifdef _MSC_VER
itoa(number,scratch,10);
#else
snprintf(scratch, 10, "%d", number);
#endif
char *source = scratch;
char *str = dest;
uint32_t len = (uint32_t)strlen(scratch);
if ( scratch[0] == '-' )
{
*str++ = '-';
source++;
len--;
}
for (uint32_t i=0; i<len; i++)
{
int32_t place = (len-1)-i;
*str++ = source[i];
if ( place && (place%3) == 0 ) *str++ = ',';
}
*str = 0;
return dest;
}
class FileLocation : public Hash256
{
public:
FileLocation(void)
{
}
FileLocation(const Hash256 &h,uint32_t fileIndex,uint32_t fileOffset,uint32_t fileLength,uint32_t transactionIndex) : Hash256(h)
{
mFileIndex = fileIndex;
mFileOffset = fileOffset;
mFileLength = fileLength;
mTransactionIndex = transactionIndex;
}
uint32_t mFileIndex;
uint32_t mFileOffset;
uint32_t mFileLength;
uint32_t mTransactionIndex;
};
typedef SimpleHash< FileLocation, 4194304, MAX_TOTAL_TRANSACTIONS > TransactionHashMap;
typedef SimpleHash< BlockHeader, 4194304, MAX_TOTAL_BLOCKS > BlockHeaderMap;
enum ScriptOpcodes
{
OP_0 = 0x00,
OP_PUSHDATA1 = 0x4c,
OP_PUSHDATA2 = 0x4d,
OP_PUSHDATA4 = 0x4e,
OP_1NEGATE = 0x4f,
OP_RESERVED = 0x50,
OP_1 = 0x51,
OP_2 = 0x52,
OP_3 = 0x53,
OP_4 = 0x54,
OP_5 = 0x55,
OP_6 = 0x56,
OP_7 = 0x57,
OP_8 = 0x58,
OP_9 = 0x59,
OP_10 = 0x5a,
OP_11 = 0x5b,
OP_12 = 0x5c,
OP_13 = 0x5d,
OP_14 = 0x5e,
OP_15 = 0x5f,
OP_16 = 0x60,
OP_NOP = 0x61,
OP_VER = 0x62,
OP_IF = 0x63,
OP_NOTIF = 0x64,
OP_VERIF = 0x65,
OP_VERNOTIF = 0x66,
OP_ELSE = 0x67,
OP_ENDIF = 0x68,
OP_VERIFY = 0x69,
OP_RETURN = 0x6a,
OP_TOALTSTACK = 0x6b,
OP_FROMALTSTACK = 0x6c,
OP_2DROP = 0x6d,
OP_2DUP = 0x6e,
OP_3DUP = 0x6f,
OP_2OVER = 0x70,
OP_2ROT = 0x71,
OP_2SWAP = 0x72,
OP_IFDUP = 0x73,
OP_DEPTH = 0x74,
OP_DROP = 0x75,
OP_DUP = 0x76,
OP_NIP = 0x77,
OP_OVER = 0x78,
OP_PICK = 0x79,
OP_ROLL = 0x7a,
OP_ROT = 0x7b,
OP_SWAP = 0x7c,
OP_TUCK = 0x7d,
OP_CAT = 0x7e, // Currently disabled
OP_SUBSTR = 0x7f, // Currently disabled
OP_LEFT = 0x80, // Currently disabled
OP_RIGHT = 0x81, // Currently disabled
OP_SIZE = 0x82, // Currently disabled
OP_INVERT = 0x83, // Currently disabled
OP_AND = 0x84, // Currently disabled
OP_OR = 0x85, // Currently disabled
OP_XOR = 0x86, // Currently disabled
OP_EQUAL = 0x87,
OP_EQUALVERIFY = 0x88,
OP_RESERVED1 = 0x89,
OP_RESERVED2 = 0x8a,
OP_1ADD = 0x8b,
OP_1SUB = 0x8c,
OP_2MUL = 0x8d, // Currently disabled
OP_2DIV = 0x8e, // Currently disabled
OP_NEGATE = 0x8f,
OP_ABS = 0x90,
OP_NOT = 0x91,
OP_0NOTEQUAL = 0x92,
OP_ADD = 0x93,
OP_SUB = 0x94,
OP_MUL = 0x95, // Currently disabled
OP_DIV = 0x96, // Currently disabled
OP_MOD = 0x97, // Currently disabled
OP_LSHIFT = 0x98, // Currently disabled
OP_RSHIFT = 0x99, // Currently disabled
OP_BOOLAND = 0x9a,
OP_BOOLOR = 0x9b,
OP_NUMEQUAL = 0x9c,
OP_NUMEQUALVERIFY = 0x9d,
OP_NUMNOTEQUAL = 0x9e,
OP_LESSTHAN = 0x9f,
OP_GREATERTHAN = 0xa0,
OP_LESSTHANOREQUAL = 0xa1,
OP_GREATERTHANOREQUAL = 0xa2,
OP_MIN = 0xa3,
OP_MAX = 0xa4,
OP_WITHIN = 0xa5,
OP_RIPEMD160 = 0xa6,
OP_SHA1 = 0xa7,
OP_SHA256 = 0xa8,
OP_HASH160 = 0xa9,
OP_HASH256 = 0xaa,
OP_CODESEPARATOR = 0xab,
OP_CHECKSIG = 0xac,
OP_CHECKSIGVERIFY = 0xad,
OP_CHECKMULTISIG = 0xae,
OP_CHECKMULTISIGVERIFY = 0xaf,
OP_NOP1 = 0xb0,
OP_NOP2 = 0xb1,
OP_NOP3 = 0xb2,
OP_NOP4 = 0xb3,
OP_NOP5 = 0xb4,
OP_NOP6 = 0xb5,
OP_NOP7 = 0xb6,
OP_NOP8 = 0xb7,
OP_NOP9 = 0xb8,
OP_NOP10 = 0xb9,
OP_SMALLINTEGER = 0xfa,
OP_PUBKEYS = 0xfb,
OP_PUBKEYHASH = 0xfd,
OP_PUBKEY = 0xfe,
OP_INVALIDOPCODE = 0xff
};
#define MAGIC_ID 0xD9B4BEF9
#define ONE_BTC 100000000
#define ONE_MBTC (ONE_BTC/1000)
#define MAX_BLOCK_FILES 512 // As of July 6, 2013 there are only about 70 .dat files; so it will be a long time before this overflows
// These defines set the limits this parser expects to ever encounter on the blockchain data stream.
// In a debug build there are asserts to make sure these limits are never exceeded.
// These limits work for the blockchain current as of July 1, 2013.
// The limits can be revised when and if necessary.
#define MAX_BLOCK_SIZE (1024*1024)*10 // never expect to have a block larger than 10mb
#define MAX_BLOCK_TRANSACTION 8192 // never expect more than 8192 transactions per block.
#define MAX_BLOCK_INPUTS 32768 // never expect more than 8192 total inputs
#define MAX_BLOCK_OUTPUTS 32768 // never expect more than 8192 total outputs
#define MAX_REASONABLE_SCRIPT_LENGTH (1024*32) // would never expect any script to be more than 16k in size; that would be very unusual!
#define MAX_REASONABLE_INPUTS 8192 // really can't imagine any transaction ever having more than 8192 inputs
#define MAX_REASONABLE_OUTPUTS 8192 // really can't imagine any transaction ever having more than 8192 outputs
class SignatureStat
{
public:
SignatureStat(void)
{
mFlags = 0;
mCount = 0;
mValue = 0;
}
uint32_t mFlags;
uint32_t mCount;
uint64_t mValue;
};
#define MAX_SIGNATURE_STAT 256
static uint32_t gSignatureStatCount=0;
static SignatureStat gSignatureStats[MAX_SIGNATURE_STAT];
//********************************************
//********************************************
#define MAX_TRANSACTION_STAT 30000000
class TransactionBlockStat
{
public:
TransactionBlockStat(void)
{
mValues = NULL;
init();
}
~TransactionBlockStat(void)
{
delete []mValues;
}
void init(void)
{
mBlockCount = 0;
mBlockSize = 0;
mTransactionCount = 0;
mTransactionSize = 0;
mInputCount = 0;
mOutputCount = 0;
mCoinBaseValue = 0;
mInputValue = 0;
mOutputValue = 0;
mFeeValue = 0;
mDustCount = 0;
}
uint32_t mBlockCount;
uint32_t mBlockSize;
uint32_t mTransactionCount;
uint32_t mTransactionSize;
uint32_t mInputCount;
uint32_t mOutputCount;
uint64_t mCoinBaseValue;
uint64_t mInputValue;
uint64_t mOutputValue;
uint64_t mFeeValue;
uint64_t *mValues;
uint32_t mDustCount;
};
class BlockImpl : public BlockChain::Block
{
public:
// Read one byte from the block-chain input stream.
inline uint8_t readU8(void)
{
assert( (mBlockRead+sizeof(uint8_t)) <= mBlockEnd );
uint8_t ret = *(uint8_t *)mBlockRead;
mBlockRead+=sizeof(uint8_t);
return ret;
}
// Read two bytes from the block-chain input stream.
inline uint16_t readU16(void)
{
assert( (mBlockRead+sizeof(uint16_t)) <= mBlockEnd );
uint16_t ret = *(uint16_t *)mBlockRead;
mBlockRead+=sizeof(uint16_t);
return ret;
}
// Read four bytes from the block-chain input stream.
inline uint32_t readU32(void)
{
assert( (mBlockRead+sizeof(uint32_t)) <= mBlockEnd );
uint32_t ret = *(uint32_t *)mBlockRead;
mBlockRead+=sizeof(uint32_t);
return ret;
}
// Read eight bytes from the block-chain input stream.
inline uint64_t readU64(void)
{
assert( (mBlockRead+sizeof(uint64_t)) <= mBlockEnd );
uint64_t ret = *(uint64_t *)mBlockRead;
mBlockRead+=sizeof(uint64_t);
return ret;
}
// Return the current stream pointer representing a 32byte hash and advance the read pointer accordingly
inline const uint8_t *readHash(void)
{
const uint8_t *ret = mBlockRead;
assert( (mBlockRead+32) <= mBlockEnd );
mBlockRead+=32;
return ret;
}
// reads a variable length integer.
// See the documentation from here: https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
inline uint32_t readVariableLengthInteger(void)
{
uint32_t ret = 0;
uint8_t v = readU8();
if ( v < 0xFD ) // If it's less than 0xFD use this value as the unsigned integer
{
ret = (uint32_t)v;
}
else
{
uint16_t v = readU16();
if ( v < 0xFFFF )
{
ret = (uint32_t)v;
}
else
{
uint32_t v = readU32();
if ( v < 0xFFFFFFFF )
{
ret = (uint32_t)v;
}
else
{
assert(0); // never expect to actually encounter a 64bit integer in the block-chain stream; it's outside of any reasonable expected value
uint64_t v = readU64();
ret = (uint32_t)v;
}
}
}
return ret;
}
// Get the current read buffer address and advance the stream buffer by this length; used to get the address of input/output scripts
inline const uint8_t * getReadBufferAdvance(uint32_t readLength)
{
const uint8_t *ret = mBlockRead;
mBlockRead+=readLength;
assert( mBlockRead <= mBlockEnd );
return ret;
}
// Read a transaction input
bool readInput(BlockChain::BlockInput &input)
{
bool ret = true;
input.transactionHash = readHash(); // read the transaction hash
input.transactionIndex = readU32(); // read the transaction index
input.responseScriptLength = readVariableLengthInteger(); // read the length of the script
assert( input.responseScriptLength < MAX_REASONABLE_SCRIPT_LENGTH );
if ( input.responseScriptLength >= 8192 )
{
logMessage("Block: %d : Unreasonably large input script length of %d bytes.\r\n", gBlockIndex, input.responseScriptLength );
}
if ( input.responseScriptLength < MAX_REASONABLE_SCRIPT_LENGTH )
{
input.responseScript = input.responseScriptLength ? getReadBufferAdvance(input.responseScriptLength) : NULL; // get the script buffer pointer; and advance the read location
input.sequenceNumber = readU32();
}
else
{
logMessage("Block %d : Outrageous sized input script of %d bytes! Shutting down.\r\n", gBlockIndex, input.responseScriptLength );
exit(1);
}
return ret;
}
void getAsciiAddress(BlockChain::BlockOutput &o)
{
o.asciiAddress[0] = 0;
char temp[256];
switch ( o.keyType )
{
case BlockChain::KT_MULTISIG:
sprintf(o.asciiAddress,"MultiSig[%d]",o.signatureCount );
break;
case BlockChain::KT_STEALTH:
strcat(o.asciiAddress,"*STEALTH*");
break;
case BlockChain::KT_SCRIPT_HASH:
strcat(o.asciiAddress,"*SCRIPT_HASH*");
break;
default:
break;
}
for (uint32_t i=0; i<MAX_MULTISIG; i++)
{
if ( o.publicKey[i] )
{
if ( i )
{
strcat(o.asciiAddress,":");
}
bitcoinAddressToAscii(o.addresses[i].address,temp,256);
strcat(o.asciiAddress,temp);
}
else
{
break;
}
}
// If this is a multi-sig address, *then* we need to generate a multisig address for it.
if ( o.keyType == BlockChain::KT_MULTISIG )
{
uint8_t hash[20];
computeRIPEMD160(&o.addresses,25*MAX_MULTISIG,hash);
bitcoinRIPEMD160ToAddress(hash,o.multisig.address);
}
}
const char * getKeyType(BlockChain::KeyType k)
{
const char *ret = "UNKNOWN";
switch ( k )
{
case BlockChain::KT_RIPEMD160:
ret = "RIPEMD160";
break;
case BlockChain::KT_UNCOMPRESSED_PUBLIC_KEY:
ret = "UNCOMPRESSED_PUBLIC_KEY";
break;
case BlockChain::KT_COMPRESSED_PUBLIC_KEY:
ret = "COMPRESSED_PUBLIC_KEY";
break;
case BlockChain::KT_TRUNCATED_COMPRESSED_KEY:
ret = "TRUNCATED_COMPRESSED_KEY";
break;
case BlockChain::KT_MULTISIG:
ret = "MULTISIG";
break;
case BlockChain::KT_STEALTH:
ret = "STEALTH";
break;
case BlockChain::KT_ZERO_LENGTH:
ret = "ZERO_LENGTH";
break;
case BlockChain::KT_SCRIPT_HASH:
ret = "SCRIPT_HASH";
break;
default:
break;
}
return ret;
}
// Read an output block
bool readOutput(BlockChain::BlockOutput &output)
{
bool ret = true;
new ( &output ) BlockChain::BlockOutput;
output.value = readU64(); // Read the value of the transaction
blockReward+=output.value;
output.challengeScriptLength = readVariableLengthInteger();
assert ( output.challengeScriptLength < MAX_REASONABLE_SCRIPT_LENGTH );
if ( output.challengeScriptLength >= 8192 )
{
logMessage("Block %d : Unreasonably large output script length of %d bytes.\r\n", gBlockIndex, output.challengeScriptLength );
}
else if ( output.challengeScriptLength > MAX_REASONABLE_SCRIPT_LENGTH )
{
logMessage("Block %d : output script too long %d bytes!\r\n", gBlockIndex, output.challengeScriptLength );
exit(1);
}
output.challengeScript = output.challengeScriptLength ? getReadBufferAdvance(output.challengeScriptLength) : NULL; // get the script buffer pointer and advance the read location
if ( output.challengeScript )
{
uint8_t lastInstruction = output.challengeScript[output.challengeScriptLength-1];
if ( output.challengeScriptLength == 67 && output.challengeScript[0] == 65 && output.challengeScript[66]== OP_CHECKSIG )
{
output.publicKey[0] = output.challengeScript+1;
output.keyType = BlockChain::KT_UNCOMPRESSED_PUBLIC_KEY;
}
if ( output.challengeScriptLength == 40 && output.challengeScript[0] == OP_RETURN )
{
output.publicKey[0] = &output.challengeScript[1];
output.keyType = BlockChain::KT_STEALTH;
}
else if ( output.challengeScriptLength == 66 && output.challengeScript[65]== OP_CHECKSIG )
{
output.publicKey[0] = output.challengeScript;
output.keyType = BlockChain::KT_UNCOMPRESSED_PUBLIC_KEY;
}
else if ( output.challengeScriptLength == 35 && output.challengeScript[34] == OP_CHECKSIG )
{
output.publicKey[0] = &output.challengeScript[1];
output.keyType = BlockChain::KT_COMPRESSED_PUBLIC_KEY;
}
else if ( output.challengeScriptLength == 33 && output.challengeScript[0] == 0x20 )
{
output.publicKey[0] = &output.challengeScript[1];
output.keyType = BlockChain::KT_TRUNCATED_COMPRESSED_KEY;
}
else if ( output.challengeScriptLength == 23 &&
output.challengeScript[0] == OP_HASH160 &&
output.challengeScript[1] == 20 &&
output.challengeScript[22] == OP_EQUAL )
{
output.publicKey[0] = output.challengeScript+2;
output.keyType = BlockChain::KT_SCRIPT_HASH;
}
else if ( output.challengeScriptLength >= 25 &&
output.challengeScript[0] == OP_DUP &&
output.challengeScript[1] == OP_HASH160 &&
output.challengeScript[2] == 20 )
{
output.publicKey[0] = output.challengeScript+3;
output.keyType = BlockChain::KT_RIPEMD160;
}
else if ( output.challengeScriptLength == 5 &&
output.challengeScript[0] == OP_DUP &&
output.challengeScript[1] == OP_HASH160 &&
output.challengeScript[2] == OP_0 &&
output.challengeScript[3] == OP_EQUALVERIFY &&
output.challengeScript[4] == OP_CHECKSIG )
{
logMessage("WARNING: Unusual but expected output script. Block %s : Transaction: %s : OutputIndex: %s\r\n", formatNumber(gBlockIndex), formatNumber(gTransactionIndex), formatNumber(gOutputIndex) );
gIsWarning = true;
}
else if ( lastInstruction == OP_CHECKMULTISIG && output.challengeScriptLength > 25 ) // looks to be a multi-sig
{
const uint8_t *scanBegin = output.challengeScript;
const uint8_t *scanEnd = &output.challengeScript[output.challengeScriptLength-2];
bool expectedPrefix = false;
bool expectedPostfix = false;
switch ( *scanBegin )
{
case OP_0:
case OP_1:
case OP_2:
case OP_3:
case OP_4:
case OP_5:
expectedPrefix = true;
break;
default:
// assert(0); // unexpected
break;
}
switch ( *scanEnd )
{
case OP_1:
case OP_2:
case OP_3:
case OP_4:
case OP_5:
expectedPostfix = true;
break;
default:
// assert(0); // unexpected
break;
}
if ( expectedPrefix && expectedPostfix )
{
scanBegin++;
uint32_t keyIndex = 0;
while ( keyIndex < 5 && scanBegin < scanEnd )
{
if ( *scanBegin == 0x21 )
{
output.keyType = BlockChain::KT_MULTISIG;
scanBegin++;
output.publicKey[keyIndex] = scanBegin;
scanBegin+=0x21;
uint32_t bitMask = 1<<keyIndex;
output.multiSigFormat|=bitMask; // turn this bit on if it is in compressed format
keyIndex++;
}
else if ( *scanBegin == 0x41 )
{
output.keyType = BlockChain::KT_MULTISIG;
scanBegin++;
output.publicKey[keyIndex] = scanBegin;
scanBegin+=0x41;
keyIndex++;
}
else
{
break; //
}
}
}
if ( output.publicKey[0] == NULL )
{
logMessage("****MULTI_SIG WARNING: Unable to decipher multi-sig output. Block %s : Transaction: %s : OutputIndex: %s\r\n", formatNumber(gBlockIndex), formatNumber(gTransactionIndex), formatNumber(gOutputIndex) );
gIsWarning = true;
}
}
else
{
// Ok..we are going to scan for this pattern.. OP_DUP, OP_HASH160, 0x14 then exactly 20 bytes after 0x88,0xAC
// 25...
if ( output.challengeScriptLength > 25 )
{
uint32_t endIndex = output.challengeScriptLength-25;
for (uint32_t i=0; i<endIndex; i++)
{
const uint8_t *scan = &output.challengeScript[i];
if ( scan[0] == OP_DUP &&
scan[1] == OP_HASH160 &&
scan[2] == 20 &&
scan[23] == OP_EQUALVERIFY &&
scan[24] == OP_CHECKSIG )
{
output.publicKey[0] = &scan[3];
output.keyType = BlockChain::KT_RIPEMD160;
logMessage("WARNING: Unusual output script. Block %s : Transaction: %s : OutputIndex: %s\r\n", formatNumber(gBlockIndex), formatNumber(gTransactionIndex), formatNumber(gOutputIndex) );
gIsWarning = true;
break;
}
}
}
}
if ( output.publicKey[0] == NULL )
{
logMessage("==========================================\r\n");
logMessage("FAILED TO LOCATE PUBLIC KEY\r\n");
logMessage("ChallengeScriptLength: %d bytes long\r\n", output.challengeScriptLength );
for (uint32_t i=0; i<output.challengeScriptLength; i++)
{
logMessage("%02x ", output.challengeScript[i] );
if ( ((i+16)&15) == 0 )
{
logMessage("\r\n");
}
}
logMessage("\r\n");
logMessage("==========================================\r\n");
logMessage("\r\n");
}
}
else
{
logMessage("Block %d : has a zero byte length output script?\r\n", gBlockIndex);
gReportTransactionHash = true;
}
if ( !output.publicKey[0] )
{
if ( output.challengeScriptLength == 0 )
{
output.publicKey[0] = &gZeroByte[1];
}
else
{
output.publicKey[0] = &gDummyKey[1];
}
output.keyType = BlockChain::KT_RIPEMD160;
logMessage("WARNING: Failed to decode public key in output script. Block %s : Transaction: %s : OutputIndex: %s scriptLength: %s\r\n", formatNumber(gBlockIndex), formatNumber(gTransactionIndex), formatNumber(gOutputIndex), formatNumber(output.challengeScriptLength) );
gReportTransactionHash = true;
gIsWarning = true;
}
switch ( output.keyType )
{
case BlockChain::KT_RIPEMD160:
bitcoinRIPEMD160ToAddress(output.publicKey[0],output.addresses[0].address);
break;
case BlockChain::KT_SCRIPT_HASH:
bitcoinRIPEMD160ToScriptAddress(output.publicKey[0],output.addresses[0].address);
break;
case BlockChain::KT_STEALTH:
bitcoinRIPEMD160ToAddress(output.publicKey[0],output.addresses[0].address);
break;
case BlockChain::KT_UNCOMPRESSED_PUBLIC_KEY:
{
bitcoinPublicKeyToAddress(output.publicKey[0],output.addresses[0].address);
}
break;
case BlockChain::KT_COMPRESSED_PUBLIC_KEY:
{
bitcoinCompressedPublicKeyToAddress(output.publicKey[0],output.addresses[0].address);
}
break;
case BlockChain::KT_TRUNCATED_COMPRESSED_KEY:
{
uint8_t key[33];
key[0] = 0x2;
memcpy(&key,output.publicKey[0],32);
bitcoinCompressedPublicKeyToAddress(key,output.addresses[0].address);
}
break;
case BlockChain::KT_MULTISIG:
{
for (uint32_t i=0; i<MAX_MULTISIG; i++)
{
const uint8_t *key = output.publicKey[i];
if ( key == NULL )
break;
uint32_t mask = 1<<i;
if ( output.multiSigFormat & mask )
{
bitcoinCompressedPublicKeyToAddress(output.publicKey[i],output.addresses[i].address);
}
else
{
bitcoinPublicKeyToAddress(output.publicKey[i],output.addresses[i].address);
}
}
}
break;
default:
break;
}
output.keyTypeName = getKeyType(output.keyType);
getAsciiAddress(output);
// if ( output.keyType == BlockChain::KT_SCRIPT_HASH )
// {
// logMessage("ScriptHash: %s\r\n", output.asciiAddress );
// }
if ( gReportTransactionHash )
{
gIsWarning = true;
}
return ret;
}